From aboudouvas at panafonet.gr Fri Jan 5 17:03:17 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 5 Jan 2007 14:03:17 -0800 Subject: program deployment In-Reply-To: <1168023319.644237.273240@v33g2000cwv.googlegroups.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> <1168012877.398078.59120@s80g2000cwa.googlegroups.com> <1168013279.634426.84110@s80g2000cwa.googlegroups.com> <1168023319.644237.273240@v33g2000cwv.googlegroups.com> Message-ID: <1168034597.210502.51990@s80g2000cwa.googlegroups.com> > Of course you do not distribute .cs (or .vb) files when deploying your > application, but decompilers for .NET are plenty. Same for Java. Yes, but in .Net we have some strong dotfuscators that makes reverse engineer really difficult. In any way, it is not so easy to get to the source as .py files is. From nmm1 at cus.cam.ac.uk Wed Jan 17 09:24:53 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 17 Jan 2007 14:24:53 GMT Subject: Number methods Message-ID: I can't find any description of these. Most are obvious, but some are not. Note that this is from the point of view of IMPLEMENTING them, not USING them. Specifically: Does Python use classic division (nb_divide) and inversion (nb_invert) or are they entirely historical? Note that I can very easily provide the latter. Is there any documentation on the coercion function (nb_coerce)? It seems to have unusual properties. Thanks for any hints. Regards, Nick Maclaren. From bdesth.quelquechose at free.quelquepart.fr Tue Jan 2 17:22:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Jan 2007 23:22:10 +0100 Subject: array of class In-Reply-To: References: Message-ID: <459ad4f7$0$293$426a34cc@news.free.fr> mm a ?crit : > > How can I do a array of class? s/array/list/ > s1=[] ## this array should hold classes > > ## class definition > class Word: > word="" > > > ## empty words... INIT > for i in range(100): ## 0..99 > s1.append(Wort) I guess that s/Wort/Word/ > s1[0].word="There" > s1[1].word="should" > s1[2].word="be" > s1[3].word="different" > s1[4].word="classes" > > ... but it's not. Err... Are you sure you really understand what's a class is and how it's supposed to be used ? > > print s1 > ------------ > [, > , > , > , > , > , > ........ > ----------- > > Here, this "classes" are all at the same position in memory. Of course. You created a list of 100 references to the same class. > So there > are no different classes in the array. How could it be ? When did you put another class in the list ? > So I access with s1[0], s1[1], s1[2], etc. always the same data. Of course. > Any idea? Yes : read something about OO base concepts like classes and instances, then read the Python's tutorial about how these concepts are implemented in Python. FWIW, I guess that what you want here may looks like this: class Word(object): def __init__(self, word=''): self._word = word def __repr__(self): return "" % (self._word, id(self)) words = [] for w in ['this', 'is', 'probably', 'what', 'you', 'want']: words.append(Word(w)) print words From steve at holdenweb.com Mon Jan 29 08:22:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Jan 2007 13:22:41 +0000 Subject: PythonCard installation In-Reply-To: <1169557284.833325.305590@k78g2000cwa.googlegroups.com> References: <1169557284.833325.305590@k78g2000cwa.googlegroups.com> Message-ID: dudds wrote: > Anyone had any joy with this using FC6?? When I try to run code editor > I get the error "Traceback (most recent call last): > File > "/usr/lib/python2.4/PythonCard-0.8.2/tools/codeEditor/codeEditor.py", > line 13, in ? > from PythonCard import about, configuration, dialog, log, menu, > model, resource, util > ImportError: No module named PythonCard" > This isn't really a platform-specific issue - you just need to install PythonCard so that the interpreter can find it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From berteun at gmail.com Fri Jan 19 09:28:10 2007 From: berteun at gmail.com (Berteun Damman) Date: 19 Jan 2007 06:28:10 -0800 Subject: PQueue and Python 2.5 Message-ID: <1169216890.617239.209170@51g2000cwl.googlegroups.com> Hello, Recently I was looking for a Priority Queue module, and I've found Pqueue by Andrew Snare [1]. When I use it with Python 2.4 everything works okay, at least on the two system I've tested it on (Debian based AMD 64) and OS PPC. However, when I use it with Python 2.5 - again on the same machines, exiting always gives a pointer error. The easiest to demonstrate this is: python2.5 -c 'from pqueue import PQueue; PQueue()' On the Debian system: $ python2.5 -c 'from pqueue import PQueue; PQueue()' *** glibc detected *** free(): invalid pointer: 0x00002ad7b5720288 *** Abort And on my PowerBook: python2.5(8124) malloc: *** Deallocation of a pointer not malloced: 0x3b4218; This could be a double free(), or free() called with the middle of an allocated block; A memory fault can also be immediately triggered by apply 'del' to a PQueue-instance. As said, with Python 2.4 it seems to perform without problems. I haven't got a clue how to investigate this, but I would be willing to help if someone has any ideas. Berteun [1] http://py.vaults.ca/apyllo.py/514463245.769244789.44776582 From paul.sijben at xs4all.nl Wed Jan 10 06:41:38 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 12:41:38 +0100 Subject: maximum number of threads In-Reply-To: References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: <45A4D0F2.40001@xs4all.nl> Gabriel Genellina wrote: > > Simply you can't, as you can't have 10000 open files at once. Computer > resources are not infinite. sure but *how* fast they run out is the issue here > Do you really need so many threads? I might be able to do with a few less but I still need many. I have done a quick test. on WinXP I can create 1030 threads on Fedora Core 6 I can only create 301 (both python2.4 and 2.5) now the 301 is rather low I'd say. Paul From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 15 08:40:02 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 15 Jan 2007 14:40:02 +0100 Subject: python and MOV or MPEG References: <510uf3F1i9oo6U1@mid.uni-berlin.de> Message-ID: <511ehiF1i1c86U1@mid.individual.net> siggi wrote: > Thanks, Diez. I forgot to mention that I am learning Python with > python 2.5 on WinXP. And both pymedia and pygame require somewhat > older versions of python, 1.3 and 2.4, respectively. 1.3? I've found both for 2.4, and in one site's forum some guy offers windows binaries for 2.5. Regards, Bj?rn -- BOFH excuse #303: fractal radiation jamming the backbone From exarkun at divmod.com Tue Jan 23 12:37:37 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 23 Jan 2007 12:37:37 -0500 Subject: smtplib starttls gmail example In-Reply-To: <8yrth.1230$JB.276@trnddc05> Message-ID: <20070123173737.17245.1391816005.divmod.quotient.9037@ohm> On Tue, 23 Jan 2007 17:25:24 GMT, py wrote: >from smtplib import SMTP >from socket import sslerror #if desired >server = SMTP('smtp.gmail.com') >server.set_debuglevel(0) # or 1 for verbosity >server.ehlo('youraddress at gmail.com') >server.starttls() >server.ehlo('youraddress at gmail.com') # say hello again >server.login('youraddress at gmail.com', 'yourpassword') ># i have a suspicion that smptlib does not add the required newline dot newline so i do it myself >server.sendmail('youraddress at gmail.com', 're at cipient.com', message_text + '\n.\n') ># next line generates the ignorable socket.sslerror >server.quit() > Or with Twisted: from twisted.internet.ssl import ClientContextFactory from twisted.internet.defer import Deferred from twisted.mail.smtp import ESMTPSenderFactory from twisted.internet import reactor contextFactory = ClientContextFactory() result = Deferred() factory = ESMTPSenderFactory('youraddress at gmail.com', 'your password', 'youraddress at gmail.com', 're at cipient.com', messageText, contextFactory=contextFactory) reactor.connectTCP('smtp.gmail.com', 25, factory) result.addCallback(lambda ign: reactor.stop()) reactor.run() Jean-Paul From aisaac at american.edu Thu Jan 25 17:54:35 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 25 Jan 2007 22:54:35 GMT Subject: stop script w/o exiting interpreter Message-ID: I'm fairly new to Python and I've lately been running a script at the interpreter while working on it. Sometimes I only want to run the first quarter or half etc. What is the "good" way to do this? Possible ugly hacks include: - stick an undefined name at the desired stop point - comment out the last half I do not like these and assume that I have overlooked the obvious. Thanks, Alan Isaac From postbox.holger at gmx.net Mon Jan 22 08:05:00 2007 From: postbox.holger at gmx.net (Holger) Date: Mon, 22 Jan 2007 14:05:00 +0100 Subject: Frequency spectrum with fft of a real valued array...? References: Message-ID: Hello Robert! Thank you for your tips. They were very useful. Bye Holger Am 11.01.2007, 19:08 Uhr, schrieb Robert Kern : > Holger wrote: > >> What does it mean to me? How do I get to the wanted frequenca >> spectrum??? > > It's packed in the conventional FFT format. Here is a function in numpy > (the > successor to Numeric, which I assume that you are using) that generates > the > corresponding frequencies in the same packed format: > > In [324]: import numpy > > In [325]: numpy.fft.fftfreq? > Type: function > Base Class: > Namespace: Interactive > File: > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/numpy-1.0.2.dev3507-py2.5-macosx-10.4-i386.egg/numpy/fft/helper.py > Definition: numpy.fft.fftfreq(n, d=1.0) > Docstring: > fftfreq(n, d=1.0) -> f > > DFT sample frequencies > > The returned float array contains the frequency bins in > cycles/unit (with zero at the start) given a window length n and a > sample spacing d: > > f = [0,1,...,n/2-1,-n/2,...,-1]/(d*n) if n is even > f = [0,1,...,(n-1)/2,-(n-1)/2,...,-1]/(d*n) if n is odd > > From sjdevnull at yahoo.com Thu Jan 25 14:59:49 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 25 Jan 2007 11:59:49 -0800 Subject: Python does not play well with others In-Reply-To: References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> Message-ID: <1169755188.989078.75510@v33g2000cwv.googlegroups.com> On Jan 25, 12:17 pm, John Nagle wrote: > My main concern is with glue code to major packages. The connections > to OpenSSL, MySQL, and Apache (i.e. mod_python) all exist, but have major > weaknesses. If you're doing web applications, those are standard pieces > which need to work right. There's a tendency to treat those as abandonware > and re-implement them as event-driven systems in Twisted. In the real world I've worked on Python web apps at my last 3 jobs, and they've all used mod_python and either MySQL or Postgres. I haven't had a need to do anything with OpenSSL from Python; all that takes place in the Apache server (possibly with some mod_rewrite rules to ensure that certain pages are only hit from https and so forth). I think the impression that everyone's using some sexy new framework like Django or TurboGears or Pylons on Twisted or lighttpd/wsgi is pretty misleading, especially when it comes to companies with a decent-size existing codebase (we're into the "fairly large" range with about 325,000 lines of Python now--most is independent of the architecture, but it'd still be an administratively sizeable change)--the place I'm at currently is considering moving to apache+wsgi, but that's a smaller change (and one that's been under consideration for months now). From daniele.varrazzo at gmail.com Thu Jan 18 08:06:48 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 18 Jan 2007 05:06:48 -0800 Subject: One more regular expressions question In-Reply-To: <1169121609.571152.214850@11g2000cwr.googlegroups.com> References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> <1169120317.437211.73660@m58g2000cwm.googlegroups.com> <1169121609.571152.214850@11g2000cwr.googlegroups.com> Message-ID: <1169125608.166197.164490@v45g2000cwv.googlegroups.com> Victor Polukcht wrote: > Great thanks. > > You post helped me so much! > > My resulting regexp is: > "(?P^(.*)\s*)\(((?P\d+))\)\s+((?P\d+))" Notice that this way you are including trailing whitespaces in the var1 group. You may want to put the "\s*" outside the parenthesis. mmm... in this case you should make the ".*" in the first group non-greedy. r"^(?P.*?)\s*\(((?P\d+))\)\s+((?P\d+))" does the job. Bye Daniele From gagsl-py at yahoo.com.ar Thu Jan 25 20:39:29 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 22:39:29 -0300 Subject: Pyparsing - Dealing with a Blank Value In-Reply-To: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> References: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> Message-ID: <7.0.1.0.0.20070125223432.047c3dc8@yahoo.com.ar> At Thursday 25/1/2007 22:13, Steve wrote: >I've picked up the PyParsing module and am trying to figure out how to >do a simple parsing of some HTML source code. My specific problem is >dealing with an element that is blank. Sorry for not answering your question exactly, but I'd use BeautifulSoup instead, it works even if the HTML is not well formed. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From skip at pobox.com Tue Jan 2 21:49:09 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 2 Jan 2007 20:49:09 -0600 Subject: Iterate through list two items at a time In-Reply-To: <1167791404.814286.80570@n51g2000cwc.googlegroups.com> References: <1167791404.814286.80570@n51g2000cwc.googlegroups.com> Message-ID: <17819.6565.616462.795230@montanaro.dyndns.org> >> I'm looking for a way to iterate through a list, two (or more) items >> at a time. Basically... >> >> myList = [1,2,3,4,5,6] >> >> I'd like to be able to pull out two items at a time... Dan> def pair_list(list_): Dan> return [list_[i:i+2] for i in xrange(0, len(list_), 2)] Here's another way (seems a bit clearer to me, but each person has their own way of seeing things): >>> import string >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> zip(string.letters[::2], string.letters[1::2]) [('a', 'b'), ('c', 'd'), ..., ('W', 'X'), ('Y', 'Z')] It extends readily to longer groupings: >>> zip(string.letters[::3], string.letters[1::3], string.letters[2::3]) [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ... Obviously, if your lists are long, you can substitute itertools.izip for zip. There's probably some easy way to achieve the same result with itertools.groupby, but I'm out of my experience there... Skip From __peter__ at web.de Thu Jan 4 07:46:25 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Jan 2007 13:46:25 +0100 Subject: Iterate through list two items at a time References: <12pmahqc7kclbfc@corp.supernews.com> <1167882211.696350.271620@s34g2000cwa.googlegroups.com> <1167913980.320964.264860@s34g2000cwa.googlegroups.com> Message-ID: Wade Leftwich wrote: > from itertools import groupby > > def chunk(it, n=0): > if n == 0: > return iter([it]) > def groupfun((x,y)): > return int(x/n) > grouped = groupby(enumerate(it), groupfun) > counted = (y for (x,y) in grouped) > return ((z for (y,z) in x) for x in counted) > >>>> [list(x) for x in chunk(range(10), 3)] > [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] > >>>> [x for x in chunk(range(10), 3)] > [, > , > , > ] Note that all but the last of these generators are useless: >>> chunks = [x for x in chunk(range(10), 3)] >>> [list(x) for x in chunks] [[], [], [], [9]] # did you expect that? Peter From wangshuhao at sina.com Thu Jan 25 01:48:44 2007 From: wangshuhao at sina.com (Wang Shuhao) Date: Thu, 25 Jan 2007 14:48:44 +0800 Subject: sys.path issue in cygwin References: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> <20070124124355.GA1308@tishler.net> <001801c73fc3$f8c410c0$1400a8c0@mytomato> <20070124152304.GA3668@tishler.net> Message-ID: <001101c7404c$dc5468c0$14fd0179@WANGSHUHAO> This is not a problem of Cygwin itself. The root cause of the problem is that I installed both in Win32 version and Cygwin version on my machine. The PYTHONHOME environment variable in Windows point to c:\python24. After remove this environment variable, the Cygwin version python's sys.path become correct. Override the environment variable in Cygwing is also Ok. ----- Original Message ----- From: "Jason Tishler" To: "Wang Shuhao" Cc: "Python-List" Sent: Wednesday, January 24, 2007 11:23 PM Subject: Re: sys.path issue in cygwin > Wang, > > Please keep your replies on-list. > > On Wed, Jan 24, 2007 at 10:28:51PM +0800, Wang Shuhao wrote: >> > Why not use the Python that is part of the standard Cygwin >> > distribution? >> > >> Cause the Cygwin version python has the same problem, that why I try >> to build python from source. > > The above implies that you may have a Cygwin installation problem that > may impact other Cygwin applications too. I recommend taking this > problem to the Cygwin list: > > http://cygwin.com/problems.html > > FWIW, I get the following with the official Cygwin Python version: > > $ python -c 'import sys; print sys.path' > ['', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-cygwin', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages'] > >> But finally I found the solution, the PYTHONHOME environment variable >> controls the content of initial sys.path. Thanks anyway. >> export PYTHONHOME=/usr/localWang Shuhao > > IMO, the above is just a workaround, not a solution. > > Jason > > -- > PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers > Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 > From me at privacy.net Fri Jan 12 21:40:37 2007 From: me at privacy.net (Dan Sommers) Date: Fri, 12 Jan 2007 21:40:37 -0500 Subject: Tools Designing large/complicated applications References: <45a80c9e$0$308$426a74cc@news.free.fr> Message-ID: On Sat, 13 Jan 2007 00:00:20 +0100, Bruno Desthuilliers wrote: > Carl J. Van Arsdall a ?crit : >> For those of you that work on larger applications but still code in >> python... do your development teams use any tools to facilitate the >> design? > Yes : coffee, beer, pizzas, cigarettes, paper napkins, pen, and a good > wiki. It is a well-known fact that the best engineering tools ever invented are the cocktail napkin and the white board. Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From metsakuri at gmail.com Thu Jan 4 02:36:11 2007 From: metsakuri at gmail.com (tonisk) Date: 3 Jan 2007 23:36:11 -0800 Subject: question on creating class In-Reply-To: <1167895677.041759.230190@42g2000cwt.googlegroups.com> References: <1167895677.041759.230190@42g2000cwt.googlegroups.com> Message-ID: <1167896171.288729.159820@51g2000cwl.googlegroups.com> Or if you have required class name in variable, then use: class TestClass: pass globals()[className] = TestClass -- T?nis On Jan 4, 9:27 am, "wcc" wrote: > Hello, > > How do I create a class using a variable as the class name? > > For example, in the code below, I'd like replace the line > > class TestClass(object): > with something like > class eval(className) (object): > > Is it possible? Thanks for your help. > > className = "TestClass" > > class TestClass(object): > def __init__(self): > print "Creating object of TestClass..." > > def method1(self): > print "This is a method." > > if __name__ == "__main__": > o = TestClass() > o.method1() > > -- > wcc From nmm1 at cus.cam.ac.uk Sun Jan 14 07:04:29 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jan 2007 12:04:29 GMT Subject: Rational Numbers References: Message-ID: In article , "Hendrik van Rooyen" writes: |> |> > Financial calculations need decimal FIXED-point, with a precisely |> > specified precision. It is claimed that decimal FLOATING-point |> > helps with providing that, but that claim is extremely dubious. |> > I can explain the problem in as much detail as you want, but would |> > very much rather not. |> |> Ok I will throw in a skewed ball at this point - use integer arithmetic, |> and work in tenths of cents or pennies or whatever, and don't be too |> lazy to do your own print formatting... That's not a skewed ball - that's the traditional way of doing it on systems that don't have fixed-point hardware (and sometimes even when they do). Yes, it's dead easy in a language (like Python) that allows decent encapsulation. The decimal floating-point brigade grossly exaggerate the difficulty of doing that, in order to persuade people that their solution is better. If they admitted the difficulties of using decimal floating-point, and merely said "but, overall, we think it is a better solution", I would disagree but say nothing. Regards, Nick Maclaren. From andre.roberge at gmail.com Sun Jan 28 07:39:04 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 28 Jan 2007 04:39:04 -0800 Subject: Crunchy 0.8 release In-Reply-To: References: <1169932766.450129.259840@k78g2000cwa.googlegroups.com> Message-ID: <1169987944.776274.33600@p10g2000cwp.googlegroups.com> > > I found it a little strange that the top-level directory in the > distribution is called "andre" rather than "crunchy", but that's a very > minor point. Dang! Thanks for pointing this out; I've made the proper change. I had checked out from "my" development branch, as it contained the final changes required for the release. Andr? > > regards > Steve From klibertp at gmail.com Sun Jan 7 21:30:29 2007 From: klibertp at gmail.com (klibertp at gmail.com) Date: 7 Jan 2007 18:30:29 -0800 Subject: C++/Python programmers for a MUD's gamedriver wanted. In-Reply-To: <459fdf8e$0$4849$4c368faf@roadrunner.com> References: <1168102038.680286.73330@42g2000cwt.googlegroups.com> <459fdf8e$0$4849$4c368faf@roadrunner.com> Message-ID: <1168223429.214744.224440@51g2000cwl.googlegroups.com> Paul McGuire wrote: > Have you considered whether the C++ Driver is even necessary? Python's > run-time engine already implements the memory and process management tasks, > and does so in compiled C code (and has been tested and retested by > hundreds, nay thousands, perhaps even millions of Python users). > Interprocess communication can be done using CORBA or Pyro add-ons. > > You may do better by "letting Python be Python" instead of confining it to > limited user graphical and/or text interaction, and then > marshaling/unmarshaling commands and responses to and from the C++ layer. > Before getting too wrapped up in the C++ core/utility layer, get this (or a > prototype) running in pure Python first, measure the performance, and then > reimplement in C/Pyrex/ShedSkin/C++ for the performance-intensive bits. > > -- Paul The idea of writing C++ layer for Python lib seemed to be great, as far as the only programmer involved in the project knows C++ a lot better, than Python - we hoped to start as soon as possible, get the basic services running in few weeks, learning Python 'by the way'. But in the meantime we've realised, that even with much more people developing this project it will surely last for years, so carefull consideration of every little part of it is needed before writing even single line of code. Extreme programming is nice, but we lack of proper skills - instead we have a lot of time. You're right - writing prototype with pure Python seems to be very good idea. If we encounter any performance problems, reimplementing just a part of code would be the best and easiest way to deal with them. Also, using Python in the whole app will result with much cleaner code, the integration between diferent modules will be done in more natural manner. We have to rethink whole app architecture, slowly and precisely. But still, of course, everyone who wants to help is kindly welcomed :) Sorry for my english if I made a mistake somewhere, and thank you for your reply. Piotr Klibert. From mpeters42 at gmail.com Mon Jan 8 03:57:01 2007 From: mpeters42 at gmail.com (Mark Peters) Date: 8 Jan 2007 00:57:01 -0800 Subject: regex question In-Reply-To: <1168246148.673027.13720@38g2000cwa.googlegroups.com> References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> <1168243020.304940.212700@42g2000cwt.googlegroups.com> <1168244922.620428.273260@38g2000cwa.googlegroups.com> <1168245604.911965.248360@11g2000cwr.googlegroups.com> <1168246148.673027.13720@38g2000cwa.googlegroups.com> Message-ID: <1168246621.453688.53850@v33g2000cwv.googlegroups.com> > yes, i suppose you are right. i can't think of a reason i would NEED a > raw string in this situation. It looks from your code that you are trying to remove all occurances of one string from the other. a simple regex way would be to use re.sub() >>> import re >>> a = "abc" >>> b = "debcabbde" >>> re.sub("[" + a + "]","",b) 'dede' From skip at pobox.com Mon Jan 15 22:49:33 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 15 Jan 2007 21:49:33 -0600 Subject: How naive is Python? In-Reply-To: <1168893633.362384.176620@38g2000cwa.googlegroups.com> References: <1168848408.785931.285160@q2g2000cwa.googlegroups.com> <17835.39437.115750.617750@montanaro.dyndns.org> <1168893633.362384.176620@38g2000cwa.googlegroups.com> Message-ID: <17836.19277.938869.961598@montanaro.dyndns.org> >>>>> "John" == John Machin writes: John> skip at pobox.com wrote: John> Sorry, Skip, but I find that very hard to believe. The foo() John> function would take quadratic time if it were merely adding on John> pieces of constant size -- however len(str(i)) is not a constant, John> it is O(log10(i)), so the time should be super-quadratic. >> me> Sorry, I should have pointed out that I'm using the latest version me> of Python. I believe += for strings has been optimized to simply me> extend s when there is only a single reference to it. John> Sorry, I should have pointed out that you need to read up about John> time.time() -- what is its resolution on your box? -- and John> time.clock() and the timeit module. time.time() should be plenty good enough for this particular task on my machine (Mac OSX). time.time() has plenty of resolution: >>> import time >>> t = time.time() ; print time.time()-t 3.79085540771e-05 >>> t = time.time() ; print time.time()-t 5.00679016113e-06 >>> t = time.time() ; print time.time()-t 5.96046447754e-06 >>> t = time.time() ; print time.time()-t 5.00679016113e-06 It's time.clock() on Unix-y systems that is too coarse: >>> t = time.clock() ; print time.clock()-t 0.0 >>> t = time.clock() ; print time.clock()-t 0.0 >>> t = time.clock() ; print time.clock()-t 0.0 >>> t = time.clock() ; print time.clock()-t 0.0 >>> t = time.clock() ; print time.clock()-t 0.0 I ran the size of the loop to 2**24 and still only saw linear growth in the later versions of Python. The machine (my Mac laptop) was otherwise idle. I only reduced the loop length in what I posted before because of the quadratic growth in Python 2.2 and 2.3. It took so long to run my script using 2.2 and 2.3 I made a slight change so that it bailed out of the larger loops: #!/usr/bin/env python from __future__ import division def foo(kcount): s = '' for i in xrange(kcount) : s += str(i) + ' ' import time for i in xrange(5,25): t = time.time() foo(2**i) t = time.time() - t print "2**%d"%i, 2**i, t, t/2**i if t > 200: break I then ran it using this shell command: for v in 2.6 2.5 2.4 2.3 2.2 ; do echo $v time python$v strcopy.py done 2>&1 \ | tee strcopy.out The output is: 2.6 2**5 32 0.000240802764893 7.52508640289e-06 2**6 64 0.000278949737549 4.3585896492e-06 2**7 128 0.000599145889282 4.68082726002e-06 2**8 256 0.00878977775574 3.43350693583e-05 2**9 512 0.00221586227417 4.32785600424e-06 2**10 1024 0.00433588027954 4.23425808549e-06 2**11 2048 0.00897288322449 4.38129063696e-06 2**12 4096 0.0197570323944 4.82349423692e-06 2**13 8192 0.0359501838684 4.38845017925e-06 2**14 16384 0.0721030235291 4.40081930719e-06 2**15 32768 0.146120071411 4.45923069492e-06 2**16 65536 0.292731046677 4.46672129328e-06 2**17 131072 0.692205905914 5.28111195308e-06 2**18 262144 1.20644402504 4.60221872345e-06 2**19 524288 3.34210991859 6.37456878394e-06 2**20 1048576 6.86596488953 6.54789437249e-06 2**21 2097152 10.0534589291 4.79386278585e-06 2**22 4194304 21.4015710354 5.1025321568e-06 2**23 8388608 40.8173680305 4.86580944425e-06 2**24 16777216 84.5512800217 5.039649011e-06 real 2m50.195s user 2m26.258s sys 0m2.998s 2.5 2**5 32 0.000205039978027 6.40749931335e-06 2**6 64 0.000274896621704 4.29525971413e-06 2**7 128 0.000594139099121 4.64171171188e-06 2**8 256 0.00110697746277 4.32413071394e-06 2**9 512 0.00236988067627 4.62867319584e-06 2**10 1024 0.0045051574707 4.39956784248e-06 2**11 2048 0.00938105583191 4.58059366792e-06 2**12 4096 0.0197520256042 4.82227187604e-06 2**13 8192 0.0375790596008 4.58728754893e-06 2**14 16384 0.0780160427094 4.76172135677e-06 2**15 32768 0.148911952972 4.54443215858e-06 2**16 65536 0.307368040085 4.69006408821e-06 2**17 131072 0.703125953674 5.36442530574e-06 2**18 262144 1.22114300728 4.6582908908e-06 2**19 524288 2.62232589722 5.00168971485e-06 2**20 1048576 5.06462287903 4.83000076201e-06 2**21 2097152 10.3055510521 4.9140696774e-06 2**22 4194304 24.6841719151 5.88516519429e-06 2**23 8388608 42.5984380245 5.07812953288e-06 2**24 16777216 89.6156759262 5.34151052989e-06 real 2m58.236s user 2m29.354s sys 0m2.978s 2.4 2**5 32 0.000231981277466 7.24941492081e-06 2**6 64 0.000316858291626 4.95091080666e-06 2**7 128 0.000571966171265 4.46848571301e-06 2**8 256 0.00112700462341 4.40236181021e-06 2**9 512 0.00228881835938 4.47034835815e-06 2**10 1024 0.00619387626648 6.04870729148e-06 2**11 2048 0.00927710533142 4.52983658761e-06 2**12 4096 0.0188140869141 4.593282938e-06 2**13 8192 0.0386338233948 4.71604289487e-06 2**14 16384 0.0761170387268 4.64581535198e-06 2**15 32768 0.153247117996 4.67673089588e-06 2**16 65536 0.306257009506 4.67311110697e-06 2**17 131072 0.724220991135 5.52536766918e-06 2**18 262144 1.23747801781 4.7206040108e-06 2**19 524288 2.69648981094 5.1431461543e-06 2**20 1048576 5.20070004463 4.9597740599e-06 2**21 2097152 10.6776590347 5.09150459038e-06 2**22 4194304 21.149684906 5.04247782374e-06 2**23 8388608 46.8901240826 5.58973837883e-06 2**24 16777216 110.079385042 6.56124264253e-06 real 3m19.593s user 2m32.932s sys 0m3.100s 2.3 2**5 32 0.000223159790039 6.97374343872e-06 2**6 64 0.000349998474121 5.46872615814e-06 2**7 128 0.000737905502319 5.76488673687e-06 2**8 256 0.00150609016418 5.88316470385e-06 2**9 512 0.00307989120483 6.01541250944e-06 2**10 1024 0.00642395019531 6.27338886261e-06 2**11 2048 0.0161211490631 7.87165481597e-06 2**12 4096 0.110109090805 2.68821022473e-05 2**13 8192 0.787949800491 9.61852783803e-05 2**14 16384 3.3133919239 0.000202233393793 2**15 32768 14.3907749653 0.000439171599282 2**16 65536 60.2394678593 0.000919181333302 2**17 131072 295.17253089 0.00225198769294 real 6m15.110s user 1m54.907s sys 3m26.747s 2.2 2**5 32 0.000303030014038 9.46968793869e-06 2**6 64 0.000451803207397 7.05942511559e-06 2**7 128 0.00087308883667 6.82100653648e-06 2**8 256 0.00233697891235 9.12882387638e-06 2**9 512 0.00344800949097 6.73439353704e-06 2**10 1024 0.00730109214783 7.12997280061e-06 2**11 2048 0.017196893692 8.39692074805e-06 2**12 4096 0.112847805023 2.75507336482e-05 2**13 8192 0.840929031372 0.00010265246965 2**14 16384 3.05718898773 0.000186596007552 2**15 32768 13.0093569756 0.000397014067858 2**16 65536 57.9497959614 0.00088424371279 2**17 131072 294.361263037 0.00224579821042 real 6m9.514s user 1m55.257s sys 3m26.943s It's clear that the behavior of the 2.4, 2.5 and 2.6 (cvs) versions is substantially different than the 2.2 and 2.3 versions, and grows linearly as the string length grows. I believe any slight nonlinearity in the 2.4-2.6 versions is just due to quadratic behavior in the Mac's realloc function. Skip From martin at v.loewis.de Fri Jan 5 04:22:35 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Jan 2007 10:22:35 +0100 Subject: When argparse will be in the python standard installation In-Reply-To: <64mdnTE_-5Ff3gDYnZ2dnUVZ_q6vnZ2d@comcast.com> References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> <459C008D.5040404@v.loewis.de> <459CBAC8.9060007@v.loewis.de> <64mdnTE_-5Ff3gDYnZ2dnUVZ_q6vnZ2d@comcast.com> Message-ID: <459e18db$0$17143$9b622d9e@news.freenet.de> Steven Bethard schrieb: > * alias ArgumentParser to OptionParser > * alias add_argument to add_option > * alias Values to Namespace > * alias OptionError and OptionValueError to ArgumentError > * alias add_help= keyword argument of ArgumentParser to add_help_option= > * alias namespace= keyword argument of parse_args to options= Not sure what you mean by "alias": I don't think the argparse names should be retained (unless you feel they describe things better). You don't need to aim for argparse compatibility: users of argparse can continue to use the current (or future) version of argparse as a separate module. > * ArgumentParser.parse_args returns a single namespace object, not an > (options, args) tuple, since argparse handles positional arguments. > This could probably be addressed by adding an __iter__ method to the > Namespace object which would return (self, []) I find that I'm not that familiar with command line arguments :-) To understand that difference, I would have to see examples of both, and why it is better to return a single result. In any case, if the argparse interface is more powerful, and the old interface cannot be emulated transparently, a new interface could be added, with the old one deprecated and phased out (preferably with some conversion guideline). It would be possible to drop the old one in Py3k, I guess. > * argparse uses standard string formatting specifiers, e.g. %(default)s > and %(prog)s instead of optparse's %default and %prog. It could > probably be hacked to support both though. That would be good. > * argparse makes the default value for a "store_true" action False, and > the default value for a "store_false" action True. This is what users > expect, but different from optparse where the default is always None. Could we deprecate "store_false" with no default? It may be that users expect to see True and False, but how can you find out whether the option was given or not afterwards? Alternatively, could the actions become keyword arguments (with the action argument only preserved for backwards compatibility)? E.g. parser.add_option("-v", store_true_into="verbose") parser.add_option("-q", store_false_into="verbose") (same for store, append, count, callback) > * the choices argument is now checked *after* arguments have been > type-converted. This is intentional, so that you can specify, say > xrange(100) instead of ["0", "1", "2", "3", ... "99"]. There is also > no "choices" type anymore since any action can also specify their > choices. As an incompatible change, this could be warned-about if the type is not string, yet the first choice is. Alternatively, we could require users that pass converted values to specify converted_choices=True in 2.6, and warn all users that don't pass a converted_choices flag, and then flip the default in 2.7 and 3.0. Then current users had a quick fix to silence the warning, and new users could drop the extra flag in the future. > I could probably add callback actions by creating an appropriate > Action subclass and registering it. However, any code relying on > parser.{largs,rargs,values} would break because the parsing algorithm > is completely different in argparse. If you can find a way to make callbacks work in the "common case", this flag could be deprecated and removed. > I guess I don't know how to proceed from here. I'm reluctant to start > adding the code necessary to support even the easily solved issues when > the issues that I don't know how to solve seem like they could be deal > breakers. This asks for a PEP. The views above are mine only, others may feel differently. Regards, Martin From dwaizer at noreply.com Thu Jan 18 12:57:56 2007 From: dwaizer at noreply.com (David Waizer) Date: Thu, 18 Jan 2007 12:57:56 -0500 Subject: spidering script Message-ID: <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d@fdn.com> Hello.. I'm looking for a script (perl, python, sh...)or program (such as wget) that will help me get a list of ALL the links on a website. For example ./magicscript.pl www.yahoo.com and outputs it to a file, it would be kind of like a spidering software.. Any suggestions would be appreciated. David From could.net at gmail.com Sun Jan 21 11:52:06 2007 From: could.net at gmail.com (Frank Potter) Date: 21 Jan 2007 08:52:06 -0800 Subject: Is any python like linux shell? Message-ID: <1169398326.510530.180860@51g2000cwl.googlegroups.com> I learned some python in windows. And now I've turned to linux. I read a book and it teaches how to write shell script with bash, but I don't feel like the grammar of bash. Since I know about python, I want to get a linux shell which use python grammar. I searched by google and I found pysh, which is not maintained any more. There's another script named pyshell, which is not likely what I'm searching for. So, will somebody please tell me if there are any python like shells for linux? From smusnmrNOSPAM at yahoo.com Mon Jan 15 03:55:06 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Mon, 15 Jan 2007 09:55:06 +0100 Subject: python and MOV or MPEG Message-ID: Hi all, does Python support MPEG or MOV videoclips? I couldn't find anything about it online. Thank you, Siggi From egooli at gmail.com Sun Jan 28 04:31:48 2007 From: egooli at gmail.com (gooli) Date: 28 Jan 2007 01:31:48 -0800 Subject: Locking access to all data members Message-ID: <1169976708.934441.213770@h3g2000cwc.googlegroups.com> I have a class with a lot of attributes whose objects are accessed from multiple threads. I would like to synchronize the access to all the attributes, i.e. acquire a lock, return the value, release the lock (in a finally clause). Is there a way to do that without turning each attribute into a property and manually wrapping each property with the locking code? How about classes bound with SQLAlchemy? Is it possible to do that for those too? Example of a class I would like to wrap: class Job(object): def __init__(self, itemType): self.id = self.idSequence self.itemType = itemType self.status = "waiting" self.createDate = None self.hostName = None self.progress = 0 self.items = [] From steve at REMOVE.THIS.cybersource.com.au Tue Jan 23 17:17:26 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 24 Jan 2007 09:17:26 +1100 Subject: Overloading assignment operator References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Tue, 23 Jan 2007 19:42:01 +0100, Peter Otten wrote: > Achim Domma wrote: > >> I want to use Python to script some formulas in my application. The user >> should be able to write something like >> >> A = B * C >> >> where A,B,C are instances of some wrapper classes. Overloading * is no >> problem but I cannot overload the assignment of A. I understand that >> this is due to the nature of Python, but is there a trick to work around >> this? > >>>> class D(dict): > ... def __setitem__(self, key, value): > ... print key, "<--", value > ... dict.__setitem__(self, key, value) > ... >>>> namespace = D(B=42, C=24) >>>> exec "A = B * C" in namespace > A <-- 1008 Very clever, except: (1) The Original Poster's requirement was for a "clean syntax" and 'exec "A = B * C" in namespace' is anything but a clean syntax. (2) The O.P. specifies that the syntax is for use by his users. We don't know who these users are, but can you see users getting this right and not ignoring the namespace argument? (3) Even if they do use the namespace argument, how hard is it for the users to break the security of your exec? >>> exec "A = B * C;import os;os.system('ls -l break-something')" in namespace A <-- 1008 os <-- -rw-rw-r-- 1 steve steve 0 Jan 24 08:27 break-something Using exec on user-supplied data is just begging to be p0wned. -- Steven. From robert.kern at gmail.com Mon Jan 29 16:13:25 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 29 Jan 2007 15:13:25 -0600 Subject: python 2.3 module ref In-Reply-To: <6178735.qJi6sMvOM0@teancum> References: <6178735.qJi6sMvOM0@teancum> Message-ID: David Bear wrote: > Since redhat packages python2.3 with their distro (RHEL 4..) I was looking > for a module reference for that version. Looking at python.org I only see > current documentation. > > any pointers to a 2.3 module ref? http://docs.python.org/ Click on "Locate previous versions." http://www.python.org/doc/versions/ Click on "2.3.5" (or whichever microrelease your desire). http://www.python.org/doc/2.3.5/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py at yahoo.com.ar Mon Jan 8 14:19:04 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 16:19:04 -0300 Subject: More Efficient fnmatch.fnmatch for multiple patterns? In-Reply-To: References: <1168279822.921033.267210@v33g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070108161513.05c2d808@yahoo.com.ar> At Monday 8/1/2007 15:55, Wojciech =?ISO-8859-2?Q?Mu=B3a?= wrote: >pats = re.compile('|'.join(fnmatch.translate(p) for p in patterns)) Hmm, fnmatch.translate does not appear in the docs. But it does on the module docstring, and in __all__, so certainly it's supposed to be public. I'll file a bug report. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From austuff at gmail.com Thu Jan 25 01:05:49 2007 From: austuff at gmail.com (aus stuff) Date: Thu, 25 Jan 2007 15:35:49 +0930 Subject: ftplib and retrbinary or retrlines (losing newline characters in my log files) Message-ID: <7d1760310701242205u6e6b4706ja20e3c07406a8064@mail.gmail.com> Hi am successfully downloading my text files and writing them to local files with either ftp.retrlines('RETR ' + fl, fileObj.write)" ftp.retrbinary('RETR ' + fl, fileObj.write) However all my recieved (log) files have lost thier newline characters? Can anyone steer me in the right direction so my 'recieved log' files arent all jumbled into one line? (full code below) any help appreciated :) (excuse my newbie code copying ) Special thanks to the person/s whom originally made this code (found on google) <<<<<<<<>myLogger, "Couldn't find server" ftp.login(userName,passWord ) ftp.cwd(remotePath ) try: #print >>myLogger, "Connecting...", print "Connecting..." if onlyDiff: lFileSet = Set(os.listdir(localPath)) rFileSet = Set(ftp.nlst()) transferList = list(rFileSet - lFileSet) #print >>myLogger, "Missing: " + str(len(transferList)) + ' >>> ', print "Missing: " + str(len(transferList)), else: transferList = ftp.nlst() delMsg = "" filesMoved = 0 for fl in transferList: ttt = '' ttt = str(fl) if string.find(ttt, '.') > 0 : print '\nCopying >>> ' + ttt # create a full local filepath localFile = localPath + fl grabFile = True if grabFile: #open a the local file fileObj = open(localFile, 'wb') # Download the file a chunk at a time using RETR #ftp.retrbinary('RETR ' + fl, fileObj.write) ftp.retrlines('RETR ' + fl, fileObj.write) # Close the file fileObj.close() filesMoved += 1 # Delete the remote file if requested if deleteRemoteFiles: ftp.delete(fl) delMsg = " and Deleted" #print >>myLogger, " and Deleted" #print >>myLogger, "Files Moved" + delMsg + ": " + str(filesMoved) + ' >>> ' + " On " + timeStamp() print "\nFiles Copied " + delMsg + ": " + str(filesMoved) except: #print >>myLogger, "Connection Error - " + timeStamp() print "Connection Error - " ftp.close() # Close FTP connection ftp = None copyFTPFiles("server","uname","pass","remoteDir","localDir") >>>>>>>code end -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Thu Jan 25 20:33:33 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 22:33:33 -0300 Subject: difflib qualm In-Reply-To: <4-CdnZBrjaO4zSTYnZ2dnUVZ_v6tnZ2d@comcast.com> References: <2adc542f0701241805i79b79580y2522ec854e49621d@mail.gmail.com> <4-CdnZBrjaO4zSTYnZ2dnUVZ_v6tnZ2d@comcast.com> Message-ID: <7.0.1.0.0.20070125222947.047c3388@yahoo.com.ar> At Thursday 25/1/2007 21:49, Larry Bates wrote: >Gabriel Genellina wrote: > > At Wednesday 24/1/2007 23:05, Sick Monkey wrote: > > > >> I am trying to write a python script that will compare 2 files which > >> contains names (millions of them). > >> > >> More specifically, I have 2 files (Files1.txt and Files2.txt). > >> Files1.txt contains 180 thousand names and Files2.txt contains 34 > >> million names. > >Put the big list of names in a database and create soundex keys for the names >and make the soundex keys an index so you can search quickly. Databases >are really good at storing data that is searchable via an index. If >you REALLY >need speed you can consider an in-memory database. > >Create soundex keys for each name in your small list and query the database >with this key into the table in the DB that is indexed on soundex keys. >If you get a hit, the key is sufficiently "alike" to be a candidate. I'll >leave the remainder to you. Perhaps there is other information that will >help determine if there is a match? Soundex is only good for English words, and it's almost useless for non-English names, so it must be used with caution if used at all. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From sjmachin at lexicon.net Mon Jan 15 15:40:35 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2007 12:40:35 -0800 Subject: How naive is Python? In-Reply-To: References: <1168848408.785931.285160@q2g2000cwa.googlegroups.com> <17835.39437.115750.617750@montanaro.dyndns.org> Message-ID: <1168893633.362384.176620@38g2000cwa.googlegroups.com> skip at pobox.com wrote: > John> Sorry, Skip, but I find that very hard to believe. The foo() > John> function would take quadratic time if it were merely adding on > John> pieces of constant size -- however len(str(i)) is not a constant, > John> it is O(log10(i)), so the time should be super-quadratic. > > me> Sorry, I should have pointed out that I'm using the latest version > me> of Python. I believe += for strings has been optimized to simply > me> extend s when there is only a single reference to it. Sorry, I should have pointed out that you need to read up about time.time() -- what is its resolution on your box? -- and time.clock() and the timeit module. > > Actually, it isn't until I work my way back to 2.3 that I start to see > quadratic behavior: > > % python2.6 strcopy.py > 32 0.00022292137146 6.96629285812e-06 > 64 0.000907897949219 1.41859054565e-05 > 128 0.000649929046631 5.0775706768e-06 > 256 0.00111794471741 4.36697155237e-06 > 512 0.00260806083679 5.09386882186e-06 > 1024 0.00437998771667 4.27733175457e-06 > 2048 0.00921607017517 4.50003426522e-06 > 4096 0.0191979408264 4.68699727207e-06 > 8192 0.0694131851196 8.47328919917e-06 > 16384 0.0976829528809 5.96209429204e-06 > 32768 0.194766998291 5.94381708652e-06 > % python2.5 strcopy.py > 32 0.000439167022705 1.37239694595e-05 > 64 0.000303030014038 4.73484396935e-06 > 128 0.000631809234619 4.93600964546e-06 > 256 0.00112318992615 4.38746064901e-06 > 512 0.00279307365417 5.45522198081e-06 > 1024 0.00446391105652 4.35928814113e-06 > 2048 0.00953102111816 4.65381890535e-06 > 4096 0.0198018550873 4.83443727717e-06 > 8192 0.175454854965 2.14178289752e-05 > 16384 0.103327989578 6.30663998891e-06 > 32768 0.191411972046 5.84142981097e-06 [snip] Your ability to "see" quadratic behavoiur appears to be impaired by (1) the low resolution and/or erratic nature of time.time() on your system (2) stopping the experiment just before the results become interesting. Try this with the latest *production* release (2.5): C:\junk>cat fookount.py def foo(kcount): s = '' for i in xrange(kcount) : s += str(i) + ' ' C:\junk>for /L %n in (10,1,19) do \python25\python -mtimeit -s"from fookount import foo" "foo(2**%n)" C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**10)" 100 loops, best of 3: 1.1 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**11)" 100 loops, best of 3: 2.34 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**12)" 100 loops, best of 3: 4.79 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**13)" 10 loops, best of 3: 9.57 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**14)" 10 loops, best of 3: 19.8 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**15)" 10 loops, best of 3: 40.7 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**16)" 10 loops, best of 3: 82.1 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**17)" 10 loops, best of 3: 242 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**18)" 10 loops, best of 3: 886 msec per loop C:\junk>\python25\python -mtimeit -s"from fookount import foo" "foo(2**19)" 10 loops, best of 3: 3.21 sec per loop Cheers, John From gagsl-py at yahoo.com.ar Mon Jan 15 20:38:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 22:38:49 -0300 Subject: for v in l: In-Reply-To: References: Message-ID: <7.0.1.0.0.20070115223439.05c87058@yahoo.com.ar> At Monday 15/1/2007 21:48, Gert Cuykens wrote: >is there a other way then this to loop trough a list and change the values > > i=-1 > for v in l: > i=i+1 > l[i]=v+x for i,value in enumerate(my_list): my_list[i] = compute_new_value(value) See the tutorial http://docs.python.org/tut/node7.html#SECTION007600000000000000000 for more info about loops. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From anil.pundoor at gmail.com Thu Jan 11 07:51:34 2007 From: anil.pundoor at gmail.com (anil.pundoor at gmail.com) Date: 11 Jan 2007 04:51:34 -0800 Subject: Reloading the already imported module Message-ID: <1168519894.160024.70930@o58g2000hsb.googlegroups.com> hi all, i have following code if from SIPT.xml_param_mapping import MESSAGE_PARAMETER_MAPPING else: from SIPT.msg_param_mapping import MESSAGE_PARAMETER_MAPPING parameter_list = MESSAGE_PARAMETER_MAPPING [ 'ABC' ] for parms in parameter_list: parameter_list[parms][4] = 'EXPORT' parameter_list[parms][5] = 'IMPORT' After this the xml_param_mapping gets altered. this process is repeated over couple of time. But every time i need to get a fresh xml_param_mapping. So how to relaod the already imported module?? regards Anil From lrahuel.notgood at voila.fr Wed Jan 24 04:46:52 2007 From: lrahuel.notgood at voila.fr (Laurent Rahuel) Date: Wed, 24 Jan 2007 10:46:52 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? References: Message-ID: <45b72b0d$0$5107$ba4acef3@news.orange.fr> Hi, I known this can be impossible but what about an "HTML" GUI ? Daniel Jonsson wrote: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! > > Daniel From gagsl-py at yahoo.com.ar Wed Jan 17 18:23:10 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Jan 2007 20:23:10 -0300 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: <5d831$45aea748$d443bb3a$26464@news.speedlinq.nl> References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> <1168904865.253014.210140@m58g2000cwm.googlegroups.com> <8ab5f$45ad5c12$d443bb3a$7243@news.speedlinq.nl> <5d831$45aea748$d443bb3a$26464@news.speedlinq.nl> Message-ID: <7.0.1.0.0.20070117201541.04226b60@yahoo.com.ar> At Wednesday 17/1/2007 19:46, Stef Mientki wrote: > > for key,value in count: > > line += ' %s=%d' % (key, value) > > >I didn't succeed to use value as a enumerator, and I had to typecast >key into a string (and skipping >some redundant information, but then it works great, thanks !! Ouch, my fault! I didn't test it when I wrote it :( >here the complete listing: > count = {} > for item in V: > t = type(item) > try: count[t] += 1 > except KeyError: count[t] = 1 > if type(V)==list: line = 'list:' > else: line = 'tuple:' > for key in count: line += ' %s=%d' %('N_'+str(key)[7:-2],count[key]) > print line str(key)[7:-2] => key.__name__ Nice to see you built a useful tool! It's a great way to learn a language. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Mon Jan 8 19:13:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 21:13:52 -0300 Subject: Maths error In-Reply-To: <50fudtF1g1nplU1@mid.individual.net> References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <7.0.1.0.0.20070108211131.0398ec20@yahoo.com.ar> At Monday 8/1/2007 19:20, Bjoern Schliessmann wrote: >Rory Campbell-Lange wrote: > > > Is using the decimal module the best way around this? (I'm > > expecting the first sum to match the second). It seem > > anachronistic that decimal takes strings as input, though. >[...] >Also check the recent thread "bizarre floating point output". And the last section on the Python Tutorial "Floating Point Arithmetic: Issues and Limitations" -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From suregay at google.com Sun Jan 21 03:47:53 2007 From: suregay at google.com (Eds Daughter) Date: Sun, 21 Jan 2007 08:47:53 GMT Subject: ***** See my Cam ***** Message-ID: An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Jan 2 07:38:36 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Jan 2007 13:38:36 +0100 Subject: mutable numeric type References: Message-ID: Andreas Beyer wrote: > There has been quite some traffic about mutable and immutable data types > on this list. I understand the issues related to mutable numeric data > types. However, in my special case I don't see a better solution to the > problem. > Here is what I am doing: > > I am using a third party library that is performing basic numerical > operations (adding, multiplying, etc.) with objects of unknown type. Of > course, the objects must support the numerical operators. In my case the > third party library is a graph algorithm library and the assigned > objects are edge weights. I am using the library to compute node > distances, etc. > > I would like to be able to change the edge weights after creating the > edges. Otherwise, I would have to remove the edges and re-create them > with the new values, which is quite costly. Since I also didn't want to > change the code of the graph library, I came up with a mutable numeric > type, which implements all the numerical operators (instances are of > course not hashable). This allows me to change the edge weights after > creating the graph. > > I can do the following: > >>> x = MutableNumeric(10) > >>> y = MutableNumeric(2) > >>> x*y > 20 > >>> x.value = 1.3 > >>> x*y > 2.6000000000000001 > >>> > > The effect of numerical operations is determined by the contained basic > data types: > >>> x.value = 3 > >>> x/2 > 1 > >>> x.value = 3.0 > >>> x/2 > 1.5 > >>> > > Augmented operations change the instance itself: > >>> x.value = 0 > >>> id(x) > -1213448500 > >>> x += 2 > >>> x > MutableNumeric(2) > >>> id(x) # show that same instance > -1213448500 > >>> > > Is there anything wrong with such design? The library you are planning to feed with your mutable numbers has to be designed with such somewhat unusual beasts in mind. For instance, it can no longer cache intermediate values as their constituents may have changed without notification. Don't use that design unless the library's designers explicitly allow it or at least after extensive testing. Be aware that in the latter case every new version of the library may break your app beyond fixability. > I am a bit surprised that > Python does not already come with such data type (which is really simple > to implement). I'm guessing: Such a type is not normally useful -- and if you need it it is really simple to implement :-) Peter From wojciech_mula at poczta.null.onet.pl.invalid Fri Jan 5 08:06:23 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Fri, 5 Jan 2007 13:06:23 +0000 (UTC) Subject: Change coords of a canvas.line item References: Message-ID: Fredrik Lundh wrote: > Matthias Vodel wrote: > >> I want to change the beginning/end-coordinates of a canvas.line item. >> >> Something like: >> >> self.myCanvas.itemconfigure(item_id, coords=(x1_new, y1_new, x2_new, y2_new)) > > self.myCanvas.coords(item_id, x1_new, y1_new, x2_new, y2_new) You can also use insert and dchars methods to add and delete vertices (useful for polylines/polygons). w. From pydecker at gmail.com Tue Jan 16 10:36:33 2007 From: pydecker at gmail.com (Peter Decker) Date: Tue, 16 Jan 2007 10:36:33 -0500 Subject: Projects anyone? In-Reply-To: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> References: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> Message-ID: On 16 Jan 2007 04:07:50 -0800, placid wrote: > Hi all, > > I'm looking for anyone who is working on a project at the moment that > needs help (volunteer). The last project i worked on personally was > screen-scraping MySpace profiles (read more at the following link) > > http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles > > > but that didn't go all to well, so im kinda bored and need something to > do, with Python. So any suggestions anyone? I know the Dabo folks (http://dabodev.com) are always looking for help, although that is not a simple one-trick project, so it might not be what you're looking for. -- # p.d. From nagle at animats.com Fri Jan 19 13:16:14 2007 From: nagle at animats.com (John Nagle) Date: Fri, 19 Jan 2007 10:16:14 -0800 Subject: More M2Crypto issues In-Reply-To: References: Message-ID: <6u7sh.264$4H1.150@newssvr17.news.prodigy.net> Gabriel Genellina wrote: > At Thursday 18/1/2007 04:41, John Nagle wrote: > On a previous version of M2Crypto that line said: map()[self.ctx] = > self, and that failed too ("unhashable object", I think). > I changed the class _ctxmap (the map() above returns an instance of it) > to use str(key) in the 3 places it was used. (That would be equivalent > to use str(self.ctx) everywhere, instead of long(self.ctx) as your > traceback is showing). All I can say is that no error happened > afterwards, but I don't know if that broke something. > > > So using str() appears, at least on the surface, to be reasonable. But > someone with more intimate knowledge of the library should confirm that. > I don't even understand what's the point for the _ctxmap singleton - > it's the same thing as a global dictionary, isn't it? I played around with using "str" too, but I was worried about Python and SWIG version issues. I'm not sure you can use "str" on those objects on all versions and platforms. I think that SWIG is generating the implementations of __str__ and __long__. Incidentally, note in that area that if you never explicitly call "close" on a Context, it will never be released. Or so it looks from the code. Actually, at the moment I'm having an M2Crypto problem related to a SWIG/OpenSSL conflict. Older versions of OpenSSL have an include file that needs __i386__ defined, which is something GCC does based on what platform you're on. SWIG uses CPP, but doesn't set the platform defines, so the SWIG phase of the M2Crypto build fails. I'm currently trying to get the shared host where that build took place upgraded to a later version of OpenSSL, but that requires a server restart, so it may take a few days. I'm doing something that requires M2Crypto to run on a range of machines, which turns out to be rather harder than expected. All this stuff is in the area that Guido was unhappy about in his "M2Crypto Woes" article. http://www.artima.com/weblogs/viewpost.jsp?thread=95863 The worst problems there have been fixed, but we're not out of the woods yet. As Guido wrote, using SWIG does complicate things. I'm currently getting good results on Windows 2000 with Python 2.4 using M2Crypto 0.17; right now, the problems are on the Linux side. John Nagle From draghuram at gmail.com Tue Jan 23 12:26:47 2007 From: draghuram at gmail.com (draghuram at gmail.com) Date: 23 Jan 2007 09:26:47 -0800 Subject: Reading character from keyboard References: Message-ID: <1169573207.270724.316560@d71g2000cwa.googlegroups.com> Tommy Grav wrote: > A very simple question. I would like to read a single character from the > keyboard (y or n). I have tried to look in my Python books and a google > search, but have come up empty. I am sure the info s out there, but I > guess I am unable to find the right question or search keyword :o/ You can use "raw_input". http://docs.python.org/lib/built-in-funcs.html If you are looking for a function to ask the user for confirmation, you can use something like this: ----------------------------------- def confirm(_prompt=None, _default=False): """prompts for yes or no response. Return True for yes and False for no.""" promptstr = _prompt if (not promptstr): promptstr = "Confirm" if (_default): prompt = "%s [%s]|%s: " % (promptstr, "y", "n") else: prompt = "%s [%s]|%s: " % (promptstr, "n", "y") while (True): ans = raw_input(prompt) if (not ans): return _default if ((ans != "y") and (ans != "Y") and (ans != "n") and (ans != "N")): print "please enter again y or n." continue if ((ans == "y") or (ans == "Y")): return True if ((ans == "n") or (ans == "N")): return False -------------------------------------------- Usage: if (confirm("\nWant to proceed?", _default=False)): # proceed ------------------------------------------------ From andrea.massa at gmail.com Tue Jan 9 04:39:08 2007 From: andrea.massa at gmail.com (Nuke) Date: 9 Jan 2007 01:39:08 -0800 Subject: formattazione cifra con decimali Message-ID: <1168335548.504284.287150@q40g2000cwq.googlegroups.com> Ho cercato un poco sulla documentazione di python senza trovare una risposta soddisfacente al mio problema, quindi spero di trovare un aiuto qui. Ho creato un programmino che mi fa alcuni calcoli e riepiloghi personali e vorrei visualizzare i totali numerici in euro con la formattazione comprensiva dei separatori decimali. Per esempio ho un totale scritto attualmente cos?: 50320,12 e vorrei che si visualizzasse cosi: 50.320,12 esiste gi? una qualche funzione che mi formatta il numero (o la stringa eventualmente) in questo modo? Grazie a chi sapr? darmi una risposta in merito. From NikitaTheSpider at gmail.com Fri Jan 26 13:59:46 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 26 Jan 2007 13:59:46 -0500 Subject: Help extracting info from HTML source .. References: <1169819118.201093.267320@h3g2000cwc.googlegroups.com> Message-ID: In article <1169819118.201093.267320 at h3g2000cwc.googlegroups.com>, "Miki" wrote: > Hello Shelton, > > > I am learning Python, and have never worked with HTML. However, I would > > like to write a simple script to audit my 100+ Netware servers via their web > > portal. > Always use the right tool, BeautilfulSoup > (http://www.crummy.com/software/BeautifulSoup/) is best for web > scraping (IMO). > > from urllib import urlopen > from BeautifulSoup import BeautifulSoup > > html = urlopen("http://www.python.org").read() > soup = BeautifulSoup(html) > for link in soup("a"): > print link["href"], "-->", link.contents Agreed. HTML scraping is really complicated once you get into it. It might be interesting to write such a library just for your own satisfaction, but if you want to get something done then use a module that already written, like BeautifulSoup. Another module that will do the same job but works differently (and more simply, IMO) is HTMLData by Connelly Barnes: http://oregonstate.edu/~barnesc/htmldata/ -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From steve at REMOVE.THIS.cybersource.com.au Sat Jan 13 14:08:03 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 14 Jan 2007 06:08:03 +1100 Subject: Boilerplate in rich comparison methods References: <1168674664.792869.213260@m58g2000cwm.googlegroups.com> <45a90301$0$7677$4c368faf@roadrunner.com> Message-ID: On Sat, 13 Jan 2007 10:04:17 -0600, Paul McGuire wrote: > Just a side note on writing these comparison operators. I remember when > learning Java that this was really the first time I spent so much time > reading about testing-for-identity vs. testing-for-equality. The Java > conventional practice at the time was to begin each test-for-equality method > by testing to see if an object were being compared against itself, and if > so, cut to the chase and return True (and the converse for an inequality > comparison). The idea behind this was that there were ostensibly many times > in code where an object was being compared against itself (not so much in an > explicit "if x==x" but in implicit tests such as list searching and > filtering), and this upfront test-for-identity, being very fast, could > short-circuit an otherwise needless comparison. > > In Python, this would look like: > > class Parrot: > def __eq__(self, other): > return self is other or self.plumage() == other.plumage() [snip] Surely this is only worth doing if the comparison is expensive? Testing beats intuition, so let's find out... class Compare: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x class CompareWithIdentity: def __init__(self, x): self.x = x def __eq__(self, other): return self is other or self.x == other.x Here's the timing results without the identity test: >>> import timeit >>> x = Compare(1); y = Compare(1) >>> timeit.Timer("x = x", "from __main__ import x,y").repeat() [0.20771503448486328, 0.16396403312683105, 0.16507196426391602] >>> timeit.Timer("x = y", "from __main__ import x,y").repeat() [0.20918107032775879, 0.16187810897827148, 0.16351795196533203] And with the identity test: >>> x = CompareWithIdentity(1); y = CompareWithIdentity(1) >>> timeit.Timer("x = x", "from __main__ import x,y").repeat() [0.20761799812316895, 0.16907095909118652, 0.16420602798461914] >>> timeit.Timer("x = y", "from __main__ import x,y").repeat() [0.2090909481048584, 0.1968839168548584, 0.16479206085205078] Anyone want to argue that this is a worthwhile optimization? :) > On the other hand, I haven't seen this idiom in any Python code that I've > read, and I wonder if this was just a coding fad of the time. > > Still, in cases such as Steven's Aardark class, it might be worth > bypassing something that calls lots_of_work if you tested first to see > if self is not other. The comparison itself would have to be quite expensive to make it worth the extra code. -- Steven. From roy at panix.com Sun Jan 14 23:12:08 2007 From: roy at panix.com (Roy Smith) Date: Sun, 14 Jan 2007 23:12:08 -0500 Subject: How naive is Python? References: Message-ID: In article , John Nagle wrote: > How naive (in the sense that compiler people use the term) > is the current Python system? For example: > > def foo() : > s = "This is a test" > return(s) > > s2 = foo() > > How many times does the string get copied? All of those just move around pointers to the same (interned) string. > How about this? > > kcount = 1000 > s = '' > for i in range(kcount) : > s += str(i) + ' ' > > Is this O(N) or O(N^2) because of recopying of "s"? This is a well-known (indeed, the canonical) example of quadratic behavior in Python. The standard solution is to store all the strings (again, really just pointers to the strings) in a list, then join all the elements: temp = [] for i in range (1000): temp.append (str(i)) s = "".join (temp) That ends up copying each string once (during the join operation), and is O(N) overall. From nmm1 at cus.cam.ac.uk Wed Jan 17 04:48:44 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 17 Jan 2007 09:48:44 GMT Subject: Class data members in C References: Message-ID: In article , "Hendrik van Rooyen" writes: |> > |> > Hmm. The extensions documentation describes how to add instance |> > members to a class (PyMemberDef), but I want to add a class member. |> > Yes, this is constant for all instances of the class. |> |> When? - at time of defining base class, between class definition and |> first instance, at time of creating instance, or after instance creation? |> |> After instance creation is not easy, I think you would have to add |> to each instance... Oh, one of the first two - I am not bonkers! Changing a class after instance creation is guaranteed to cause confusion, if nothing else. Regards, Nick Maclaren. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 10:27:33 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 16:27:33 +0100 Subject: multi-threaded webcam with SimpleAsyncHTTPServer.py References: Message-ID: <50f675F1fb5uqU3@mid.individual.net> Ray Schumacher wrote: > I'll be trying implementing some streaming next. > Question, though: how can I unblock asyncore.loop(), Not at all. That's the way event loops work. > or at least be able to interrupt it? Sorry for the stupid question, but why would you want to do that? > Other suggestions? Yes, why do you call it multithreaded when it's multiplexing? (or isn't it?) Regards, Bj?rn -- BOFH excuse #10: hardware stress fractures From gagsl-py at yahoo.com.ar Fri Jan 26 22:26:09 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Jan 2007 00:26:09 -0300 Subject: Getting the output from a console command while it's been generated! References: <684b0a740701261905o76ca3a9av6425b88cd1c3b9fc@mail.gmail.com> Message-ID: "Ra?l G?mez C." escribi? en el mensaje news:684b0a740701261905o76ca3a9av6425b88cd1c3b9fc at mail.gmail.com... > I'm trying to make my apps more informative to the user, so I want to know > if its possible to get the output of the execution of a console command > while it's been generated, I mean, I want to get the output from > commands.getstatusoutput('CMD') while CMD it's been executed and not wait > until CMD have finished (because CMD take very long time to). Use the subprocess module and read line by line. -- Gabriel Genellina From gandalf at designaproduct.biz Fri Jan 5 12:28:23 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 18:28:23 +0100 Subject: program deployment In-Reply-To: <459E7024.3040204@gmx.net> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <459E7024.3040204@gmx.net> Message-ID: <459E8AB7.2030806@designaproduct.biz> > hehehe, but what I am thinking: Is it somehow possible to _really_ hide > the source from being viewed by other persons when using python? Not > that I want to do that ( I am an Open Source friend ), but that might > get others that rely on that (commercial) to use python for more > projects as it is done now. > Yes. I use Python for running background tasks. I wrote many servers in Python and also websites. Users are using it, but they do not have access to the .py files. This is one possible way to do it. E.g. hide the whole computer system from the end users, and allow them to access some restricted interfaces only. Of course, you cannot distribute or sell these programs without showing the source code. You can sell them as a service; that is accessible remotely. Or you can sell them together with the machine, cased and stamped. :-) Laszlo From persed at princeton.edu Mon Jan 22 10:49:11 2007 From: persed at princeton.edu (Per B.Sederberg) Date: Mon, 22 Jan 2007 15:49:11 +0000 (UTC) Subject: Program eating memory, but only on one machine? References: Message-ID: Wolfgang Draxinger darkstargames.de> writes: > > > So, does anyone have any suggestions for how I can debug this > > problem? > > Have a look at the version numbers of the GCC used. Probably > something in your C code fails if it interacts with GCC 3.x.x. > It's hardly Python eating memory, this is probably your C > module. GC won't help here, since then you must add this into > your C module. > > > If my program ate up memory on all machines, then I would know > > where to start and would blame some horrible programming on my > > end. This just seems like a less straightforward problem. > > GCC 3.x.x brings other runtime libs, than GCC 4.x.x, I would > check into that direction. > Thank you for the suggestions. Since my C module is such a small part of the simulations, I can just comment out the call to that module completely (though I am still loading it) and fill in what the results would have been with random values. Sadly, the program still eats up memory on our cluster. Still, it could be something related to compiling Python with the older GCC. I'll see if I can make a really small example program that eats up memory on our cluster. That way we'll have something easy to work with. Thanks, Per From oliphant.travis at ieee.org Mon Jan 15 16:06:56 2007 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Mon, 15 Jan 2007 14:06:56 -0700 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168715634.695961.14710@l53g2000cwa.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168715634.695961.14710@l53g2000cwa.googlegroups.com> Message-ID: oyekomova wrote: > Thanks to everyone for their excellent suggestions. I was able to > acheive the following results with all your suggestions. However, I am > unable to cross file size of 6 million rows. I would appreciate any > helpful suggestions on avoiding memory errors. None of the solutions > posted was able to cross this limit. Did you try using numpy.fromfile ? This will not require you to allocate more memory than needed. If you specify a count, it will also not have to re-allocate memory in blocks as the array size grows. It's limitation is that it is not a very sophisticated csv reader (it only understands a single separator (plus line-feeds are typically seen as a separator). -Travis From steve at REMOVE.THIS.cybersource.com.au Sat Jan 6 03:34:10 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 06 Jan 2007 19:34:10 +1100 Subject: attribute decorators References: <1168058094.179442.173650@s34g2000cwa.googlegroups.com> Message-ID: On Fri, 05 Jan 2007 20:34:54 -0800, gert wrote: > Would it not be nice if you could assign decorators to attributes too ? > for example > > class C: > @staticattribute > data='hello' You can. You just have to write it as: class C: data = staticattribute('hello') (Of course, writing the staticattribute function is a non-trivial problem.) > or > > class C: > @privateattribute > data='hello' That would be written as class C: _data = 'hello' or possibly class C: __data = 'hello' depending on whether you want private attributes to be by convention or by name-mangling. -- Steven. From jeff at taupro.com Sat Jan 27 06:11:58 2007 From: jeff at taupro.com (Jeff Rush) Date: Sat, 27 Jan 2007 05:11:58 -0600 Subject: New vs Old Style Python Classes in C Extensions? Message-ID: <45BB337E.5060906@taupro.com> While I have a reasonable understanding of the differences in new-style versus old-style classes, tonight while working a C extension module I realized I don't know how to indicate which style my C extension module should appear as. I'm following the Python docs for extended modules, but it doesn't say in there anyplace I can find which style I'm creating. My clue that something was wrong is when this: from cextension import Context class MyContext(Context): def __init__(self): super(Context, self).__init__() repeatedly and reliably failed with a corrupted C data structure, while this: class MyContext(Context): def __init__(self): Context.__init__() worked without any problems. As I understand it, the former uses new-style semantics while the latter uses old-style, and -thats- when I realized I have no idea which my C extension implemented. Any enlightenment? -Jeff From duncan.booth at invalid.invalid Thu Jan 18 08:41:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Jan 2007 13:41:32 GMT Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: Peter Otten <__peter__ at web.de> wrote: > Let's see if I understand the above: In C a call > > f(g(), g()) > > may result in machine code equivalent to either > > x = g() > y = g() > f(x, y) > > or > > y = g() > x = g() > f(x, y) > > Is that it? > Yes, or changing one of the calls to h() and compiling with "cl -Fat.asm -Ox -c t.c": ------ t.c -------- extern int f(int a, int b); extern int g(); extern int h(); int main(int argc, char **argv) { return f(g(), h()); } ------------------- The output file: ------- t.asm ----- ; Listing generated by Microsoft (R) Optimizing Compiler Version 13.10.3077 TITLE t.c .386P include listing.inc if @Version gt 510 .model FLAT else _TEXT SEGMENT PARA USE32 PUBLIC 'CODE' _TEXT ENDS _DATA SEGMENT DWORD USE32 PUBLIC 'DATA' _DATA ENDS CONST SEGMENT DWORD USE32 PUBLIC 'CONST' CONST ENDS _BSS SEGMENT DWORD USE32 PUBLIC 'BSS' _BSS ENDS $$SYMBOLS SEGMENT BYTE USE32 'DEBSYM' $$SYMBOLS ENDS _TLS SEGMENT DWORD USE32 PUBLIC 'TLS' _TLS ENDS FLAT GROUP _DATA, CONST, _BSS ASSUME CS: FLAT, DS: FLAT, SS: FLAT endif INCLUDELIB LIBC INCLUDELIB OLDNAMES PUBLIC _main EXTRN _f:NEAR EXTRN _g:NEAR EXTRN _h:NEAR ; Function compile flags: /Ogty _TEXT SEGMENT _argc$ = 8 ; size = 4 _argv$ = 12 ; size = 4 _main PROC NEAR ; File c:\temp\t.c ; Line 6 call _h push eax call _g push eax call _f add esp, 8 ; Line 7 ret 0 _main ENDP _TEXT ENDS END ------------------------- From gagsl-py at yahoo.com.ar Sat Jan 13 08:38:25 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Jan 2007 10:38:25 -0300 Subject: How to run external program? References: <1168594577.397453.320380@a75g2000cwd.googlegroups.com> <1168596401.191648.79440@38g2000cwa.googlegroups.com> Message-ID: "Lad" escribi? en el mensaje news:1168596401.191648.79440 at 38g2000cwa.googlegroups.com... > mpeg = "mpeg.exe -i %s codec mp3 -s 320x240 %s" % (sourcefile, > targetfile) > stdin, stdout, stderr = os.popen3(mpeg) > mpegresult = stdout.read() > mpegerrors = stderr.read() > stdin.close(); stdout.close(); stderr.close() > print ffmpegerrors > print ffmpegresult > ######### > > It works if the sourcefile is small but if it is large( 30MB) it does > NOT work.It hangs or the file is not converted in full. > Any advice how I should change the program? What do you mean by "NOT work"? Does it "work" if you execute the same line from the command prompt? -- Gabriel Genellina From larry.bates at websafe.com Mon Jan 15 19:42:02 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 15 Jan 2007 18:42:02 -0600 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> Message-ID: <45AC1F5A.90403@websafe.com> Stef Mientki wrote: > hello, > > Is there some handy/ nice manner to view the properties of some variable ? > As a newbie, I often want to see want all the properties of a var, > and also some corner values (large arrays) etc. > > Probably it's not so difficult, > but I don't see how to distinguish for example between a string and an > array. An array has a shape, a string not etc. > > > thanks, > Stef Mientki Others have given some suggestions, but I thought I'd put in my thoughts also. When I first started using Python I was looking for exactly what you describe. After using a while, you begin to understand that the objects in Python can be so complex (lists of dictionaries that contain lists and other dictionaries, lists of class instances that can contain other class instances, that can contain...., you get the picture). You have to begin to think about navigating through this by using dir(), vars() and pprint.pprint(). Unlike older programming languages there is no limit to how you can mix/match values within an object. Also in standard Python lists (arrays?) don't have shape (there are add on modules that give you this type of feature). Everything is a collection of objects. class foo: def __init__(self): self.x=1 self.y=2 l=[[1,2,3], 'test', 6, 3.14159, {'a':1, 'b':2}, foo()] a list with: a list as first element a string as the second element an integer as the third element a float as the third element a dictionary as the fourth element a class instance as the fifth element The tutorial is a good place to start if you haven't already looked at it. -Larry Bates From steven.bethard at gmail.com Sat Jan 20 15:49:52 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 20 Jan 2007 13:49:52 -0700 Subject: pyparsing Combine without merging sub-expressions Message-ID: Within a larger pyparsing grammar, I have something that looks like:: wsj/00/wsj_0003.mrg When parsing this, I'd like to keep around both the full string, and the AAA_NNNN substring of it, so I'd like something like:: >>> foo.parseString('wsj/00/wsj_0003.mrg') (['wsj/00/wsj_0003.mrg', 'wsj_0003'], {}) How do I go about this? I was using something like:: >>> digits = pp.Word(pp.nums) >>> alphas = pp.Word(pp.alphas) >>> wsj_name = pp.Combine(alphas + '_' + digits) >>> wsj_path = pp.Combine(alphas + '/' + digits + '/' + wsj_name + ... '.mrg') But of course then all I get back is the full path:: >>> wsj_path.parseString('wsj/00/wsj_0003.mrg') (['wsj/00/wsj_0003.mrg'], {}) I could leave off the final Combine and add a parse action:: >>> wsj_path = alphas + '/' + digits + '/' + wsj_name + '.mrg' >>> def parse_wsj_path(string, index, tokens): ... wsj_name = tokens[4] ... return ''.join(tokens), wsj_name ... >>> wsj_path.setParseAction(parse_wsj_path) >>> wsj_path.parseString('wsj/00/wsj_0003.mrg') ([('wsj/00/wsj_0003.mrg', 'wsj_0003')], {}) But that then allows whitespace between the pieces of the path, which there shouldn't be:: >>> wsj_path.parseString('wsj / 00 / wsj_0003.mrg') ([('wsj/00/wsj_0003.mrg', 'wsj_0003')], {}) How do I make sure no whitespace intervenes, and still have access to the sub-expression? Thanks, STeVe From weekender_ny at yahoo.com Thu Jan 4 18:23:37 2007 From: weekender_ny at yahoo.com (John) Date: 4 Jan 2007 15:23:37 -0800 Subject: cache line length of a machine Message-ID: <1167953016.952907.279260@i15g2000cwa.googlegroups.com> How do I find out the cache line length of a machine in python? Thanks, --j From laurent.pointal at limsi.fr Mon Jan 15 10:48:06 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 15 Jan 2007 16:48:06 +0100 Subject: check if there is data in stdin without blocking In-Reply-To: References: <4PMqh.47441$X97.9536@newsfe18.lga> Message-ID: hg a ?crit : > hg wrote: > >> Hi, >> >> Is there a way ? ... select ? >> >> >> >> hg > PS: > > import sys > import select > > l_r = select.select([sys.stdin],[],[],0) > > gives me: > File "select.py", line 2, in ? > import select > File "/home/philippe/Desktop/select.py", line 4, in ? > l_r = select.select([sys.stdin],[],[],0) > TypeError: 'module' object is not callable > > Wont work under Windows: >>> help(select.select) ...... *** IMPORTANT NOTICE *** On Windows, only sockets are supported; on Unix, all file descriptors. If under Unix, maybe sys.stdin.fileno() is a valid descriptor for select. Just test it. And if under Windows, you may take a look at 22.1 msvcrt - Useful routines from the MS VC++ runtime 22.1.2 Console I/O kbhit( ) - Return true if a keypress is waiting to be read. From bignose+hates-spam at benfinney.id.au Tue Jan 16 17:16:34 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Jan 2007 09:16:34 +1100 Subject: How to determine what exceptions a method might raise? References: <12qq98ijkn5mld8@corp.supernews.com> Message-ID: <87y7o2aa7x.fsf@benfinney.id.au> Ed Jensen writes: > it would be handy if there was something I could do in the > interactive interpreter to make it tell me what exceptions the file > method might raise (such as IOError). For what purpose would this be handy? Surely the benefit of the interactive interpreter is that you can simply try it out and *see* what happens. But, in case it helps: Any code may raise any exception at any time. This is a feature, since it encourages program that are tested properly. -- \ "I'm a great lover, I'll bet." -- Emo Philips | `\ | _o__) | Ben Finney From steve at REMOVEME.cybersource.com.au Wed Jan 31 02:34:25 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 31 Jan 2007 18:34:25 +1100 Subject: how to "free" an object/var ? References: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> Message-ID: On Tue, 30 Jan 2007 23:22:52 -0800, Paddy wrote: >> As far as I know there is no way to force the deletion of an object >> even if it is in use. This is a Good Thing. >> >> -- >> Steven D'Aprano > > The folowing will make the data available for garbage collection no > matter what references it: > >>>> l = ["data"] *10 >>>> l > ['data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', > 'data'] >>>> l2 = l >>>> l[:] = [] >>>> l2 > [] Sort of. What happens is that both l and l2 are names referring to the same list. After executing l[:] the *contents* of the list change, from lots of "data" to nothing. Naturally both l and l2 see the change, because they both point to the same list. But the original contents of the list still exist until the garbage collector sees that they are no longer in use, and then frees them. You can prove this by doing something like this: data = "\0"*1000000 # one (decimal) megabyte of data L = [data] # put it in a list L[:] = [] # "free" the contents of the list assert len(data) == 1000000 # but the megabyte of data still there Again, you can't force Python to free up memory that is still in use. If you could, that would be a bug. -- Steven D'Aprano From metsakuri at gmail.com Thu Jan 4 02:33:21 2007 From: metsakuri at gmail.com (tonisk) Date: 3 Jan 2007 23:33:21 -0800 Subject: question on creating class In-Reply-To: <1167895677.041759.230190@42g2000cwt.googlegroups.com> References: <1167895677.041759.230190@42g2000cwt.googlegroups.com> Message-ID: <1167896001.235226.307830@6g2000cwy.googlegroups.com> You can always rename your defined clas afterwards class TestClass: pass myClass = TestClass -- T?nis On Jan 4, 9:27 am, "wcc" wrote: > Hello, > > How do I create a class using a variable as the class name? > > For example, in the code below, I'd like replace the line > > class TestClass(object): > with something like > class eval(className) (object): > > Is it possible? Thanks for your help. > > className = "TestClass" > > class TestClass(object): > def __init__(self): > print "Creating object of TestClass..." > > def method1(self): > print "This is a method." > > if __name__ == "__main__": > o = TestClass() > o.method1() > > -- > wcc From robert.kern at gmail.com Wed Jan 24 16:18:07 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 24 Jan 2007 15:18:07 -0600 Subject: Simple Matrix class In-Reply-To: <1169670271.547292.141110@l53g2000cwa.googlegroups.com> References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> <1169664540.120687.211350@s48g2000cws.googlegroups.com> <1169670271.547292.141110@l53g2000cwa.googlegroups.com> Message-ID: Paul McGuire wrote: > On Jan 24, 1:47 pm, Robert Kern wrote: >> Paul McGuire wrote: >>> And the purpose/motivation for "reimplementing it better" would be >>> what, exactly? So I can charge double for it? >> So you can have accurate results, and you get a good linear solver out of the >> process. The method you use is bad in terms of accuracy as well as efficiency. > > Dang, I thought I was testing the results sufficiently! What is the > accuracy problem? In my test cases, I've randomly created test > matrices, inverted, then multiplied, then compared to the identity > matrix, with the only failures being when I start with a singular > matrix, which shouldn't invert anyway. Ill-conditioned matrices. You should grab a copy of _Matrix Computations_ by Gene H. Golub and Charles F. Van Loan. For example, try the Hilbert matrix n=6. H_ij = 1 / (i + j - 1) http://en.wikipedia.org/wiki/Hilbert_matrix While all numerical solvers have issues with ill-conditioned matrices, your method runs into them faster. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From parallelpython at gmail.com Sat Jan 13 23:00:15 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 13 Jan 2007 20:00:15 -0800 Subject: Threaded for loop References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> Message-ID: <1168747208.275625.55590@51g2000cwl.googlegroups.com> John wrote: > I want to do something like this: > > for i = 1 in range(0,N): > for j = 1 in range(0,N): > D[i][j] = calculate(i,j) > > I would like to now do this using a fixed number of threads, say 10 > threads. > What is the easiest way to do the "parfor" in python? > > Thanks in advance for your help, As it was already mentioned before threads will not help in terms of parallelism (only one thread will be actually working). If you want to calculate this in parallel here is an easy solution: import ppsmp #start with 10 processes srv = ppsmp.Server(10) f = [] for i = 1 in range(0,N): for j = 1 in range(0,N): #it might be a little bit more complex if 'calculate' depends on other modules or calls functions f.append(srv.submit(calculate, (i,j))) for i = 1 in range(0,N): for j = 1 in range(0,N): D[i][j] = f.pop(0) You can get the latest version of ppsmp module here: http://www.parallelpython.com/ From goodepic at gmail.com Fri Jan 5 15:55:53 2007 From: goodepic at gmail.com (goodepic) Date: 5 Jan 2007 12:55:53 -0800 Subject: PyGreSQL Install Message-ID: <1168030553.913612.309020@q40g2000cwq.googlegroups.com> I successfully installed postgresql and pygresql from source on my MacBook 2ghz Intel core duo running os x 10.4.8. However, pygresql installed under the defualt python 2.3 installation, while I've been upgrading and working in 2.5, and have invested too much time to go back to 2.3. I definitely don't know where every file is, but I know that the site-packages folder where I need pgdb to be is /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages. This is where I have pypar, pynum, numeric, etc. PyGreSQL installed in the default /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages. Anyone know where I can edit setup.py or what flags I can use to force the install onto 2.5? Thanks! From nachogomez at gmail.com Sun Jan 28 21:54:03 2007 From: nachogomez at gmail.com (=?UTF-8?Q?Ra=C3=BAl_G=C3=B3mez_C.?=) Date: Sun, 28 Jan 2007 22:54:03 -0400 Subject: Getting the output from a console command while it's been generated! In-Reply-To: References: <684b0a740701261905o76ca3a9av6425b88cd1c3b9fc@mail.gmail.com> Message-ID: <684b0a740701281854r7108415aqb43221ab5ad9a7d6@mail.gmail.com> I can't use the subprocess module because my app needs to be compatible with Python 2.3 so, is there another approach to this problem??? Thanks! On 1/26/07, Gabriel Genellina wrote: > > "Ra?l G?mez C." escribi? en el mensaje > news:684b0a740701261905o76ca3a9av6425b88cd1c3b9fc at mail.gmail.com... > > > I'm trying to make my apps more informative to the user, so I want to > know > > if its possible to get the output of the execution of a console command > > while it's been generated, I mean, I want to get the output from > > commands.getstatusoutput('CMD') while CMD it's been executed and not > wait > > until CMD have finished (because CMD take very long time to). > > Use the subprocess module and read line by line. > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Wed Jan 31 15:37:58 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Jan 2007 15:37:58 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170275061.786779.74910@a34g2000cwb.googlegroups.com> Message-ID: <20070131203758.25807.1007628884.divmod.quotient.4971@ohm> On 31 Jan 2007 12:24:21 -0800, Carl Banks wrote: >Michele Simionato wrote: >> On Jan 31, 5:23 pm, "Frank Potter" wrote: >> > I want to find a multithreaded downloading lib in python, >> > can someone recommend one for me, please? >> > Thanks~ >> >> Why do you want to use threads for that? Twisted is the >> obvious solution for your problem, > >Overkill? Just to download a few web pages? You've got to be >kidding. Better "overkill" (whatever that is) than wasting time re-implementing the same boring thing over and over for no reason. Jean-Paul From uymqlp502 at sneakemail.com Tue Jan 23 21:07:55 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 23 Jan 2007 18:07:55 -0800 Subject: Overloading assignment operator In-Reply-To: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1169604475.177104.40330@s48g2000cws.googlegroups.com> Achim Domma wrote: > Hi, > > I want to use Python to script some formulas in my application. The user > should be able to write something like > > A = B * C > > where A,B,C are instances of some wrapper classes. Overloading * is no > problem but I cannot overload the assignment of A. I understand that > this is due to the nature of Python, but is there a trick to work around > this? > All I'm interested in is a clean syntax to script my app. Any ideas are > very welcome. > > regards, > Achim Why do you need to overload assignment anyway? If you overloaded "*" properly, it should return the result you want, which you then "assign" to A as usual. Maybe I'm missing something. From bob at passcal.nmt.edu Fri Jan 26 13:26:46 2007 From: bob at passcal.nmt.edu (Bob Greschke) Date: Fri, 26 Jan 2007 11:26:46 -0700 Subject: Fixed length lists from .split()? References: <2007012611072716807-bob@passcalnmtedu> Message-ID: <2007012611264650073-bob@passcalnmtedu> On 2007-01-26 11:13:56 -0700, Duncan Booth said: > Bob Greschke wrote: > >> Is there a fancy way to get Parts=Line.split(";") to make Parts always >> have three items in it, or do I just have to check the length of Parts >> and loop to add the required missing items (this one would just take >> Parts+=[""], but there are other types of lines in the file that have >> about 10 "fields" that also have this problem)? > >>>> def nsplit(s, sep, n): > return (s.split(sep) + [""]*n)[:n] > >>>> nsplit("bcsn; 1000001; 1456", ";", 3) > ['bcsn', ' 1000001', ' 1456'] >>>> nsplit("bcsn; 1000001", ";", 3) > ['bcsn', ' 1000001', ''] That's fancy enough. :) I didn't know you could do [""]*n. I never thought about it before. Thanks! Bob From redefined.horizons at gmail.com Fri Jan 5 23:27:07 2007 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 5 Jan 2007 20:27:07 -0800 Subject: Adding a directory to the Python System Path - Edit the registry? In-Reply-To: <459e8fa5$0$335$e4fe514c@news.xs4all.nl> References: <1168017552.010631.276080@s34g2000cwa.googlegroups.com> <459e8fa5$0$335$e4fe514c@news.xs4all.nl> Message-ID: <1168057627.305211.151320@s34g2000cwa.googlegroups.com> Thanks Martin. I'll take a look at the documentation you pointed out. Scott Martin P. Hellwig wrote: > redefined.horizons at gmail.com wrote: > > I have been trying to find a way to add a directory to Python's sytem > > path on my MS Windows XP computer. I did some searching online, but the > > only solution I found involved editing the MS Windows Registry. That > > seemed a little to hard core. Is there another easier way to do this? > > > > Thanks, > > > > Scott Huey > > > > Take a look at: > http://docs.python.org/tut/node8.html > > Specifically 6.1.1 and 6.2, perhaps that might answer your question. > > Cheers > > -- > mph From steve at REMOVE.THIS.cybersource.com.au Sat Jan 20 06:09:19 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 22:09:19 +1100 Subject: Match 2 words in a line of file References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> <1169172954.107365.133950@51g2000cwl.googlegroups.com> <1169175299.490994.244700@51g2000cwl.googlegroups.com> <1169276257.512909.92380@v45g2000cwv.googlegroups.com> Message-ID: On Fri, 19 Jan 2007 22:57:37 -0800, Rickard Lindberg wrote: > Daniel Klein wrote: > >> 2) This can be resolved with >> >> templine = ' ' + line + ' ' >> if ' ' + word1 + ' ' in templine and ' ' + word2 + ' ' in templine: > > But then you will still have a problem to match the word "foo" in a > string like "bar (foo)". That's a good point for a general word-finder application, but in the case of the Original Poster's problem, it depends on the data he is dealing with and the consequences of errors. If the consequences are serious, then he may need to take extra precautions. But if the consequences are insignificant, then the fastest, most reliable solution is probably a simple generator: def find_new_events(text): for line in text.splitlines(): line = line.lower() # remove this for case-sensitive matches if "event" in line and "new" in line: yield line To get all the matching lines at once, use list(find_new_events(test)). This is probably going to be significantly faster than a regex. So that's three possible solutions: (1) Use a quick non-regex matcher, and deal with false positives later; (2) Use a slow potentially complicated regex; or (3) Use a quick non-regex matcher to eliminate obvious non-matches, then pass the results to a slow regex to eliminate any remaining false positives. Which is best will depend on the O.P.'s expected data. As always, resist the temptation to guess which is faster, and instead use the timeit module to measure it. -- Steven. From S.Mientki-nospam at mailbox.kun.nl Tue Jan 30 18:53:51 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 31 Jan 2007 00:53:51 +0100 Subject: how to "free" an object/var ? In-Reply-To: References: Message-ID: <981d4$45bfda7f$d443bb3a$9863@news.speedlinq.nl> James Stroud wrote: > Stef Mientki wrote: >> If I create a large array of data or class, >> how do I destroy it (when not needed anymore) ? >> >> Assign it to an empty list ? >> >> thanks, >> Stef Mientki > > It will be gc'd when you leave the scope or you can call del() to > explicitly get rid of the object if its existence bothers you. > > James thanks James, indeed, large objects, are sometimes bothering me, and assigning it to an empty list requires comment ;-) cheers, Stef From sturlamolden at yahoo.no Sun Jan 14 11:06:38 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 14 Jan 2007 08:06:38 -0800 Subject: Threaded for loop In-Reply-To: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> Message-ID: <1168790797.930958.327230@11g2000cwr.googlegroups.com> John wrote: > I want to do something like this: > > for i = 1 in range(0,N): > for j = 1 in range(0,N): > D[i][j] = calculate(i,j) > > I would like to now do this using a fixed number of threads, say 10 > threads. Why do you want to run this in 10 threads? Do you have 10 CPUs? If you are concerned about CPU time, you should not be using threads (regardless of language) as they are often implemented with the assumption that they stay idle most of the time (e.g. win32 threads and pthreads). In addition, CPython has a global interpreter lock (GIL) that prevents the interpreter from running on several processors in parallel. It means that python threads are a tool for things like writing non-blocking i/o and maintaining responsiveness in a GUI'. But that is what threads are implemented to do anyway, so it doesn't matter. IronPython and Jython do not have a GIL. In order to speed up computation you should run multiple processes and do some sort of IPC. Take a look at MPI (e.g. mpi4py.scipy.org) or 'parallel python'. MPI is the de facto industry standard for dealing with CPU bound problems on systems with multiple processors, whether the memory is shared or distributed does not matter. Contrary to common belief, this approach is more efficient than running multiple threads, sharing memory and synchronizong with mutexes and event objects - even if you are using a system unimpeded by a GIL. The number of parallel tasks should be equal to the number of available CPU units, not more, as you will get excessive context shifts if the number of busy threads or processes exceed the number of computational units. If you only have two logical CPUs (e.g. one dual-core processor) you should only run two parallel tasks - not ten. If you try to parallelize using additional tasks (e.g. 8 more), you will just waste time doing more context shifts, more cache misses, etc. But if you are a lucky bastard with access to a 10-way server, sure run 10 tasks in parallel. From tomas at fancy.org Fri Jan 5 17:40:28 2007 From: tomas at fancy.org (Tom Plunket) Date: Fri, 05 Jan 2007 14:40:28 -0800 Subject: A python library to convert RTF into PDF ? References: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> <5stnp25m2uffc4n5k7g9e68hk2l85u4fmm@4ax.com> <1167850322.373355.327020@s34g2000cwa.googlegroups.com> Message-ID: leonel.gayard at gmail.com wrote: > First, pdflatex is too slow. Second, my templates are M$-Word doc > files, and they cannot be easily converted to tex. I have tried to > convert them to tex using OpenOffice, but the result is ugly as hell. Ok, have you tried using the PDF printers (I've used PDFfactory before, but there are a number of free ones on SourceForge that may be worth a shot), and just using MSWord via COM to print to that printer? (This line of answers merely because nobody seems to know of a directly-Python solution.) -tom! -- From gagsl-py at yahoo.com.ar Sun Jan 14 12:27:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Jan 2007 14:27:37 -0300 Subject: Tkinter code (with pmw) executing to soon please help References: <1168746063.322340.10410@l53g2000cwa.googlegroups.com> <1168760423.608731.213550@a75g2000cwd.googlegroups.com> Message-ID: escribi? en el mensaje news:1168760423.608731.213550 at a75g2000cwd.googlegroups.com... > button[num] = Tkinter.Button(frame,text = returnstring, > command=callback(returnstring))# > > I understand this part of it > > def callback(text): > def handler(event): > print text > It stopped calling it automaticaly but will not do anything when I > click on the button. Does something have to change on this line as > well. Sorry, I overlooked your example. For a button, command should be a function with no arguments (and I forget to return the handler, as someone already pointed out): def callback(text): def handler(): print text return handler -- Gabriel Genellina From jrpfinch at gmail.com Thu Jan 11 10:32:53 2007 From: jrpfinch at gmail.com (jrpfinch) Date: 11 Jan 2007 07:32:53 -0800 Subject: Newbie question: SMTP -> SQL Server Message-ID: <1168529572.873867.207730@k58g2000hse.googlegroups.com> I have an externally-written piece of software that spits out emails using SMTP (a few hundred per hour) and I would like to dump the content of them in an MS SQL Server database. I have barely used Python before but it looks as if it could do the job. I have no experience with mail agents. My starting point is this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440690 I know that there are various libraries that can connect to MS SQL server and I am going to research these. I have two questions: i) Does this sound like an efficient way of transferring data to the database? ii) Looking through the Python documentation, I cannot see a way to set the password on the SMTP server. I would like to have a password - does anyone know how to use the recipe above to set one? Any other useful nudges in the right direction appreciated. Many thanks Jon From steve at REMOVE.THIS.cybersource.com.au Fri Jan 12 06:44:33 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 12 Jan 2007 22:44:33 +1100 Subject: Learning Python book, new edition? References: Message-ID: On Fri, 12 Jan 2007 04:50:21 -0600, Steven Wayne wrote: [snip stupid disclaimer and response to it] > Unlawful how? You've already given permission for an "agent responsible > for delivering the message" to broadcast it around the world. > > Sorry for the rant, but I'm an email admin and I've just been told about > the change to UK law. What change to UK law? > I'm giving our legal department even more grief. For those interested in an amateur analysis of email disclaimers: http://goldmark.org/jeff/stupid-disclaimers/ If you get a Forbidden error, try going to the top level of the site first http://goldmark.org/ and navigating down by following links. Try not to laugh at all the "an error occurred while processing this directive" messages. -- Steven. From theller at ctypes.org Thu Jan 4 04:10:07 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 04 Jan 2007 10:10:07 +0100 Subject: where to ask questions related to comtypes? In-Reply-To: <1167891509.842292.125420@i80g2000cwc.googlegroups.com> References: <1167891509.842292.125420@i80g2000cwc.googlegroups.com> Message-ID: wcc schrieb: > Hello group, > > Is there a separate mailing list for comtypes? Or this is the > appropriate place to post questions related to this package(from Thomas > Heller)? It seems the python-win32 mailing list is the place where the most COM knowledge is, so that would be most appropriate. Other places are *this* list or the ctypes-users lists (since comtypes is based on ctypes). Thomas From gagsl-py at yahoo.com.ar Sun Jan 7 14:07:56 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 11:07:56 -0800 Subject: find a .py path In-Reply-To: References: <0Nunh.45640$gl2.30462@newsfe16.lga> Message-ID: <1168196876.449368.111080@q40g2000cwq.googlegroups.com> On 5 ene, 13:33, Laszlo Nagy wrote: > Be aware with this. It is different when you do > > /usr/bin/python prog.py > > and > > ./prog.py > > In the first case, sys.argv[0] will be /usr/bin/python! No, sys.argv[0] is always the running script, and sys.argv[1] the first argument after the script, and so on. It doesn't matter if you call python implicitely, or with other options. Try this: /usr/bin/python -i -u -O prog.py -- Gabriel Genellina From steven.bethard at gmail.com Wed Jan 31 16:41:43 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 31 Jan 2007 14:41:43 -0700 Subject: SyntaxError: 'return' outside function In-Reply-To: <1170278702.599741.212420@l53g2000cwa.googlegroups.com> References: <1170278702.599741.212420@l53g2000cwa.googlegroups.com> Message-ID: Melih Onvural wrote: > Has anyone seen this error before and been able to solve it? I can't > seem to find anything that leads to a solution. I found this post > http://zope.org/Collectors/Zope/1809, but can't really understand it. > I've attached my code below to see if anything looks funny. It happens > at the very last return at the end. Thanks in advance, > > --melih > > ===========Code======== > > def legiturl(self, url): > # this breaks down the url into 6 components to make sure it's > "legit" > t = urlparse.urlparse(url) > > if t[0] != 'http': > return "" > > # remove URL fragments, but not URL > if len(t[5]) > 0: > url = urlparse.urlunparse((t[0],t[1],t[2],"","","")) > t = urlparse.urlparse(url) > > # stupid parser sometimes leaves frag in path > x = find(t[2], '#') > if x >= 0: > return "" Looks like you're mixing tabs and spaces. Your "return" statement is outside the "legiturl" function. Steve From wccppp at gmail.com Thu Jan 4 02:27:57 2007 From: wccppp at gmail.com (wcc) Date: 3 Jan 2007 23:27:57 -0800 Subject: question on creating class Message-ID: <1167895677.041759.230190@42g2000cwt.googlegroups.com> Hello, How do I create a class using a variable as the class name? For example, in the code below, I'd like replace the line class TestClass(object): with something like class eval(className) (object): Is it possible? Thanks for your help. className = "TestClass" class TestClass(object): def __init__(self): print "Creating object of TestClass..." def method1(self): print "This is a method." if __name__ == "__main__": o = TestClass() o.method1() -- wcc From Barry.Carroll at psc.com Wed Jan 17 14:31:32 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 17 Jan 2007 11:31:32 -0800 Subject: *POLL* How many sheeple believe in the 911 fairy tale and willingto accept an Orwellian doublespeak and enslavement world ? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A81@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: st911 at rock.com [mailto:st911 at rock.com] > Sent: Wednesday, January 17, 2007 11:05 AM > To: python-list at python.org > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > > Robert Hicks wrote: > > Please, none of the real facts points to anything else except what > > actually happened. Two planes hit two towers and they came down. > > The issue is the causality of the towers coming down. > > A magician pulls appears to cast a spell > and out comes a rabbit out of his hat. There will always be fools who > will accept this causality and others who know better the laws of > conservation. > Ladies and Gentlemen: PLEASE take this discussion to a more appropriate forum. There are many forums where people will be happy to debate this: physics, firefighting, metallurgy, geopolitics, etc. This forum is about the Python programming language. Let's keep it that way. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From soyouthinkimgonnalikethis at hotmail.com Thu Jan 4 13:52:41 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Thu, 04 Jan 2007 13:52:41 -0500 Subject: what is this? In-Reply-To: <504v40F1ebv3sU1@mid.individual.net> Message-ID: >From: Paul Watson >Probably most helpful to you is: > >http://developer.mozilla.org/es4/proposals/slice_syntax.html Oh, the step. Okay, thanks ;) Eric _________________________________________________________________ Communicate instantly! Use your Hotmail address to sign into Windows Live Messenger now. http://get.live.com/messenger/overview From theinvisable_man at yahoo.com Fri Jan 19 03:59:47 2007 From: theinvisable_man at yahoo.com (JCH) Date: Fri, 19 Jan 2007 08:59:47 GMT Subject: ^*^*^^ Hot Smutty Videos ^*^*^ Message-ID: <7M%rh.686217$1T2.240423@pd7urf2no> An HTML attachment was scrubbed... URL: From pierre.imbaud at laposte.net Fri Jan 12 11:42:30 2007 From: pierre.imbaud at laposte.net (Imbaud Pierre) Date: Fri, 12 Jan 2007 17:42:30 +0100 Subject: module file Message-ID: <45a7ba78$0$316$426a74cc@news.free.fr> I am willing to retrieve the file an imported module came from; module.__file__, or inspect.getfile(module) only gives me the relative file name. How do I determine the path? Its obviously possible from python: ipython displays the information (interactively: *module?*). Python 2.4 on Suse 9.3 (clueless, I guess) From tony at PageDNA.com Mon Jan 1 14:28:25 2007 From: tony at PageDNA.com (Tony Lownds) Date: Mon, 1 Jan 2007 11:28:25 -0800 Subject: PEP 3107 Function Annotations for review and comment In-Reply-To: <1167673695.249834.40100@a3g2000cwd.googlegroups.com> References: <1167568000.728842.170160@48g2000cwx.googlegroups.com> <1167673695.249834.40100@a3g2000cwd.googlegroups.com> Message-ID: On Jan 1, 2007, at 9:48 AM, Kay Schluehr wrote: > Good. There is still one issue. I understand that you don't want to > fix > the semantics of function annotations but to be usefull some > annotations are needed to express function types. Using those > consistently with the notation of the enhanced function statement I > suggest introducing an arrow expression and an __arrow__ special > function: > > expr: arrow_expr ('->' arrow_expr)* > arrow_expr: xor_expr ('|' xor_expr)* > I agree with the use case and I am in favor of this addition despite the drawbacks below. While overloading __eq__ is a decent alternative, the -> operator is so much nicer (IMO). The precedence seems right: Function(A) -> B | C <=> Function(A) -> (B | C) Most operators special method names refer to the action or operation rather that the symbol, eg __or__, not __vbar__. Also, since the token is called RARROW, __arrow__ / __rarrow__ would be potentially easy to mix up. There might be opposition to adding an operator whose meaning in C is very different. Also the operator as suggested does not have any meaning on any built in objects, which is odd. We could add a meaning for ints/bools: http://mathworld.wolfram.com/Implies.html If that is reasonable I would suggest calling the special method __implies__ and putting the slot on PyNumberMethods. If that's just silly, I suggest calling the special method __returns__. We'll see what others say :) Thanks for the suggestion! -Tony From bearophileHUGS at lycos.com Thu Jan 18 05:57:56 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Jan 2007 02:57:56 -0800 Subject: A note on heapq module In-Reply-To: <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> Message-ID: <1169117876.063858.56570@s34g2000cwa.googlegroups.com> Steven Bethard: > Antoon Pardon: > > For me, your class has the same drawback as the heappush, heappop > > procedurers: no way to specify a comparision function. > > Agreed. I'd love to see something like ``Heap(key=my_key_func)``. It can be done, but the code becomes more complex and hairy: http://rafb.net/p/iCCmDz16.html (If someone spots a problem please tell me, thank you.) Bye, bearophile From tiedon_jano at hotmail.com Mon Jan 8 12:37:25 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Mon, 08 Jan 2007 17:37:25 GMT Subject: Why less emphasis on private data? In-Reply-To: References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <%Isoh.22447$X97.12337@newsfe18.lga> Message-ID: Neil Cerutti kirjoitti: > On 2007-01-08, hg wrote: >> sturlamolden wrote: >> >>> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that >>> if an object's 'internal' variables or states cannot be kept private, >>> programmers get an irresistible temptation to mess with them in >>> malicious ways. But if you are that stupid, should you be programming >>> in any language? The most widely used language is still C, and there is >>> no concept of private data in C either, nor is it needed. >> >> void test(void) >> { >> static int i; >> } >> >> >> Do you agree that i is "private" to test ? > > In C one uses the pointer to opaque struct idiom to hide data. > For example, the standard FILE pointer. > To surlamolden: I don't know how you define private, but if one defines in C an external static variable i.e. a variable outside any functions, on the file level, the scope of the variable is that file only. To hg: One does not need in C the static keyword to make a variable defined inside a function i.e. a so called 'automatic variable' private to that test. Automatic variables are private to their function by definition. The static keyword makes the variable permanent i.e. it keeps its value between calls but it is of course private also. To Neil Cerutti: If a programmer in C has got a pointer to some piece of memory, that piece is at the mercy of the programmer. There's no data hiding at all in this case. To whom it may concern: please stop comparing C and Python with regard to privacy and safety. They are two different worlds altogether. Believe me: I've been in this world for 2.5 years now after spending 19 years in the C world. Cheers, Jussi From justask at acme.com Sat Jan 20 01:49:22 2007 From: justask at acme.com (Vincent Delporte) Date: Sat, 20 Jan 2007 07:49:22 +0100 Subject: Code reformater? Message-ID: Hello When I copy/paste Python code from the web, every so often, the TABs are wrong, which means that the code won't work and I have to manually reformat the code. Is there a code reformater that can parse the code to make it right? Thanks. From elrondrules at gmail.com Tue Jan 30 14:07:39 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 30 Jan 2007 11:07:39 -0800 Subject: Convert raw data to XML In-Reply-To: References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> Message-ID: <1170184059.739808.244660@s48g2000cws.googlegroups.com> On Jan 29, 8:54 pm, "Gabriel Genellina" wrote: > En Mon, 29 Jan 2007 23:42:07 -0300, escribi?: > > > For example the raw data is as follows > > > SomeText > Description>PassorFail > > > without spaces or new lines. I need this to be written into an XML > > file as > > [same content but nicely indented] > > Is the file supposed to be processed by humans? If not, just write it as > you receive it. > Spaces and newlines and indentation are mostly irrelevant on an xml file. > > -- > Gabriel Genellina the reason I wanted to write it as a file was to parse the file, look for a specific attribute and execute a set of commands based on the value of the attribute.. also i needed to display the output of the http post in a more readable format.. From smusnmrNOSPAM at yahoo.com Thu Jan 4 03:13:22 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Thu, 4 Jan 2007 09:13:22 +0100 Subject: pow() works but sqrt() not!? Message-ID: Hi all, this is a newbie question on : Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 PC with WinXP In http://www.python.org/doc/2.3.5/lib/module-math.html I read: "sqrt( x) Return the square root of x." Now the test for module math with function pow(): --------------------------------------------------- >>> pow(9,9) 387420489 Fine, but sqrt() fails: ------------------- >>> sqrt(9) I get this error message 'Traceback (most recent call last): File "", line 1, in sqrt(9) NameError: name 'sqrt' is not defined' Same for sin() and cos(). ">>> Import math" does not help. Will I have to define the sqrt() function first? If so, how? Please help! Thank you, Siggi From sturlamolden at yahoo.no Thu Jan 11 07:02:17 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 11 Jan 2007 04:02:17 -0800 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <7x8xga215f.fsf@ruckus.brouhaha.com> Message-ID: <1168516936.890690.235300@p59g2000hsd.googlegroups.com> robert wrote: > Thus communicated data is "serialized" - not directly used as with threads or with custom shared memory techniques like POSH object sharing. Correct, and that is precisely why MPI code is a lot easier to write and debug than thread code. The OP used a similar technique in his 'parallel python' project. This does not mean that MPI is inherently slower than threads however, as there are overhead associated with thread synchronization as well. With 'shared memory' between threads, a lot more fine grained synchronization ans scheduling is needed, which impair performance and often introduce obscure bugs. From arkanes at gmail.com Thu Jan 18 10:14:56 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 18 Jan 2007 09:14:56 -0600 Subject: Catching wx events In-Reply-To: <1169129536.879657.113130@v45g2000cwv.googlegroups.com> References: <1169129536.879657.113130@v45g2000cwv.googlegroups.com> Message-ID: <4866bea60701180714y14cb76b2p9b9b602acccc1bcb@mail.gmail.com> On 18 Jan 2007 06:12:17 -0800, Cruelemort wrote: > Hello all, > > I am new to this group (and new to Python) and was hoping someone would > be able to help me with something, it is not so much a problem it is > more of a general interest query about something i have a solution too > but am not sure it is the correct one. > > I have a class that contains a string ID and a name, and a list > containing a few objects of this type, i need to loop through this list > and create a button for each object (with the name as the label) i have > done this with the following code - > > for chan in self._channellist: > channelbutton = wx.Button(self, id=-1, > label=chan.getName()) > > channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged) > > My question is this - in the _channelChanged method, how do i know > which button has been pressed when i enter the channel changed method, > and so how do i retrieve the appropriate object depending on which > button has been pressed? > > I have potentially solved this problem using the UserData property in a > sizer, i have added all the buttons to a sizer for display purposes and > so SizerItem objects have been created, i can then set the original > object to the UserData object by putting the following line of code in > the loop > > sizeritem = > self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan) > > This way i can retrieve the item in the _channelChanged method with the > following - > > def _channelChanged(self, event): > eventobj = event.GetEventObject() > chan = self.topsizer.GetItem(eventobj).GetUserData() > > > This works fine but by looking at the API it would appear the UserData > property is not really designed for this use ("userData - Allows an > extra object to be attached to the sizer item, for use in derived > classes when sizing information is more complex than the proportion and > flag will allow for"). > > Another option would be to derive my own Button class and include the > object in there. > > Any advice on the best way to solve this problem would be appreciated. > Exactly how I would do it depends on the rest of the application. I would probably derive my own button - never be afraid to subclass. You could also generate the buttons IDs up front, and maintain a mapping between the IDs and the channels, like so: self.mapper = {} for channel in self.channels: id = wx.NewId() self.mapper[id] = channel channelbutton = wx.Button(self, id=id, label=channel.getName()) def channelChanged(self, event): channel = self.mapper[event.Id] You could also use closures (lambdas or via a factory function) to bind the channel at the time you create the button: for channel in self.channels: channelbutton = wx.Button(self, label=channel.getName()) self.Bind(wx.EVT_BUTTON, lambda event: self.channelChanged(channel), source=channelbutton) def channelChanged(self, channel): print "Channel changed to ", channel.getName() From tomerfiliba at gmail.com Thu Jan 25 11:50:11 2007 From: tomerfiliba at gmail.com (gangesmaster) Date: 25 Jan 2007 08:50:11 -0800 Subject: free variables /cell objects question In-Reply-To: References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> <1169725374.504546.153890@v33g2000cwv.googlegroups.com> <7xirevuw5s.fsf@ruckus.brouhaha.com> Message-ID: <1169743811.129419.80400@v45g2000cwv.googlegroups.com> [Steven] > My solution is, don't try to have one function do too much. Making a list > of foos should be a separate operation from making a single foo: that's exactly what my second example does (as well as my production code) [Paul] > But it does work as expected, if your expectations are based on what > closures actually do. yet, i find what closures actually do, to be logically wrong. moreover, it means the frame object must be kept alive for no reason... or in my case, two frame objects per foo-function. > The Python idiom is: ... > def foo(n=n): besides of being ugly, the def f(n=n) idiom is very bad, programatically speaking. what if the user chooses to be a smartass and call with n = 7? or what if the function's signature is meaningful? (as it is in my case) anyway, this talk is not going anywhere. thanks for the info, and i'll see how i manage to optimize my code from here. -tomer On Jan 25, 4:51 pm, Steven D'Aprano wrote: > On Thu, 25 Jan 2007 04:29:35 -0800, Paul Rubin wrote: > > "gangesmaster" writes: > >> what i see as a bug is this code not working as expected: > > >> >>> def make_foos(names): > >> ... funcs = [] > >> ... for n in names: > >> ... def foo(): > >> ... print "my name is", n > >> ... funcs.append(foo) > >> ... return funcs > > > But it does work as expected, if your expectations are based on what > > closures actually do. > > >> i have to create yet another closure, make_foo, so that the name > >> is correctly bound to the object, rather than the frame's slot: > > > The Python idiom is: > > > def make_foos(names): > > funcs = [] > > for n in names: > > def foo(n=n): > > print "my name is", n > > funcs.append(foo) > > return funcs > > > The n=n in the "def foo" creates the internal binding that you need.Hmmm... I thought that the introduction of nested scopes removed the need > for that idiom. Its an ugly idiom, the less I see it the happier I am. > > And I worry that it will bite you on the backside if your "n=n" is a > mutable value. > > My solution is, don't try to have one function do too much. Making a list > of foos should be a separate operation from making a single foo: > > >>> def makefoo(name):... def foo(): > ... return "my name is " + name > ... return foo > ...>>> makefoo("fred")() > 'my name is fred' > >>> def makefoos(names):... foos = [] > ... for name in names: > ... foos.append(makefoo(name)) > ... return foos > ...>>> L = makefoos(["fred", "wilma"]) > >>> L[0]() > 'my name is fred' > >>> L[1]()'my name is wilma' > > That makes it easier to do unit testing too: you can test your makefoo > function independently of your makefoos function, if that's important. > > If you absolutely have to have everything in one function: > > >>> def makefoos(names):... def makefoo(name): > ... def foo(): > ... return "my name is " + name > ... return foo > ... L = [] > ... for name in names: > ... L.append(makefoo(name)) > ... return L > ...>>> L = makefoos(["betty", "barney"]) > >>> L[0]() > 'my name is betty' > >>> L[1]()'my name is barney' > > Best of all, now I don't have to argue as to which binding behaviour is > more correct for closures!!! *wink* > > -- > Steven. From puttaramakrishna at gmail.com Thu Jan 11 02:24:12 2007 From: puttaramakrishna at gmail.com (prk) Date: 10 Jan 2007 23:24:12 -0800 Subject: Print message with Colors Message-ID: <1168500252.143831.235250@i56g2000hsf.googlegroups.com> Hi Folks, Is there any procesure for print messages with colors. Ex: print "Welcome" Comment: Here i want to see the welcome message in Red Color. Regards, Ram From codecraig at gmail.com Mon Jan 8 13:10:23 2007 From: codecraig at gmail.com (abcd) Date: 8 Jan 2007 10:10:23 -0800 Subject: More Efficient fnmatch.fnmatch for multiple patterns? Message-ID: <1168279822.921033.267210@v33g2000cwv.googlegroups.com> I am using fnmatch.fnmatch to find some files. The only problem I have is that it only takes one pattern...so if I want to search using multiple patterns I have to do something like.... patterns = ['abc*.txt', 'foo*'] for p in patterns: if fnmatch.fnmatch(some_file_name, p): return True ...is there a built-in function that will match using multiple patterns? From sebastien.thur at laposte.net Wed Jan 3 08:24:10 2007 From: sebastien.thur at laposte.net (seb) Date: 3 Jan 2007 05:24:10 -0800 Subject: convert frames from mpeg to array Message-ID: <1167830650.673687.103330@v33g2000cwv.googlegroups.com> Hi, I need to convert each frame from a movie (mpeg for example) to an array (in order to do some computation) and then back to a video format mpeg for example. Do you know of any tools ? The equipment : ------------------------ I got myself an IP axis camera with wich I am playing to trying to do some shape recognition. My PC is running winXP SP2. The plan is : ------------------ 1) to manage to record the movies to my hard disk (in mpeg format for example) 2) to analyse the films in order to tests various algorythms / computation 3) to generate the transformed frame back to mpeg (or any format). What is already done is : ------------------------------------- 1) record to hard disk is easily donne using vlc for example vlc "http://192.168.0.90/axis-cgi/mjpg/video.cgi?fps=30&nbrofframes=0" --sout file/ts:test.mpg The problem is point 2 --------------------------------- I have tried to use pygame (on winXP) but it seems that it does not suppport movies. Pycar does not run on my PC. I have looked for some other tools but without any success. There is possibily a python binding to vlc but I am not sure of what can be done with it. I thank you in advance for taking the time to read this mail. Best regards. Seb. From pibizza at gmail.com Sat Jan 13 09:34:19 2007 From: pibizza at gmail.com (PaoloB) Date: 13 Jan 2007 06:34:19 -0800 Subject: Barcode recognition in Python In-Reply-To: <87zm8n6ozr.fsf@gmail.com> References: <1168676514.115592.181620@v45g2000cwv.googlegroups.com> <87zm8n6ozr.fsf@gmail.com> Message-ID: <1168698859.441778.117650@51g2000cwl.googlegroups.com> Jorge Godoy wrote: > "PaoloB" writes: > > > Hi everyone, > > > > I am searching for a python library for barcode recognition. We have > > developed a rather complex application for document tracking and > > document management in python/Zope, called PAFlow (www.paflow.it: > > sorry, most of the information is in Italian...). > > > > As our project is completely free software, we will need a library that > > is free software too. > > > > Is there something like this in python ? > > Sorry, but what do you mean by "barcode recognition"? A barcode reader > already decodes the barcode and sends the decoded output. If it is one > plugged in a keyboard port, for example, reading the barcode or typing the > "message" is exactly the same thing. > > Or are you willing some kind of OCR to process the barcodes without a barcode > reader (why having barcodes then?)? > Hi Jorge, basically we are trying to do exactly this. Our process works as follows: - an operator receives a paper document, compiles a series of data on a computer form and produces a bar code stamp, that he puts on the document. - the document received during the day are put on a mass scanner. The documents are sent to a specific e-mail address; - the system reads the scanned documents, and based on the barcodes, associate the documents to the information already present on the system. So, yes, we have to make OCR for barcodes. Ciao PaoloB From Major27104 at aol.com Thu Jan 18 19:35:04 2007 From: Major27104 at aol.com (Major27104 at aol.com) Date: Thu, 18 Jan 2007 19:35:04 EST Subject: Free Downloads, Wallpapers, Games, Eroticgames, Handy-Logos and much more Message-ID: From jeremit0 at gmail.com Tue Jan 30 10:35:17 2007 From: jeremit0 at gmail.com (jeremito) Date: 30 Jan 2007 07:35:17 -0800 Subject: Help me override append function of list object Message-ID: <1170171317.866549.261060@a34g2000cwb.googlegroups.com> I have created a class that inherits from the list object. I want to override the append function to allow my class to append several copies at the same time with one function call. I want to do something like: import copy class MyList(list): __init__(self): pass def append(self, object, n=1): for i in xrange(n): self.append(copy.copy(object)) Now I know this doesn't work because I overwrite append, but want the original functionality of the list object. Can someone help me? Thanks, Jeremy From ptmcg at austin.rr.com Mon Jan 29 15:25:02 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 29 Jan 2007 12:25:02 -0800 Subject: List Behavior when inserting new items In-Reply-To: <1170099535.989235.35800@a75g2000cwd.googlegroups.com> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> <1170099535.989235.35800@a75g2000cwd.googlegroups.com> Message-ID: <1170102302.883700.87810@m58g2000cwm.googlegroups.com> > py> def __init__(self, arg = []): > py> self.__list = arg Please don't perpetuate this bad habit!!! "arg=[]" is evaluated at compile time, not runtime, and will give all default-inited llists the same underlying list. The correct idiom is: def __init__(self, arg = None): if arg is not None: self.__list = arg else: self.__list = [] -- Paul From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 06:13:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 19 Jan 2007 22:13:45 +1100 Subject: Traversing the properties of a Class References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> Message-ID: On Thu, 18 Jan 2007 18:03:41 +0000, Neil Cerutti wrote: > On 2007-01-18, EdG wrote: >> For debugging purposes, I would like to traverse the class >> listing out all the properties. > > This is the first thing that came to mind. > > def show_properties(cls): > for attr in dir(cls): > if isinstance(getattr(cls, attr), property): > print attr Funny. The first thing that came to my mind was, "Thank you for sharing. Did you have a question?" *wink* -- Steven. From deets at nospam.web.de Tue Jan 30 04:38:04 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 Jan 2007 10:38:04 +0100 Subject: Help me understand this References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> <1170146755.446429.90720@v45g2000cwv.googlegroups.com> Message-ID: <528hvsF1lrmsgU1@mid.uni-berlin.de> Beej wrote: > On Jan 29, 11:47 pm, Steven D'Aprano > wrote: >> Outside of a print statement (and also an "except" statement), commas >> create tuples. > > And function calls: > >>>> 3, > (3,) >>>> type(3,) > >>>> type((3,)) > > > But here's one I still don't get: > >>>> type(2) > >>>> type((2)) > >>>> (2).__add__(1) > 3 >>>> 2.__add__(1) > File "", line 1 > 2.__add__(1) > ^ > SyntaxError: invalid syntax Because 2. is the start of a float-literal. That isn't distinguishable for the parsere otherwise. Diez From gagsl-py at yahoo.com.ar Tue Jan 16 22:00:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Jan 2007 00:00:52 -0300 Subject: How can i eval subindex on list[ ][ ] ? In-Reply-To: <1168988937.512029.192800@q2g2000cwa.googlegroups.com> References: <1168988937.512029.192800@q2g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070116235803.0466cb30@yahoo.com.ar> At Tuesday 16/1/2007 20:08, jairodsl wrote: >Excuse me, i was trying in too many ways but i couldnt access subindex >on a list , the problem is the next: > >I have > >indif=[[0,'A'],[1,'B'],[2,'C'],[3,'D']] > >and > >indic=[[0,'B'],[1,'C'],[2,'D'],[3,'E']] > >i need to eval if indic[i][j] is equal to indif[i][j] > >I used a double for but i had got "list index out of range". How can i >do ??? Posting your actual code would help. indif[i][j] should be fine, if i is between 0 and 3 inclusive, and j is 0 or 1. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From not at set.se Tue Jan 23 16:27:26 2007 From: not at set.se (Daniel Jonsson) Date: Tue, 23 Jan 2007 22:27:26 +0100 Subject: Noob Question: Force input to be int? References: <1169546377.017596.43840@k78g2000cwa.googlegroups.com> Message-ID: Ah, thank you for the respone! I have not gotten around to test it yet, but I hope it will work! :) -Daniel 2007-01-23 10:59:37 wd.jonsson at gmail.com wrote in message <1169546377.017596.43840 at k78g2000cwa.googlegroups.com> > Hello everyone! > I have a piece of code that looks like this: > > if len(BuildList) > 0: > print "The script found %d game directories:" % len(BuildList) > print > num = 0 > for i in BuildList: > print str(num) +" " + i > num = num + 1 > print > print "Select a build number from 0 to " + str(len(BuildList) - 1) > buildNum = int(raw_input('Select build #> ')) > > while buildNum > (len(BuildList) -1) or buildNum <= -1: > print > print "Error: Invalid build number!" > print "Select a build number from 0 to " + str(len(BuildList) - > 1) > print > buildNum = int(raw_input('Select build: ')) > > The problem is with the while buildNum-loop. If the user enters a > non-numeric value in the buildNum input, the scripts throws an > exception. I need to constrict the user to ONLY use integers in the > input box. How can I solve this issue? From kbk at shore.net Fri Jan 19 22:15:13 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 19 Jan 2007 22:15:13 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200701200315.l0K3FD59009106@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 423 open ( +2) / 3539 closed ( +9) / 3962 total (+11) Bugs : 960 open ( -3) / 6446 closed (+20) / 7406 total (+17) RFE : 258 open ( +3) / 249 closed ( +3) / 507 total ( +6) New / Reopened Patches ______________________ Add aliases for latin7/9/10 charsets (2007-01-13) http://python.org/sf/1634778 opened by Christoph Zwerschke htonl et al accept negative ints (2007-01-14) CLOSED http://python.org/sf/1635058 opened by Mark Roberts Logging Module - followfile patch (2006-11-17) CLOSED http://python.org/sf/1598415 reopened by cjschr CSV DictWriter Errors (2007-01-14) http://python.org/sf/1635454 opened by Mark Roberts strptime %F and %T directives (2007-01-14) CLOSED http://python.org/sf/1635473 opened by Mark Roberts File Read/Write Flushing Patch (2007-01-16) http://python.org/sf/1636874 opened by jurojin urllib: change email.Utils -> email.utils (2007-01-16) http://python.org/sf/1637157 opened by Russell Owen urllib2: email.Utils->email.utils (2007-01-16) http://python.org/sf/1637159 opened by Russell Owen smtplib email renames (2007-01-16) http://python.org/sf/1637162 opened by Russell Owen Add httponly to Cookie module (2007-01-17) http://python.org/sf/1638033 opened by Arvin Schnell compiler.pycodegen causes crashes when compiling 'with' (2007-01-17) http://python.org/sf/1638243 opened by kirat Fix to the long("123\0", 10) problem (2007-01-18) http://python.org/sf/1638879 opened by Calvin Spealman email.utils.parsedate documentation (2007-01-19) http://python.org/sf/1639973 opened by Mark Roberts Patches Closed ______________ platform.py support for IronPython (2006-09-23) http://python.org/sf/1563842 closed by lemburg Small upgrades to platform.platform() (2005-11-10) http://python.org/sf/1352731 closed by lemburg pybench support for IronPython (2006-09-23) http://python.org/sf/1563844 closed by lemburg Py3k: Fix pybench so it runs (2007-01-12) http://python.org/sf/1634499 closed by gvanrossum Bug fixes for int unification branch (2006-12-20) http://python.org/sf/1619846 closed by gvanrossum htonl et al accept negative ints (2007-01-14) http://python.org/sf/1635058 closed by gvanrossum Logging Module - followfile patch (2006-11-17) http://python.org/sf/1598415 closed by vsajip strptime %F and %T directives (2007-01-14) http://python.org/sf/1635473 closed by bcannon BSD version of ctypes.util.find_library (2006-12-07) http://python.org/sf/1610795 closed by theller New / Reopened Bugs ___________________ Problem running a subprocess (2007-01-13) http://python.org/sf/1634739 opened by Florent Rougon locale 1251 does not convert to upper case properly (2007-01-13) http://python.org/sf/1634774 opened by Ivan Dobrokotov Little mistake in docs (2007-01-14) http://python.org/sf/1635217 opened by anatoly techtonik Add registry functions to windows postinstall (2007-01-14) http://python.org/sf/1635335 opened by anatoly techtonik expanduser tests in test_posixpath fail if $HOME ends in a / (2007-01-14) CLOSED http://python.org/sf/1635353 opened by Marien Zwart Add command line help to windows unistall binary (2007-01-14) http://python.org/sf/1635363 opened by anatoly techtonik ConfigParser does not quote % (2007-01-15) http://python.org/sf/1635639 opened by Mark Roberts Interpreter seems to leak references after finalization (2007-01-15) http://python.org/sf/1635741 opened by B Sizer description of the beta distribution is incorrect (2007-01-15) CLOSED http://python.org/sf/1635892 opened by elgordo Newline skipped in "for line in file" (2007-01-16) http://python.org/sf/1636950 opened by Andy Monthei Python-2.5 segfault with tktreectrl (2007-01-16) CLOSED http://python.org/sf/1637022 opened by klappnase Python 2.5 fails to build on AIX 5.3 (xlc_r compiler) (2007-01-16) http://python.org/sf/1637120 opened by Orlando Irrazabal mailbox.py uses old email names (2007-01-16) http://python.org/sf/1637167 opened by Russell Owen make_table in difflib does not work with unicode (2007-01-18) http://python.org/sf/1637850 opened by y-unno Problem packaging wx application with py2exe. (2007-01-17) CLOSED http://python.org/sf/1637943 opened by Indy typo http://www.python.org/doc/current/tut/node10.html (2007-01-17) CLOSED http://python.org/sf/1637952 opened by jim pruett langref: missing item in numeric op list (2007-01-17) CLOSED http://python.org/sf/1637967 opened by paul rubin Incorrect documentation for random.betavariate() (2007-01-18) CLOSED http://python.org/sf/1638627 opened by Troels Walsted Hansen Bugs Closed ___________ class derived from float evaporates under += (2007-01-11) http://python.org/sf/1633630 closed by gbrandl file.encoding doesn't apply to file.write (2004-06-07) http://python.org/sf/967986 closed by lemburg platform.libc_ver() fails on Cygwin (2004-04-02) http://python.org/sf/928297 closed by lemburg subprocess swallows empty arguments under win32 (2007-01-12) http://python.org/sf/1634343 closed by astrand htonl, ntohl don't handle negative longs (2006-12-20) http://python.org/sf/1619659 closed by gvanrossum expanduser tests in test_posixpath fail if $HOME ends in a / (2007-01-14) http://python.org/sf/1635353 closed by marienz time.strftime() accepts format which time.strptime doesnt (2007-01-11) http://python.org/sf/1633628 closed by bcannon SaveConfigParser.write() doesn't quote %-Sign (2006-11-27) http://python.org/sf/1603688 closed by gbrandl logging module / wrong bytecode? (2007-01-11) http://python.org/sf/1633605 closed by vsajip description of the beta distribution is incorrect (2007-01-15) http://python.org/sf/1635892 closed by rhettinger os.path.expandvars deletes things on w32 (2001-12-18) http://python.org/sf/494589 closed by sjoerd Python-2.5 segfault with tktreectrl (2007-01-16) http://python.org/sf/1637022 closed by loewis Problem packaging wx application with py2exe. (2007-01-17) http://python.org/sf/1637943 closed by bcannon typo http://www.python.org/doc/current/tut/node10.html (2007-01-17) http://python.org/sf/1637952 closed by gbrandl langref: missing item in numeric op list (2007-01-17) http://python.org/sf/1637967 closed by gbrandl Incorrect type in PyDict_Next() example code (2007-01-05) http://python.org/sf/1629125 closed by gbrandl website issue reporter down (2007-01-03) http://python.org/sf/1627036 closed by gbrandl Incorrect documentation for random.betavariate() (2007-01-18) http://python.org/sf/1638627 closed by loewis Garbage output to file of specific size (2007-01-08) http://python.org/sf/1630894 deleted by mculbert Forwarding events and Tk.mainloop problem (2006-05-05) http://python.org/sf/1482402 closed by loewis New / Reopened RFE __________________ csv.DictWriter: Include offending name in error message (2007-01-13) http://python.org/sf/1634717 opened by Gabriel Genellina Please provide rsync-method in the urllib[2] module (2007-01-13) http://python.org/sf/1634770 opened by Matthias Klose if __name__=='__main__' missing in tutorial (2007-01-17) http://python.org/sf/1637365 opened by Gabriel Genellina Empty class 'Object' (2007-01-17) http://python.org/sf/1637926 opened by kxroberto add type defintion support (2007-01-18) CLOSED http://python.org/sf/1639002 opened by djnet RFE Closed __________ logging.RotatingFileHandler has no "infinite" backupCount (2006-09-28) http://python.org/sf/1567331 closed by vsajip Print full exceptions as they occur in logging (2006-09-06) http://python.org/sf/1553380 closed by vsajip add type defintion support (2007-01-18) http://python.org/sf/1639002 closed by gbrandl From webraviteja at gmail.com Sat Jan 27 11:17:32 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 27 Jan 2007 08:17:32 -0800 Subject: Hi, I'm new to python In-Reply-To: <1169905027.776723.194140@a75g2000cwd.googlegroups.com> References: <1169905027.776723.194140@a75g2000cwd.googlegroups.com> Message-ID: <1169914652.807494.200330@a34g2000cwb.googlegroups.com> On Jan 27, 5:37 am, millbal... at yahoo.com wrote: > Hey Everyone > > Let me tell you all a little bit about my programming background so > you can get an idea of my capability, or lack of, dealing with p.l; > so far i've learned some visual basic when i was doing my a-levels.... > and thats about it lol. > > Basically i like the sound of python and its ease of use and would > like to know in depth more about it and its range of useage. Please > do tell me all you know, keeping in mind i am a n00b, so do be > gentle. :) > > Thanks > Millball54 Start Here http://www.python.org/doc/ There is a ton of documentation tailored to learners with differing skills. You might also want to pick up a book on Python. Be sure to read the docs, use Google, search this group for similar questions in the past before you post questions. They are great resources. If you have very basic questions, IRC (freenode has a Python channel), is a better option. When you post, make the question as specific as possible. Sometimes typing a good question itself gives you an answer. Ravi Teja. From steve at REMOVE.THIS.cybersource.com.au Mon Jan 8 05:37:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Jan 2007 21:37:55 +1100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> <7xlkke19he.fsf@ruckus.brouhaha.com> <7xirfiyn3y.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 07 Jan 2007 23:49:21 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> Just how often do you inherit from two identically-named classes >> both of which use identically-named private attributes? > > I have no idea how often if ever. You've established that there's a name conflict when you do so, which leads to bugs. So how often do you get bitten by that particular type of bug? > I inherit from library classes all > the time, without trying to examine what superclasses they use. If my > subclass happens to have the same name as a superclass of some library > class (say Tkinter) this could happen. Whether it ever DOES happen, I > don't know, I could only find out by examining the implementation > details of every library class I ever use, and I could only prevent it > by remembering those details. class MySubClass(SomeSuperclass): try: __my_private_attribute except AttributeError: __my_private_attribute = some_value else: raise ValueError("Name conflict with private attribute!") Problem solved. *wink* > That is an abstraction leak and is > dangerous and unnecessary. The name mangling scheme is a crock. How > often does anyone ever have a good reason for using it, Exactly. I never use it. The truth of the matter is, MyClass.__private is not private at all. It is still a public attribute with a slightly unexpected name. In other words, if you want to code defensively, you should simply assume that Python has no private attributes, and code accordingly. Problem solved. -- Steven. From apardon at forel.vub.ac.be Wed Jan 17 07:18:01 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2007 12:18:01 GMT Subject: A note on heapq module References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> Message-ID: On 2007-01-16, bearophileHUGS at lycos.com wrote: > In few minutes I have just written this quite raw class, it lacks > doctring (the same of the functions of the heapq module), it may > contain bugs still, I haven't tested it much. It's just a simple > wrapper around some of the functions of the heapq module (nsmallest and > nlargest are missing). Usually I use classes only when I need then, I > like functional programming enough, and this class seems to just slow > down the functions of the heapq module. But I think an improved class > similar to this one may be useful (added, replacing isn't necessary) > into the heapq module, because it can avoid cetain errors: I know what > Heaps are and how they work, but some time ago I have written a bug > into small program that uses the functions of the heapq module, because > I have added an item to the head of the heap using a normal list > method, breaking the heap invariant. With a simple class like this one > all the methods of your object keep the heap invariant, avoiding that > kind of bugs. (If you are interested I can improve this class some, > it't not difficult.) > > [ Heap class based on heapq ] For me, your class has the same drawback as the heappush, heappop procedurers: no way to specify a comparision function. Somewhere in my experimental code I work with line segments in two dimensions. Now in one place I want from the available segments the one in which the first point is farthest to the left. In a second place I want from the available segments the one in which the second point is farthest to the left. Both can be done with a heap, but currently I can't get both behaviours while using the same class and using the heapq module or your Heap class. -- Antoon Pardon From paroutyj at gdls.com Fri Jan 26 13:41:36 2007 From: paroutyj at gdls.com (paroutyj at gdls.com) Date: Fri, 26 Jan 2007 13:41:36 -0500 Subject: Problem embedding the Python interpreter and importing win32 extensions Message-ID: I have been playing around with this issue for a while and seen some previous posting trying to address the problem but I haven't seen any answers to the problem so I am reposting it in my quest for a solution. I am using python 2.2.3, because I am using some dSpace software (controldesk/automationdesk) that is based upon that version of python. I have some pre-compiled python modules that come with the dspace applications. I am pretty sure that those modules use win32com or pythoncom. I want to use those modules from a C/C++ application or DLL via an embedded interpreter. I can make it work, but it only works once. I get an error trying to import those modules again, even after uninitializing the interpreter (Py_Initialize) and re-initializing it (Py_Uninitialize). I thought may be using a new sub-interpreter would help but it doesn't so now I have no idea what I could try. Any ideas? This is an e-mail from General Dynamics Land Systems. It is for the intended recipient only and may contain confidential and privileged information. No one else may read, print, store, copy, forward or act in reliance on it or its attachments. If you are not the intended recipient, please return this message to the sender and delete the message and any attachments from your computer. Your cooperation is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyenyec at gmail.com Sun Jan 7 14:23:20 2007 From: nyenyec at gmail.com (nyenyec) Date: 7 Jan 2007 11:23:20 -0800 Subject: urlib.quote gives KeyError in Python 2.4.4 but workin 2.3.5 In-Reply-To: <1168195697.483795.71160@38g2000cwa.googlegroups.com> References: <1168195697.483795.71160@38g2000cwa.googlegroups.com> Message-ID: <1168197800.107994.143170@51g2000cwl.googlegroups.com> encode seems to solve my problem: >>> urllib.quote(u'\xe9'.encode('utf-8')) '%C3%A9' Cheers, nyenyec nyenyec wrote: > urllib.quote chokes on unicode in 2.4.4. > > >>> print sys.version > 2.4.4 (#1, Oct 18 2006, 10:34:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] > >>> urllib.quote(u"\xe9") > Traceback (most recent call last): > File "", line 1, in ? > File > "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/urllib.py", > line 1117, in quote > res = map(safe_map.__getitem__, s) > KeyError: u'\xe9' > > but it seems to work in Python 2.3.5 > > Python 2.3.5 (#1, Aug 19 2006, 21:31:42) > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys, urllib > >>> print sys.version > 2.3.5 (#1, Aug 19 2006, 21:31:42) > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] > >>> urllib.quote(u'\xe9') > '%E9' > > Is this a known bug? > > What's the workaround? > > Thanks, > nyenyec From paddy3118 at netscape.net Tue Jan 9 02:10:36 2007 From: paddy3118 at netscape.net (Paddy) Date: 8 Jan 2007 23:10:36 -0800 Subject: re.sub and re.MULTILINE In-Reply-To: <1168316266.374186.271310@42g2000cwt.googlegroups.com> References: <1168316266.374186.271310@42g2000cwt.googlegroups.com> Message-ID: <1168326636.436910.165360@v33g2000cwv.googlegroups.com> nyenyec wrote: > I feel like a complete idiot but I can't figure out why re.sub won't > match multiline strings: > > This works: > >>> re.search("^foo", "\nfoo", re.MULTILINE) > <_sre.SRE_Match object at 0x6c448> > > This doesn't. No replacement: > >>> re.sub("^foo", "bar", "\nfoo", re.MULTILINE) > '\nfoo' > > Why? > > Thanks, > nyenyec Check the arguments to re.sub. >>> re.sub('(?m)^foo', 'bar', '\nfoo', count=0) '\nbar' - Paddy. From pavlovevidence at gmail.com Tue Jan 16 02:11:26 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 15 Jan 2007 23:11:26 -0800 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: References: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> Message-ID: <1168931486.610893.250040@38g2000cwa.googlegroups.com> Ron Adam wrote: > There have been times where I would like assert to be a little more assertive > than it is. :-) > > ie.. not being able to turn them off with the -0/-00 switches, and having them > generate a more verbose traceback. Personally, I'd rather see it get less assertive, i.e., having it only work in a special debugging mode. That way people who haven't RTFM don't use it to make sure their input is correct. Carl Banks From AleydisGP at gmail.com Mon Jan 8 06:34:12 2007 From: AleydisGP at gmail.com (AleydisGP at gmail.com) Date: 8 Jan 2007 03:34:12 -0800 Subject: Working with Excel inside Python In-Reply-To: References: <1168205727.130771.257030@51g2000cwl.googlegroups.com> <1168218370.688414.171150@s80g2000cwa.googlegroups.com> Message-ID: <1168256052.090472.54890@s80g2000cwa.googlegroups.com> Sorry for my little knowledge on Python. Actually my knowledge is specific for automating geo-processing tasks within ESRI environment, but sometimes I need to automate some other tasks (like this one) which require more in-depth knowledge of this language. Lots of documentation are of no use when you don't know exactly what to look for or have a wrong idea of what to do. Thanks for the guidance. On 8 ene, 02:21, Dennis Lee Bieber wrote: > On 7 Jan 2007 17:06:10 -0800, "John Machin" > declaimed the following in comp.lang.python: > > > However I don't understand how a reasonable solution to the OP's > > requirement (translate a tab-separated file to a DBF file with a bit of > > slicing and dicing on the way) would have anything to do with .xls > > files, or Excel, or VB ... Only in that the original poster stated they were trying to > translate an Excel VBA "macro" into Python, and the malformed (for > Python) code appeared to be using Window's COM access to run all the > work via Excel (I presume via importing the TSV, performing the edits, > then exporting via some DBF compatible format -- ODBC?). > > I'd agree, however, that the specification of the task to be > performed does not, it would seem, require any of the clumsiness of > using Excel. Read the lines of the TSV file using proper specifications > to the Python CSV file handling module, edit the lines as needed, and > write them via an ODBC (or other) database adapter that generates the > desired DBF format... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ From tiedon_jano at hotmail.com Thu Jan 18 07:12:44 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 18 Jan 2007 12:12:44 GMT Subject: One more regular expressions question In-Reply-To: <1169121609.571152.214850@11g2000cwr.googlegroups.com> References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> <1169120317.437211.73660@m58g2000cwm.googlegroups.com> <1169121609.571152.214850@11g2000cwr.googlegroups.com> Message-ID: <0vJrh.74$6H1.13@read3.inet.fi> Victor Polukcht kirjoitti: > Great thanks. > > You post helped me so much! > > My resulting regexp is: > "(?P^(.*)\s*)\(((?P\d+))\)\s+((?P\d+))" > If it doesn't have to be a regex: #=================================================== s = '''\ Unassigned Number (1) 32 No Route To Destination (3) 12 Normal call clearing (16) 2654 User busy (17) 630 No user respond (18) 5 User alerting no answer (19) 16 Call rejected (21) 3 Destination out of order (27) 1 Invalid number format (28) 32 Normal unspecified (31) 32 No channel available (34) 2 Temporary failure (41) 11 Switching equipment congestion (42) 4 Resource unavailable unspecified (47) 2 Bearer capability not authorized (57) 73 Incomp. dest. / Non-existent CUG (88) 1 Recovery on timer expiry (102) 2 Interworking, unspecified (127) 5 ''' for row in s.split('\n')[:-1]: var1, var2 = row.split('(') var2, var3 = var2.split() var2 = var2[:-1] print var2, var3, var1 #=================================================== Cheers, Jussi From http Thu Jan 18 18:59:53 2007 From: http (Paul Rubin) Date: 18 Jan 2007 15:59:53 -0800 Subject: A note on heapq module References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> <1169117876.063858.56570@s34g2000cwa.googlegroups.com> <8NSdnf38_otYcjLYnZ2dnUVZ_tadnZ2d@comcast.com> <1169159235.864192.263210@v45g2000cwv.googlegroups.com> Message-ID: <7xk5zjyjgm.fsf@ruckus.brouhaha.com> Steven Bethard writes: > Heap(sequence=None, inplace=False) > KeyedHeap(key, sequence=None) > Of course, this approach ends up with a bunch of code duplication again. Maybe there's a way to use a metaclass that can make either type of heap but they'd share most methods. From rdiaz02 at gmail.com Sun Jan 21 18:13:03 2007 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Mon, 22 Jan 2007 00:13:03 +0100 Subject: Py 2.5 on Language Shootout In-Reply-To: <1169331552.918850.282920@a75g2000cwd.googlegroups.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> <45B23400.2010906@gmx.de> <1169321686.025356.120340@s34g2000cwa.googlegroups.com> <1169331552.918850.282920@a75g2000cwd.googlegroups.com> Message-ID: <624934630701211513t3a3e28a5ua7387c9ee2f5790e@mail.gmail.com> On 20 Jan 2007 14:19:12 -0800, Isaac Gouy wrote: > > Ramon Diaz-Uriarte wrote: > > On 20 Jan 2007 11:34:46 -0800, Isaac Gouy wrote: (...) > > > > > > And that's why the existence of CINT is such a stark reminder of the > > > separation between the language and the implementation. When people > > > think of C what do they think of - gcc? tiny-c? intel c? microsoft c? > > > some mythical C implementation? > > > > > > > > > > Really, this ain't my war. Sure, there are two things: the language > > and the implementation. But, for practical purposes, when most people > > today say Python they mean CPython, whereas if the say Scheme, they > > certainly need to say _which_ Scheme (I think only PLT is in the > > official shootout page; there are others in the beta tests). If people > > want to mean Jython or Stackless, they just say that. As for C, I > > think people will need to qualify what exactly they mean. > > > > I think all these issues do not really lead to confusion for most of > > us; certainly not if you go to the shootout page. But as I said, this > > ain't my war. I was simply pointing out that correcting one poster for > > talking about languages when referring to python was hair splitting. > > > > And I think we are all running in circles, because I guess we all > > agree. This is turning into what in Spain (a country of catholic > > tradition) we call a discussion about "the sex of the angels" (el sexo > > de los angeles), i.e., whether angels are male or female or something > > else. Since sexing angels is not my area of expertise, I'll just shut > > up (I actually don't really know why I even said anything about this > > issue; please, forgive my chatiness). > > > In England the corresponding expression is "Counting Angels on a > Pinhead" > http://dannyayers.com/2001/misc/angels.htm > Thanks, that is neat. I find the discussion on the sex of the angels, well, sexier. But we are probably a few hundred years late to start a catholic-protestant religious war here :-). R. > > > > Best, > > > > R. > > > > > > > > > > > > I think readers understood the previous poster. > > > > > > > > Best, > > > > > > > > R. > > > > > > > > > > Cheers, > > > > > > > > > > Carl Friedrich Bolz > > > > > > > > > > -- > > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > > > > > > > -- > > > > Ramon Diaz-Uriarte > > > > Statistical Computing Team > > > > Structural Biology and Biocomputing Programme > > > > Spanish National Cancer Centre (CNIO) > > > > http://ligarto.org/rdiaz > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > -- > > Ramon Diaz-Uriarte > > Statistical Computing Team > > Structural Biology and Biocomputing Programme > > Spanish National Cancer Centre (CNIO) > > http://ligarto.org/rdiaz > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From zion at ee.oulu.fi Sun Jan 28 21:12:55 2007 From: zion at ee.oulu.fi (Simo Hosio) Date: Mon, 29 Jan 2007 04:12:55 +0200 (EET) Subject: problems with pyzeroconf and linux In-Reply-To: <45bb6d30$0$49196$14726298@news.sunsite.dk> References: <45bb6d30$0$49196$14726298@news.sunsite.dk> Message-ID: On Sat, 27 Jan 2007, Damjan wrote: > >> I am trying to get pyzeroconf (http://sourceforge.net/projects/pyzeroconf) >> running on my machine but having trouble... Running the Zeroconf.py file >> seems to register the service, but is unable to find it. > > You should be running avahi.. it also comes python support. > > Here's an example that registers a CNAME that points to your hostname (that > avahi itself publishes) > > #! /usr/bin/env python > import avahi, dbus > from encodings.idna import ToASCII > > # Got these from /usr/include/avahi-common/defs.h > CLASS_IN = 0x01 > TYPE_CNAME = 0x05 > > TTL = 60 > > def publish_cname(cname): > bus = dbus.SystemBus() > server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, > avahi.DBUS_PATH_SERVER), > avahi.DBUS_INTERFACE_SERVER) > group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, > server.EntryGroupNew()), > avahi.DBUS_INTERFACE_ENTRY_GROUP) > > rdata = createRR(server.GetHostNameFqdn()) > cname = encode_dns(cname) > > group.AddRecord(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), > cname, CLASS_IN, TYPE_CNAME, TTL, rdata) > group.Commit() > > > def encode_dns(name): > out = [] > for part in name.split('.'): > if len(part) == 0: continue > out.append(ToASCII(part)) > return '.'.join(out) > > def createRR(name): > out = [] > for part in name.split('.'): > if len(part) == 0: continue > out.append(chr(len(part))) > out.append(ToASCII(part)) > out.append('\0') > return ''.join(out) > > if __name__ == '__main__': > import time, sys, locale > for each in sys.argv[1:]: > name = unicode(each, locale.getpreferredencoding()) > publish_cname(name) > try: > while 1: time.sleep(60) > except KeyboardInterrupt: > print "Exiting" > > > -- > damjan Hi, I actually tried Avahi also at first, but was having a lot of difficulties setting it up to my actual target environment (Maemo platform, based on Debian, and used on Nokia 770&N800 devices...). Probably this is anyhow an issue of Debian network configuration, so maybe I'll ask the lists there also. I will later utilize Avahi, if possible, so thanks for the code snippet. :) And if anyone knows what might be the propblem with Pyzeroconf and my dear Ubuntu, please tell me. Br, Simo From steve at REMOVE.THIS.cybersource.com.au Fri Jan 26 19:45:03 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 27 Jan 2007 11:45:03 +1100 Subject: assertions to validate function parameters References: Message-ID: On Fri, 26 Jan 2007 18:28:32 +0000, Matthew Woodcraft wrote: > I have a question for you. Consider this function: > > def f(n): > """Return the largest natural power of 2 which does not exceed n.""" > if n < 1: > raise ValueError > i = 1 > while i <= n: > j = i > i *= 2 > return j > > If I pass it an instance of MyNumericClass, it will return an int or a > long, not an instance of MyNumericClass. > > In your view, is this a weakness of the implementation? Should the > author of the function make an effort to have it return a value of the > same type that it was passed? Only if it makes sense in the context of the function. I'd say it depends on the principle of "least surprise": if the caller would expect that passing in a MyNumericClass or a float or a Rational should return the same type, then Yes, otherwise its optional. Numeric functions are probably the least convincing example of this, because in general people expect numeric functions to coerce arguments in not-always-intuitive ways, especially when they pass multiple arguments of mixed types. What should g(MyNumericClass, int, float, Rational) return? And it often doesn't matter, not if you're just doing arithmetic, because (in principle) any numeric type is compatible with any other numeric type. The principle of least surprise is sometimes hard to follow because it means putting yourself in the shoes of random callers. Who knows what they expect? One rule of thumb I use is to consider the function I'm writing, and its relationship to the argument. Would I consider that the result is somehow _made_from_ the argument? If so, then I should return the same type (unless there is a compelling reason not to). I'm NOT talking about implementation here, I'm thinking abstract functions. Whether your implementation actually transforms the initial argument, or creates a new piece of data from scratch, is irrelevant. In your above example, the result isn't "made from" the argument (although some implementations, using log, might do so). In abstract, the result is an integer that is chosen by comparison to the argument, not by construction from the argument. So it is unimportant for it to be the same type, and in fact the caller might expect that the result is an int no matter what argument he passes. -- Steven. From bdesth.quelquechose at free.quelquepart.fr Tue Jan 2 11:01:28 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Jan 2007 17:01:28 +0100 Subject: Can I beat perl at grep-like processing speed? In-Reply-To: References: Message-ID: <459a7bbe$0$693$426a74cc@news.free.fr> js a ?crit : > Just my curiosity. > Can python beats perl at speed of grep-like processing? Probably not. > > $ wget http://www.gutenberg.org/files/7999/7999-h.zip > $ unzip 7999-h.zip > $ cd 7999-h > $ cat *.htm > bigfile > $ du -h bigfile > du -h bigfile > 8.2M bigfile > > ---------- grep.pl ---------- > #!/usr/local/bin/perl > open(F, 'bigfile') or die; > > while() { > s/[\n\r]+$//; > print "$_\n" if m/destroy/oi; > } > ---------- END ---------- > ---------- grep.py ---------- > #!/usr/bin/env python > import re > r = re.compile(r'destroy', re.IGNORECASE) > > for s in file('bigfile'): > if r.search(s): print s.rstrip("\r\n") > ---------- END ---------- Please notice that you're also benchmarking IO here - and perl seems to use a custom, highly optimized IO lib, that is much much faster than the system's one. I once made a Q&D cat-like comparison of perl, Python and C on my gentoo-linux box, and the perl version was insanely faster than the C one. Now the real question is IMHO: is the Python version fast enough ? My 2 cents.. From gh at ghaering.de Sat Jan 13 20:15:37 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 14 Jan 2007 02:15:37 +0100 Subject: [ANN] pysqlite 2.3.3 released Message-ID: <45A98439.8050005@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.3.1 released ======================= I'm pleased to announce the availability of pysqlite 2.3.3. This is a bugfix release. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a relational database management system contained in a relatively small C library. It is a public domain project created by D. Richard Hipp. Unlike the usual client-server paradigm, the SQLite engine is not a standalone process with which the program communicates, but is linked in and thus becomes an integral part of the program. The library implements most of SQL-92 standard, including transactions, triggers and most of complex queries. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. pysqlite can be downloaded from http://pysqlite.org/ - Sources and Windows binaries for Python 2.5, 2.4 and Python 2.3 are available. ======= CHANGES ======= - - self->statement was not checked while fetching data, which could lead to crashes if you used the pysqlite API in unusual ways. Closing the cursor and continuing to fetch data was enough. - - Converters are stored in a converters dictionary. The converter name is uppercased first. The old upper-casing algorithm was wrong and was replaced by a simple call to the Python string's upper() method instead. - -Applied patch by Glyph Lefkowitz that fixes the problem with subsequent SQLITE_SCHEMA errors. - - Improvement to the row type: rows can now be iterated over and have a keys() method. This improves compatibility with both tuple and dict a lot. - - A bugfix for the subsecond resolution in timestamps. - - Corrected the way the flags PARSE_DECLTYPES and PARSE_COLNAMES are checked for. Now they work as documented. - - gcc on Linux sucks. It exports all symbols by default in shared libraries, so if symbols are not unique it can lead to problems with symbol lookup. pysqlite used to crash under Apache when mod_cache was enabled because both modules had the symbol cache_init. I fixed this by applying the prefix pysqlite_ almost everywhere. Sigh. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFFqYQ5dIO4ozGCH14RAlvkAKCAXPZJSPqX6lZMWvAgZPwbbznEXwCdEvPv d3deYn5TZsQ4xn2VEcw+WBE= =U221 -----END PGP SIGNATURE----- From bignose+hates-spam at benfinney.id.au Tue Jan 30 04:58:14 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Jan 2007 20:58:14 +1100 Subject: Diff between opening files in 'r' and 'r+' mode References: <1170149775.253373.318960@q2g2000cwa.googlegroups.com> Message-ID: <874pq8ygy1.fsf@benfinney.id.au> "raghu" writes: > i want to know the difference between 'r' mode and 'r+' mode > 1.i = open('c:\python25\integer.txt','w')-------->for writiing > i.write('hai')--------->written some content in text file > i = open('c:\python25\integer.txt','r')---->for reading > print i.read()---->for printing the contents in that text file > i = open('c:\python25\integer.txt','w')---------->for writing > i.write('how')-----------?Rewrite the contents > print i.read() > [MY QUESTION]:i want to read the text file contents cant it be done by > giving (print i.read())? > Before going to next question [I deleted all the contents in the text > file] This is amazingly hard to read. Can you please post your message again, this time using ordinary whitespace (e.g. a blank line) to separate program examples from other text. All the punctuation characters you're using have typographical meaning, and your arbitrary use of them for apparently decorative purposes make it difficult to see what you're trying to day. -- \ "Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again." -- Franklin P. | _o__) Jones | Ben Finney From mfmdevine at gmail.com Wed Jan 24 03:50:17 2007 From: mfmdevine at gmail.com (amadain) Date: 24 Jan 2007 00:50:17 -0800 Subject: Getting to an SSH account over a HTTP proxy In-Reply-To: References: <1169514995.916358.17030@11g2000cwr.googlegroups.com> Message-ID: <1169628615.639734.213190@d71g2000cwa.googlegroups.com> use pexpect to set the prompt after the login. class Login(General): """Class spawning an ssh expect instance""" def __init__(self, user, host, pwd, cfg_name=None, log=None): if cfg_name: self.testcell = test_config(cfg_name) self.spawn = pexpect.spawn("ssh %s@%s" % (user, host), [], 100) if log: self.spawn.logfile = log sshreply = self.spawn.expect(["Last login", "assword", "connecting"]) if sshreply == 1: self.spawn.sendline(pwd) self.spawn.expect("Last login") elif sshreply == 2: time.sleep(0.1) self.spawn.sendline("yes") print self.spawn.after Login(user, host, cfg_name, log) time.sleep(1) self.prompt=prompt_chg(self.spawn, "PROMPT:") self.spawn.sendline("uname -a") self.spawn.expect(self.prompt) On Jan 23, 10:28 am, Willi Richert wrote: > Am Dienstag, 23. Januar 2007 02:16 schrieb Nanjundi: > > > > > BJ?rn Lindqvist wrote: > > > I want to use Python to connect to a SSH account over a HTTP proxy to > > > automate some operations. I thought paramiko would be able to do that, > > > but it can not (it seems). > > > > Is there some other Python module that can do what I want? > > > > -- > > > mvh Bj?rn > > > Did you take a look at twisted library? > > twistedmatrix.com > >http://twistedmatrix.com/projects/core/documentation/howto/clients.html > > > I haven't tried to connect over port 80, but its worth a try. > > > -NIf you need it for automation you might want to usepexpect:http://pexpect.sourceforge.net/ > > It listens to the tty-stream and simulates a user typing in commands. It is > very useful, e.g. if you want to start processes on many machines over ssh. > If there are gateways/firewalls between - no problem just use a > second "sendline('ssh user at nextmachine')" > > The only problem is the regular expression: If e.g. you use a custom $PS1 > variable for your prompt you have to account for that. > > Regards, > wr From larry.bates at websafe.com Wed Jan 31 10:26:18 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 31 Jan 2007 09:26:18 -0600 Subject: Help needed on config files In-Reply-To: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> References: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> Message-ID: <45C0B51A.20801@websafe.com> jvdb wrote: > Hi there, > > I am quite new on python programming and need some help on solving my > problem.. > > I have to make a (python) program which deletes files from > directories. I don't think deleting, etc. is the problem. The problem > is that the directories where i have to delete them are 'dynamic'/ > subject to change. So what i thought is to make a config file > containing an identifier (useful for myself) and there the directory. > something like: > [PROJECTx] > > [PROJECTy] > > > I have already seen that there are sorts of modules where you can read > a config file, but only when you know the key.. Can someone help me > out on this? The configfile can be altered in time (as there are more > projects coming where i have to delete files on a scheduled basis). > > This is a good learning project for me, but i really don't see how to > solve this. > Others have answered your specific question, I thought I'd add my 2 cents. As the config file grows you will need to have other sections that are not PROJECT# sections. I use the pattern: from ConfigParser import ConfigParser cfg = ConfigParser() cfg.read("proj.cfg") projectSections=[section for section in cfg.sections() if x.startswith('PROJECT')] # # Note: sections are case sensitive # for project in projectSections: # # Do your work # -Larry This seems to work quite well. I hope information helps. -Larry From facundo at taniquetil.com.ar Wed Jan 24 07:53:16 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 24 Jan 2007 12:53:16 +0000 (UTC) Subject: newbie question: ftp.storbinary() References: Message-ID: Scott Ballard wrote: > Sorry for the lame question, I'm still trying to pick up Python and new to > the list here. Welcome! > I'm assuming that I should use storbinary( command, file[, blocksize]) to > transfer the files. the documentation says "command should be an appropriate > "STOR" command: "STOR filename"." For example: >>> fp = open("/tmp/file_to_transfer.txt") # open the file >>> self.ftp.storbinary("STOR file_to_transfer.txt", fp) # note that the name has not the path >>> fp.close() # close the file, :) Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From duncan.booth at invalid.invalid Wed Jan 3 05:56:14 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jan 2007 10:56:14 GMT Subject: import order or cross import References: Message-ID: Roland Hedberg wrote: > Now, running ONE.py causes no problem it will print "Black", but running > TWO.py I get: > AttributeError: 'module' object has no attribute 'BaseColor' > > So, how can this be solved if it can be ? > When you execute an import statement, it checks whether the module already exists. If it does exist then it immediately returns the module object. If the module does not yet exist then the module is loaded and the code it contains is executed. Remember that all statements in Python are executed at the time they are encountered: there are no declarations (apart from 'global') so no looking ahead to see what classes or functions are coming up. One other complication in your particular instance: when you run a ONE.py as a script the script is loaded in a module called '__main__', so 'import ONE' will actually load a separate module which is NOT the same as the __main__ module. Likewise when you run TWO.py as a script you have three modules __main__ (loaded from TWO.py), ONE, and TWO. So running TWO.py, you get: import ONE --- loads the module ONE and starts executing it import TWO --- loads the module TWO and starts executing it import ONE --- the module ONE already exists (even though so far it hasn't got beyond the import TWO line) so the empty module is returned. class Black(ONE.BaseColor): --- ONE doesn't have a BaseColor attribute yet so you get an error. The fix in this sort of case is usually to extract the base class out to a third module. If you put BaseColor in base.py then you can safely import that anywhere you want it. An alternative in this case would be to edit ONE.py and move the line 'import TWO' down below the definition of BaseColor: nothing before that actually requires TWO to have been imported yet. However, you really should try to separate scripts from modules otherwise the double use as both __main__ and a named module is going to come back and bite you. From nmm1 at cus.cam.ac.uk Mon Jan 8 08:39:55 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 8 Jan 2007 13:39:55 GMT Subject: Bizarre floating-point output Message-ID: x = (1.234567890125, 1.2345678901255) print x print x[0], x[1] >>> (1.2345678901249999, 1.2345678901254999) >>> 1.23456789012 1.23456789013 Is there a rational reason, or is that simply an artifact of the way that the code has evolved? It is clearly not a bug :-) Regards, Nick Maclaren. From zhangry at feng.co.jp Tue Jan 16 03:12:04 2007 From: zhangry at feng.co.jp (HYRY) Date: 16 Jan 2007 00:12:04 -0800 Subject: why scipy cause my program slow? Message-ID: <1168935124.912419.147250@a75g2000cwd.googlegroups.com> Why the exec time of test(readdata()) and test(randomdata()) of following program is different? my test file 150Hz10dB.wav has 2586024 samples, so I set randomdata function to return a list with 2586024 samples. the exec result is: 2586024 10.8603842736 2586024 2.16525233979 test(randomdata()) is 5x faster than test(readdata()) if I remove "from scipy import *" then I get the following result: 2586024 2.21851601473 2586024 2.13885042216 So, what the problem with scipy? Python 2.4.2, scipy ver. 0.5.1 import wave from scipy import * from time import * import random from array import array def readdata(): f = wave.open("150Hz10dB.wav", "rb") t = f.getparams() SampleRate = t[2] data = array("h", f.readframes(t[3])) f.close() left = data[0::2] mean = sum(left)/float(len(left)) left = [abs(x-mean) for x in left] return left def randomdata(): return [random.random()*32768.0 for i in xrange(2586024)] def test(data): print len(data) print type(data) envelop = [] e = 0.0 ga, gr = 0.977579425259, 0.999773268338 ga1, gr1 = 1.0 - ga, 1.0 - gr start = clock() for x in data: if e < x: e *= ga e += ga1*x else: e *= gr e += gr1*x envelop.append(e) print clock() - start return envelop test(readdata()) test(randomdata()) From http Wed Jan 24 19:11:07 2007 From: http (Paul Rubin) Date: 24 Jan 2007 16:11:07 -0800 Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169683654.672020.136820@q2g2000cwa.googlegroups.com> Message-ID: <7xveiwklt0.fsf@ruckus.brouhaha.com> "Klaas" writes: > POSIX issues aside, Python's threading model should be less susceptible > to memory-barrier problems that are possible in other languages (this > is due to the GIL). But the GIL is not part of Python's threading model; it's just a particular implementation artifact. Programs that rely on it are asking for trouble. > Double-checked locking, frinstance, is safe in python even though it > isn't in java. What's that? > Are you ever relying solely on the GIL to access shared data? I think a lot of programs do that, which is probably unwise in the long run. From gagsl-py at yahoo.com.ar Sat Jan 27 20:13:15 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Jan 2007 22:13:15 -0300 Subject: stop script w/o exiting interpreter References: Message-ID: "Alan Isaac" escribi? en el mensaje news:wWQuh.1259$SE6.1215 at trnddc03... > Please note that this post has subject > "stop script w/o exiting interpreter". > Note that I can just put the undefined name ``stop`` on any line > I want, and the script will stop execucting at that line and will > return to the interactive interpreter, as I wish. It is just that it > returns with an error message, and I'd like to avoid that. If this is just for playing inside the interpreter, just ignore the exception. Or comment out all lines from 25 to end of script, some editors (including IDLE) have support for that. Or use a giant """ string """ if you can. If you invoke your script with `python -i your_script.py` Python will show the interpreter prompt when your script finishes (either normally or raising an exception). -- Gabriel Genellina From smusnmrNOSPAM at yahoo.com Thu Jan 25 09:02:11 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Thu, 25 Jan 2007 15:02:11 +0100 Subject: how to unistall a Python package? Message-ID: Hi all, installing a package with 'setup.py' is easy. But how do I uninstall the package, once I want to get rid of it again? Thanks, siggi From misterwang at gmail.com Mon Jan 29 16:46:52 2007 From: misterwang at gmail.com (Peter Wang) Date: 29 Jan 2007 13:46:52 -0800 Subject: Compiling extension with Visual C++ Toolkit Compiler - MSVCR80.dll In-Reply-To: <1170103633.189538.216620@v45g2000cwv.googlegroups.com> References: <1170103633.189538.216620@v45g2000cwv.googlegroups.com> Message-ID: <1170107212.889990.45450@a75g2000cwd.googlegroups.com> On Jan 29, 2:47 pm, alexandre_irrt... at yahoo.com wrote: > The library seems to build correctly (producing Polygon.py and > cPolygon.pyd), but when I import it I get the following message from > python.exe: "This application has failed to start because MSVCR80.dll > was not found". I thought that this might be due to Python trying to > link against the .dll from Microsoft Visual C++ Express 2005, also > installed on my PC, instead of MSVCR71.dll. So I've removed MS Visual C > ++ Express 2005, and any trace of it from my environment variables, > but that doesn't seem to change anything. Alex, I'm not familiar with the particular problem you're seeing, but did you try building the polygon library using the gcc that's included with the Enthought distribution? python setup.py build_clib build_ext --inplace --compiler=mingw32 -Peter From noone at nowhere.com Sat Jan 27 23:43:10 2007 From: noone at nowhere.com (avidfan) Date: Sat, 27 Jan 2007 22:43:10 -0600 Subject: log parser design question Message-ID: I need to parse a log file using python and I need some advice/wisdom on the best way to go about it: The log file entries will consist of something like this: ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled locked working.lock status running status complete ID=9009 IID=87234785 execute wait - 01.21.2007 status wait waiting to lock status wait waiting on ID=8688 and so on... I need to be able to group these entries together, index them by ID and IID, and search the context of each entry and if a certain status if found (such as wait), then be able to return the ID or IID (depending...) of that entry. So I was considering parsing them to this effect: in a dictionary, where the key is a tuple, and the value is a list: {('ID=8688', 'IID=98889998'): ['ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled', 'locked working.lock', 'status running', 'status complete']} I am keeping the full text of each entry in the list so that I can recreate them for display if need be. I am fairly new to python, so could anyone offer any advice here before I get too far and discover a fatal flaw that you might see coming a mile away? would I, with this design, be able to, for example, search each list for "waiting on ID=8688", and when found, be able to associate that value with one of the elements of it's key "ID=9009" ? or is this approached flawed? I'm assuming there is a better way, but I need some advice... I appreciate any thoughts. Thanks. From vinay_sajip at yahoo.co.uk Fri Jan 19 06:02:44 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 19 Jan 2007 03:02:44 -0800 Subject: selective logger disable/enable References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> Message-ID: <1169204564.348768.186900@38g2000cwa.googlegroups.com> Gary Jefferson wrote: > Suppose I have 3 modules that belong to a project, 'A', 'A.a' and 'B', > and each module has its own logger, created with: > > module1logger = logging.getLogger('project.A') > > and > > module2logger = logging.getLogger('project.A.a') > > and > > module3logger = logging.getLogger('project.B') > > > And I want to selectively enable/disable these, per module (for > example, I only want logging from A and A.a, or just from B, etc). It > seems like logging.Filter is supposed to let me do this, but I can't > see how to apply it globally. Is there really no other way that to add > a addFilter(filter) call to each of these loggers individually? > The documentation for Logger - see http://docs.python.org/lib/node406.html - shows that there are addFilter() and removeFilter() methods on the Logger class which you can use to add or remove filters from individual Logger instances. From the above page (entitled "14.5.1 Logger Objects"): addFilter(filt) Adds the specified filter filt to this logger. removeFilter(filt) Removes the specified filter filt from this logger. The parent section of Section 14.5.1, which is Section 14.5, was the first search result when I just searched Google for "python logging". Best regards, Vinay Sajip From arkanes at gmail.com Mon Jan 8 10:47:04 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 8 Jan 2007 09:47:04 -0600 Subject: PDF rendering toolkit? In-Reply-To: <32822fe60701051252s6353f10drc101109adc376fdb@mail.gmail.com> References: <32822fe60701051252s6353f10drc101109adc376fdb@mail.gmail.com> Message-ID: <4866bea60701080747s380f909ana6559da75d8d894f@mail.gmail.com> On 1/5/07, Jorge Vargas wrote: > Hi > > I'm looking for a tool to take an actual .pdf file and display it in a > window (I'm using wxwidgets at the moment) > > I have found several project but none seem to do what I need. > > http://sourceforge.net/projects/pdfplayground seems like a nice > toolkit to edit pdf files with python code, but nothing about > rendering. > > I have find out http://poppler.freedesktop.org/ but there seems to be > no python bindings for it. > > there is also an example at http://www.daniweb.com/code/snippet618.html > using wx.lib.pdfwin but that is windows only, I need at least Linux > support better if it's platform independant as python *should* be > > and the reportlabs BSD packages can't do this. > http://www.reportlab.org/devfaq.html#2.1.5 > > anyone knows of a toolkit to do this? bonus points if's it is already > integrated into wxpython > -- Rendering PDF is quite hard, much harder than writing it. There are relatively few PDF rendering solutions for any platform, and it's non-trivial to merge one with a specific UI solution. So I'm not aware of any cross-platform solution. Most PDF usage either embeds the Adobe ActiveX control (on windows) or just shunts it off the user to find a working PDF viewer. From jeffrey at fro.man Tue Jan 2 22:59:26 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 02 Jan 2007 19:59:26 -0800 Subject: Iterate through list two items at a time References: Message-ID: <12pmahqc7kclbfc@corp.supernews.com> Dave Dean wrote: > I'm looking for a way to iterate through a list, two (or more) items at a > time. Here's a solution, from the iterools documentation. It may not be the /most/ beautiful, but it is short, and scales well for larger groupings: >>> from itertools import izip >>> def groupn(iterable, n): ... return izip(* [iter(iterable)] * n) ... >>> list(groupn(myList, 2)) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] >>> list(groupn(myList, 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)] >>> list(groupn(myList, 4)) [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)] >>> for a,b in groupn(myList, 2): ... print a, b ... 0 1 2 3 4 5 6 7 8 9 10 11 >>> Jeffrey From martin at v.loewis.de Thu Jan 18 13:25:34 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 18 Jan 2007 19:25:34 +0100 Subject: Memory Management in Embedded Python In-Reply-To: <1169143866.351663.316890@l53g2000cwa.googlegroups.com> References: <1169143866.351663.316890@l53g2000cwa.googlegroups.com> Message-ID: <45AFBB9E.9090502@v.loewis.de> Huayang Xia schrieb: > I have a piece of code like this: > > void funct(PyObject* pyobj) > { > char str[128]; > strncpy(str, "just a test string", sizeof(str)); > PyObject* pydata = PyObject_CallMethod(pyobj, "method_x", > "s", str); > Py_DECREF(pydata); > } > > After the function is exited, the str is not there anymore. Will this > affect python operation. How does python use the str? It's copied or it > just uses the pointer? The interpreter creates a string object, and passes that to method_x. Creating a string object does indeed create a copy. The string object will be refcounted, so it exists as long as there is a reference to it. Likely (unless the method_x implementation somehow stores the string), it gets deallocated before PyObject_Call returns. HTH, Martin From tjreedy at udel.edu Thu Jan 18 15:45:55 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 18 Jan 2007 15:45:55 -0500 Subject: [Python-Dev] Deletion order when leaving a scope? References: <45AEC612.1030001@hastings.org> <45af14dc$0$7727$4c368faf@roadrunner.com> Message-ID: "Paul McGuire" wrote in message news:45af14dc$0$7727$4c368faf at roadrunner.com... | "Calvin Spealman" wrote in message | news:mailman.2860.1169086798.32031.python-list at python.org... | > Absolutely an irrelevent side effect, especially when you take into | > consideration the 4 and counting alternative implementations of the | > language. | > | > None the less, I can explain why it is as it is, keeping in mind its | > not like that on purpose, its just how it is. Locals are optimized | > into an array for fast lookup. Every name assigned to in a function is | > known as a local in that function and this internal array holds its | > reference. It is simply a product of the array indexes and deletion | > order being the same, 0 to N. | > | | Oh good! Now I can write code that relies on this behavior! According to a followup on python-dev, you can't. The above is the normal behavior (for CPython) but it can be modified by imports and cross-references. Or did you forget a smiley? tjr From bdesth.quelquechose at free.quelquepart.fr Mon Jan 29 16:54:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Jan 2007 22:54:53 +0100 Subject: strip question In-Reply-To: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> References: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> Message-ID: <45be664c$0$16363$426a74cc@news.free.fr> eight02645999 at yahoo.com a ?crit : > hi > can someone explain strip() for these : > [code] > >>>>x='www.example.com' >>>>x.strip('cmowz.') > > 'example' > [/code] > > when i did this: > [code] > >>>>x = 'abcd,words.words' >>>>x.strip(',.') > > 'abcd,words.words' > [/code] > > it does not strip off "," and "." .Why is this so? Probably because the Fine Manual(tm) says that str.strip() removes heading and trailing chars ? """ bruno at bibi ~ $ python Python 2.4.1 (#1, Jul 23 2005, 00:37:37) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help(''.strip) Help on built-in function strip: strip(...) S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ You may want to try str.replace() instead: """ >>> help(''.replace) Help on built-in function replace: replace(...) S.replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. >>> 'abcd,words.words'.replace(',', '').replace('.', '') 'abcdwordswords' """ > thanks HTH From mh at pixar.com Tue Jan 30 11:45:55 2007 From: mh at pixar.com (Mark Harrison) Date: Tue, 30 Jan 2007 16:45:55 GMT Subject: test, please ignore qrm Message-ID: <7DKvh.23723$yC5.18799@newssvr27.news.prodigy.net> test, please ignore From nogradi at gmail.com Tue Jan 30 15:29:48 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 30 Jan 2007 21:29:48 +0100 Subject: subway code Message-ID: <5f56302b0701301229q191fd378y3069a49536f8aa1f@mail.gmail.com> (Somehow this message didn't go through for the first time.) Does anyone know what happened to the subway project? The sites gosubway.org and subway.python-hosting.com have been down for a long time now. Actually, I would like to have the code just to look at it and maybe learn something, but it seems it completely disappeared from the net. Does anyone have access to it and the rights to make it publically available? From nmm1 at cus.cam.ac.uk Wed Jan 24 13:21:38 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 24 Jan 2007 18:21:38 GMT Subject: The reliability of python threads References: Message-ID: In article , "Chris Mellon" writes: |> > |> |> > |> Does anyone have any conclusive evidence that python threads/locks are |> > |> safe or unsafe? |> > |> > Unsafe. They are built on top of unsafe primitives (POSIX, Microsoft |> > etc.) Python will shield you from some problems, but not all. |> > |> > There is precious little that you can do, because the root cause is |> > that the standards and specifications are hopelessly flawed. |> |> This is sufficiently inaccurate that I would call it FUD. Using |> threads from Python, as from any other language, requires knowledge of |> the tradeoffs and limitations of threading, but claiming that their |> usage is *inherently* unsafe isn't true. It is almost certain that |> your code and locking are flawed, not that the threads underneath you |> are buggy. I suggest that you find out rather more about the ill-definition of POSIX threading memory model, to name one of the better documented aspects. A Web search should provide you with more information on the ghastly mess than any sane person wants to know. And that is only one of many aspects :-( Regards, Nick Maclaren. From wise at hyperformix.com Thu Jan 11 17:14:53 2007 From: wise at hyperformix.com (Tim) Date: 11 Jan 2007 14:14:53 -0800 Subject: py2exe: zipfile=None raised ImportError In-Reply-To: References: <1168543966.212663.141840@i56g2000hsf.googlegroups.com> Message-ID: <1168553693.344329.182090@p59g2000hsd.googlegroups.com> Thomas Heller wote: [..] > Tim schrieb: [...] > > > File "...boot_common.py" ... no module name linecache > > > File " ... no module named zipextimporter > > > File "my.py" ... no module name optparse [...] > Another tip: You can examine what is in the zipfile, or the exe (if using > zipfile=None) when you rename the file to a *.zip file, and open it with > winzip or another archiver. I clean before every compile. When I look at the exe as a zip I see all the modules in the error message: optparse.pyc, zipextimporter.pyc, and linecache.pyc. I don't see boot_common.py. Why is it being called? -- Tim From Barry.Carroll at psc.com Wed Jan 31 12:07:15 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 31 Jan 2007 09:07:15 -0800 Subject: What is the dummy statement that do nothing in Python? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595ACA@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: Dongsheng Ruan [mailto:ruan at jcmills.com] > Sent: Wednesday, January 31, 2007 8:50 AM > To: python-list at python.org > Subject: What is the dummy statement that do nothing in Python? > > I remember that in python there is some kind of dummy statement that just > holds space and does nothing. > > I want it to hold the place after a something like if a>b: do nothing > > I can't just leave the space blank after if statement because there will > be > error message. > > Does anybody know what to insert there? > > Thanks! > > Greetings: Try 'pass': if a>b: pass else: dosomething() Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From rshepard at appl-ecosys.com Thu Jan 25 17:34:31 2007 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Thu, 25 Jan 2007 14:34:31 -0800 (PST) Subject: Right-Justifying Numeric Output In-Reply-To: References: Message-ID: On Thu, 25 Jan 2007, hg wrote: > assuming max size = 10 > > #with spaces >>> '% 10d' % 11 > ' 11' > #with zeros >>> '%010d' % 11 > '0000000011' Thank you very much! I didn't see this in any of my Python books or on the Web. Rich -- Richard B. Shepard, Ph.D. | The Environmental Permitting Applied Ecosystem Services, Inc. | Accelerator(TM) Voice: 503-667-4517 Fax: 503-667-8863 From wdraxinger at darkstargames.de Mon Jan 22 10:15:23 2007 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Mon, 22 Jan 2007 16:15:23 +0100 Subject: Program eating memory, but only on one machine? References: Message-ID: Per B. Sederberg wrote: > Python 2.4.4c1 (#2, Oct 11 2006, 20:00:03) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on > [linux2 Type "help", "copyright", "credits" or "license" for > more information. Doesn't eat up. > Python 2.4.3 (#1, Apr 7 2006, 10:54:33) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "help", "copyright", "credits" or "license" for more > information. Doesn't eat up. > Python 2.4.4 (#1, Jan 21 2007, 12:09:48) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. Eats up memory > So, does anyone have any suggestions for how I can debug this > problem? Have a look at the version numbers of the GCC used. Probably something in your C code fails if it interacts with GCC 3.x.x. It's hardly Python eating memory, this is probably your C module. GC won't help here, since then you must add this into your C module. > If my program ate up memory on all machines, then I would know > where to start and would blame some horrible programming on my > end. This just seems like a less straightforward problem. GCC 3.x.x brings other runtime libs, than GCC 4.x.x, I would check into that direction. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 From sluggoster at gmail.com Tue Jan 9 14:57:04 2007 From: sluggoster at gmail.com (Mike Orr) Date: 9 Jan 2007 11:57:04 -0800 Subject: Summarizing data by week Message-ID: <1168372624.543712.149070@77g2000hsv.googlegroups.com> What's the best way to summarize data by week? I have a set of timestamped records, and I want a report with one row for each week in the time period, including zero rows if there are weeks with no activity. I was planning to use ISO weeks because datetime has a convenient .isocalendar() method, but I want each output row to have a label like this: 2006 week 5 (Feb) However, to get the month (of the Thursday of that week) I have to convert it back to an actual date,and I don't see a method to do that in datetime or dateutil or mx.DateTime. I was planning to use a dateutil.rrule to generate the weeks from the minimum to maximum date, including any weeks that have no activity (so they won't be in the dictionary). But rrule sequences are based on an actual start date, not an ISO week, so that won't work. Unless perhaps I take the minimum date and calculate the Thursday of that week, and start from there. Then all my conversions would be to iso_week rather than from iso_week. Is there a better way to do this? --Mike From gonzlobo at gmail.com Fri Jan 19 21:32:10 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Fri, 19 Jan 2007 19:32:10 -0700 Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: References: Message-ID: I should write a python script to read this. :) >.snoitnevnoc >hsilgnE tpada )ylbissop revenehw( dluohs ew os dna ,naitraM ton ,puorgswen >egaugnal hsilgnE na no er'ew ,segaugnal hcus era ereht fi neve tuB From steve at REMOVE.THIS.cybersource.com.au Mon Jan 8 17:24:34 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 09 Jan 2007 09:24:34 +1100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 08 Jan 2007 13:11:14 +0200, Hendrik van Rooyen wrote: > When you hear a programmer use the word "probability" - > then its time to fire him, as in programming even the lowest > probability is a certainty when you are doing millions of > things a second. That is total and utter nonsense and displays the most appalling misunderstanding of probability, not to mention a shocking lack of common sense. -- Steven. From tkpmep at hotmail.com Tue Jan 16 08:34:14 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 16 Jan 2007 05:34:14 -0800 Subject: Globbing files by their creation date Message-ID: <1168954453.954486.188680@m58g2000cwm.googlegroups.com> I'd like to create a list of all files in a directory that were created after a certain date. How does one do this? I've used glob.glob to create a list of all files whose name matches a substring, but I don't see how I can use it to identify files by their creation date. Thanks in advance for the assistance. Thomas Philips From erick.lavoie at gmail.com Tue Jan 23 10:18:57 2007 From: erick.lavoie at gmail.com (=?ISO-8859-1?Q?Lavoie_=C9rick?=) Date: Tue, 23 Jan 2007 10:18:57 -0500 Subject: How to get self reference from within a module? Message-ID: <3ca9bbe50701230718s55029fc8n507eb357b298428f@mail.gmail.com> I finally found what I was searching for here: http://www.thescripts.com/forum/thread25264.html I wanted the reference to the current module and we can obtain it this way: sys.modules[__name__] so its property can be used. Thanks, Erick -------------- next part -------------- An HTML attachment was scrubbed... URL: From huayang.xia at gmail.com Wed Jan 10 17:05:56 2007 From: huayang.xia at gmail.com (Huayang Xia) Date: 10 Jan 2007 14:05:56 -0800 Subject: where to find the spec of format in PyObject_CallMethod Message-ID: <1168466755.996033.130120@i39g2000hsf.googlegroups.com> I am trying to use PyObject_CallMethod. It needs a format string to specify what are the followed arguments. Is it possible to use a PyObject* as an argument? Where can I find the spec for the format? Thanks in advance. From michael at mustun.ch Sun Jan 7 18:24:16 2007 From: michael at mustun.ch (Michael M.) Date: Mon, 08 Jan 2007 00:24:16 +0100 Subject: how to find the longst element list of lists In-Reply-To: References: <45a169f0$0$309$426a34cc@news.free.fr> <%keoh.230$L06.209@nntpserver.swip.net> Message-ID: Sorry, wrong place. From nmm1 at cus.cam.ac.uk Fri Jan 12 10:55:39 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 12 Jan 2007 15:55:39 GMT Subject: Rational Numbers References: Message-ID: In article , Carsten Haese writes: |> |> Ah, so now you're putting words in the BDFL's mouth. ;) |> |> The pronouncement does say "The needs outlined in the rationale section |> have been addressed to some extent by the acceptance of PEP 327 for |> decimal arithmetic," but it doesn't say to which extent, and it |> certainly doesn't claim that decimal arithmetic is a replacement for |> rational arithmetic. Eh? If the needs are addressed to some extent, then to some extent it is a replacement. |> The sentence you're referring to is "There are excellent Rational |> implementations [...]. Probably worth PEPping, not worth doing without |> Decimal." I agree that this sentence is poorly worded, but I think it |> means "Even if we had Rational, we'd still need Decimal" in the sense |> that Rational is not an adequate replacement for Decimal. Which would be justifiable, but is not what it said. What it SAID is what I said it said .... |> The bottom line is that there are use cases for both Rational and |> Decimal, and neither one can replace the other, So far, so good. With reservations, I agree. |> but there are more use |> cases for Decimal than for Rational. That is dubious, but let's not start that one again. Regards, Nick Maclaren. From pierre.imbaud at laposte.net Tue Jan 30 09:34:11 2007 From: pierre.imbaud at laposte.net (Imbaud Pierre) Date: Tue, 30 Jan 2007 15:34:11 +0100 Subject: data design Message-ID: <45bf5763$0$22792$426a34cc@news.free.fr> The applications I write are made of, lets say, algorithms and data. I mean constant data, dicts, tables, etc: to keep algorithms simple, describe what is peculiar, data dependent, as data rather than "case statements". These could be called configuration data. The lazy way to do this: have modules that initialize bunches of objects, attributes holding the data: the object is somehow the row of the "table", attribute names being the column. This is the way I proceeded up to now. Data input this way are almost "configuration data", with 2 big drawbacks: - Only a python programmer can fix the file: this cant be called a configuration file. - Even for the author, these data aint easy to maintain. I feel pretty much ready to change this: - make these data true text data, easier to read and fix. - write the module that will make python objects out of these data: the extra cost should yield ease of use. 2 questions arise: - which kind of text data? - csv: ok for simple attributes, not easy for lists or complex data. - xml: the form wont be easier to read than python code, but an xml editor could be used, and a formal description of what is expected can be used. - how can I make the data-to-object transformation both easy, and able to spot errors in text data? Last, but not least: is there a python lib implementing at least part of this dream? From ldo at geek-central.gen.new_zealand Wed Jan 10 01:46:46 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 10 Jan 2007 19:46:46 +1300 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: In message , Piet van Oostrum wrote: > Lawrence D'Oliveiro (LD) wrote: > In message , Piet van Oostrum wrote: > >> The scenario is as follows: Suppose the script starts with the line: >> #!/usr/bin/python >> >> (using #!/usr/bin/env python would be disastrous because the user could >> supply his own `python interpreter' in his PATH.) >> >> Now a malicious user can make a link to this file in his own directory, >> e.g. to /Users/eve/myscript1. Because permissions are part of the file >> (inode), not of the file name, this one is also suid. >> >> Now she execs /Users/eve/myscript1. The kernel, when honoring suid >> scripts, would startup python with effective uid root with the command >> line: /usr/bin/env /Users/eve/myscript1 >> >>LD> No it wouldn't. This security hole was fixed years ago. > > How? Systems which allow set-uid scripts also usually support referring to open file descriptors n via a pathname like /dev/fd/n. This might be done by mounting a special pseudo-filesystem (fdfs) on /dev/fd. (This was how I remember it being done on DEC UNIX.) So when a the kernel detects that an executable file is actually a script, it opens the script file on some file descriptor n, and passes the name /dev/fd/n to the script interpreter, instead of the original script pathname. That way, there is no opportunity for deceiving the process into executing the wrong script with set-uid privileges. From gagsl-py at yahoo.com.ar Mon Jan 8 12:22:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 14:22:00 -0300 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <1168262749.852897.13010@q40g2000cwq.googlegroups.com> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <45A1F1D9.8070206@v.loewis.de> <1168262749.852897.13010@q40g2000cwq.googlegroups.com> Message-ID: <7.0.1.0.0.20070108140718.05c30858@yahoo.com.ar> At Monday 8/1/2007 10:25, vizcayno wrote: >However, what happens when the error is due to data error. Or when the >program is reading many files to save data into a database and one or >two files have problems with data format. I would like to keep the >program running (using exception in a controlled way) for the remaining >good files and prepare a log about the failed files. How to keep the >same function for a program that runs in batch, or on-line or in the >web? Giving the simple example I put, I would like to find more >guidelines. Deal with the exception at a higher level. In your example, you have some files to be processed: for fname in filenames: do_something_with(fname) ==> for fname in filenames: try: do_something_with(fname) except StandardError, E: log_error(E) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at REMOVE.THIS.cybersource.com.au Sat Jan 13 20:24:14 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 14 Jan 2007 12:24:14 +1100 Subject: Boilerplate in rich comparison methods References: <1168674664.792869.213260@m58g2000cwm.googlegroups.com> <45a90301$0$7677$4c368faf@roadrunner.com> <5Jcqh.1188$G23.509@newsreading01.news.tds.net> Message-ID: On Sat, 13 Jan 2007 22:05:53 +0000, Neil Cerutti wrote: >> Anyone want to argue that this is a worthwhile optimization? :) > > Perhaps. But first test it with "==". Oh the ignominy! That's what happens when I run code at 6am :( >>> x = CompareWithIdentity(1); y = CompareWithIdentity(1) >>> timeit.Timer("x == y", "from __main__ import x,y").repeat() [2.2971229553222656, 2.2821698188781738, 2.2767620086669922] >>> timeit.Timer("x == x", "from __main__ import x,y").repeat() [1.6935880184173584, 1.6783449649810791, 1.6613109111785889] >>> x = Compare(1); y = Compare(1) >>> timeit.Timer("x == y", "from __main__ import x,y").repeat() [2.1717329025268555, 2.1361908912658691, 2.1338419914245605] So for this simple case, testing for identity is a factor of 1.3 faster when the objects are identical, and a factor of 1.1 slower if they aren't. That suggests that if about 33% of your comparisons match by identity, you'll break-even; any less than that, and the optimization is actually a pessimation. -- Steven. From nogradi at gmail.com Wed Jan 24 17:55:51 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 24 Jan 2007 23:55:51 +0100 Subject: file -> open in stdlib patch Message-ID: <5f56302b0701241455s69326dd0k73797deeb6153cdd@mail.gmail.com> Hi list, AFAIK using file( ) to open a file is deprecated in favor of open( ) and while grepping through the stdlib I noticed a couple of occurences of file( ) in the latest revision. I made a patch for getting rid of them; it passes all the tests. Although the change is almost trivial, since this is my first patch maybe it's better if someone knowledgeable takes a look at it before submitting it to SF. Daniel Index: Lib/site.py =================================================================== --- Lib/site.py (revision 53548) +++ Lib/site.py (working copy) @@ -274,7 +274,7 @@ for filename in self.__files: filename = os.path.join(dir, filename) try: - fp = file(filename, "rU") + fp = open(filename, "rU") data = fp.read() fp.close() break Index: Lib/webbrowser.py =================================================================== --- Lib/webbrowser.py (revision 53548) +++ Lib/webbrowser.py (working copy) @@ -216,7 +216,7 @@ cmdline = [self.name] + raise_opt + args if remote or self.background: - inout = file(os.devnull, "r+") + inout = open(os.devnull, "r+") else: # for TTY browsers, we need stdin/out inout = None @@ -340,7 +340,7 @@ else: action = "openURL" - devnull = file(os.devnull, "r+") + devnull = open(os.devnull, "r+") # if possible, put browser in separate process group, so # keyboard interrupts don't affect browser as well as Python setsid = getattr(os, 'setsid', None) Index: Lib/pstats.py =================================================================== --- Lib/pstats.py (revision 53548) +++ Lib/pstats.py (working copy) @@ -173,7 +173,7 @@ def dump_stats(self, filename): """Write the profile data to a file we know how to load back.""" - f = file(filename, 'wb') + f = open(filename, 'wb') try: marshal.dump(self.stats, f) finally: From robert.kern at gmail.com Wed Jan 3 15:42:40 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 Jan 2007 14:42:40 -0600 Subject: Unsubscribing from the list In-Reply-To: <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> Message-ID: Dotan Cohen wrote: > On 03/01/07, Fredrik Lundh wrote: >> Robert provided *detailed* instructions, which you ignored. I quoted >> the same instructions in my reply, which you also ignored. the sentence >> after the one where you stopped reading also tells you what to do. one >> might suspect that you don't really want to unsubscribe from this list... > > I didn't ignore his instructions. I went to the page, and found what I > was looking for. I told him thank you, and explained why I didn't find > it the first time. He misunderstood you (as I nearly did, too). The way you phrased "decided that there was no futher interest on the page for me" is somewhat ambiguous: it can seem like it refers to the second time, not the first. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From exarkun at divmod.com Tue Jan 23 20:30:05 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 23 Jan 2007 20:30:05 -0500 Subject: smtplib starttls gmail example In-Reply-To: Message-ID: <20070124013005.17245.470171872.divmod.quotient.9408@ohm> On Tue, 23 Jan 2007 23:48:59 GMT, py wrote: >Hi, Jean Paul. > >I read your code with interest. I wonder, does twisted also raise the socket error or does it know >about this apparently well-known and often ignored incompatibility between the standard and >the implementations? Twisted delivers disconnection notification by passing an exception to a method on a protocol instance. So, whether it dealt with this SSL behavior or not, you wouldn't see an exception being raised from the program I posted. However, if one implements connectionLost (the method which Twisted calls on disconnect), if SSL shutdown isn't done cleanly, you will see an SSL exception object instead of an exception which indicates clean shutdown. However, since the example I posted didn't actually directly interact with any protocol object at all, all of this is hidden. The program will appear to succeed completely with no error, because the success condition it defines is for the message to have been accepted by the remote host, not for the socket to have been closed cleanly. > >Something else has occurred to me. After starting tls, all the xmitted commands and data are encrypted before they leave the client machine. >so obviously they have to be decrypted by the server's socket lib before the smtp daemon can do what it's supposed to do. >but i wonder if the encryption of the trailing \n.\n has something to do with the socket error, given that >the error msg says something about premature EOF. As to this, I'm not sure. A cursory glance at smtplib.py suggests it is at least trying to handling the \r\n.\r\n sequence which terminates a DATA command correctly. I'm not sure why you needed to add your own . when you used it. I think the SSL error is most likely unrelated, though. I have seen it from gmail's servers before as well. Jean-Paul From gherron at islandtraining.com Tue Jan 16 21:19:34 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 16 Jan 2007 18:19:34 -0800 Subject: Newbie: Capture traceback message to string? In-Reply-To: <8E19FBD5-47DC-4FE3-9E5C-B143664CC846@datafly.net> References: <8E19FBD5-47DC-4FE3-9E5C-B143664CC846@datafly.net> Message-ID: <45AD87B6.1050506@islandtraining.com> Sean Schertell wrote: > Hello! > > I'm new to Python and this is my first post to the list. > > I'm trying to simply capture exception text to a few strings which > can be passed to a PSP page to display a pretty error message. The > problem is that I just can't seem to figure out how to get the basic > components of the traceback message into strings. Here's what I want > to do: > The traceback module provides a wealth of ways to get at the exception information, formated and usable in various ways. See: http://docs.python.org/lib/module-traceback.html Gary Herron > --------------------- > try: > bad_math = 1/0 > except: > info = sys.exc_info() > main_error_str = # ??? > full_traceback_str = # ??? > tmpl = psp.PSP(req, filename='error.html') > tmpl.run({'main_error_str': main_error_str, > 'full_traceback_str':full_traceback_str}) > > return apache.OK > --------------------- > > ...So then my PSP page receives the errors as variables containing > strings. > > I've been googling and experimenting for more hours than I care to > admit. A little help please? > > Thanks! > > Sean > > > From rdm at rcblue.com Thu Jan 11 11:24:48 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 11 Jan 2007 08:24:48 -0800 Subject: What happened to SPE? In-Reply-To: References: Message-ID: <7.0.1.0.2.20070111082234.07b35570@rcblue.com> At 07:43 AM 1/11/2007, Paulo Pinto wrote: >does anyone know what happened to SPE? > >It seems that the address http://pythonide.stani.be >is no longer valid. :( I'd suggest subscribing to the Python-spe-users list, , or reading the archive there. Dick Moores From mail at a-beyer.de Mon Jan 1 22:20:21 2007 From: mail at a-beyer.de (Andreas Beyer) Date: Mon, 01 Jan 2007 19:20:21 -0800 Subject: mutable numeric type Message-ID: <4599CF75.6070209@a-beyer.de> There has been quite some traffic about mutable and immutable data types on this list. I understand the issues related to mutable numeric data types. However, in my special case I don't see a better solution to the problem. Here is what I am doing: I am using a third party library that is performing basic numerical operations (adding, multiplying, etc.) with objects of unknown type. Of course, the objects must support the numerical operators. In my case the third party library is a graph algorithm library and the assigned objects are edge weights. I am using the library to compute node distances, etc. I would like to be able to change the edge weights after creating the edges. Otherwise, I would have to remove the edges and re-create them with the new values, which is quite costly. Since I also didn't want to change the code of the graph library, I came up with a mutable numeric type, which implements all the numerical operators (instances are of course not hashable). This allows me to change the edge weights after creating the graph. I can do the following: >>> x = MutableNumeric(10) >>> y = MutableNumeric(2) >>> x*y 20 >>> x.value = 1.3 >>> x*y 2.6000000000000001 >>> The effect of numerical operations is determined by the contained basic data types: >>> x.value = 3 >>> x/2 1 >>> x.value = 3.0 >>> x/2 1.5 >>> Augmented operations change the instance itself: >>> x.value = 0 >>> id(x) -1213448500 >>> x += 2 >>> x MutableNumeric(2) >>> id(x) # show that same instance -1213448500 >>> Is there anything wrong with such design? I am a bit surprised that Python does not already come with such data type (which is really simple to implement). Is there something that I am missing here? Thanks! Andreas From http Thu Jan 25 15:07:51 2007 From: http (Paul Rubin) Date: 25 Jan 2007 12:07:51 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> Message-ID: <7xveiudg4o.fsf@ruckus.brouhaha.com> "sjdevnull at yahoo.com" writes: > I haven't had a need to do anything with OpenSSL from Python; all > that takes place in the Apache server That's a reasonable approach for a typical server-side web application, but there are other types of Python apps that can also want to use SSL. It's a pain to have to deal with OpenSSL at all, and I hope that TLSLite (a very incomplete SSL implementation written in pure Python) one day becomes complete and does all the stuff that JSSE does. > (possibly with some mod_rewrite rules to ensure that certain pages > are only hit from https and so forth). Normally you'd do that SSLRequireSSL or SSLRequire, if that matters. From danb_83 at yahoo.com Sat Jan 13 13:43:24 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Jan 2007 10:43:24 -0800 Subject: Boilerplate in rich comparison methods In-Reply-To: References: Message-ID: <1168713802.798237.171610@s34g2000cwa.googlegroups.com> On Jan 13, 12:52 am, Steven D'Aprano wrote: > I'm writing a class that implements rich comparisons, and I find myself > writing a lot of very similar code. If the calculation is short and > simple, I do something like this: > > class Parrot: > def __eq__(self, other): > return self.plumage() == other.plumage() > def __ne__(self, other): > return self.plumage() != other.plumage() > def __lt__(self, other): > return self.plumage() < other.plumage() > def __gt__(self, other): > return self.plumage() > other.plumage() > def __le__(self, other): > return self.plumage() <= other.plumage() > def __ge__(self, other): > return self.plumage() >= other.plumage() > > If the comparison requires a lot of work, I'll do something like this: > > class Aardvark: > def __le__(self, other): > return lots_of_work(self, other) > def __gt__(self, other): > return not self <= other > # etc. > > But I can't help feeling that there is a better way. What do others do? Typically, I write only two kinds of classes that use comparion operators: (1) ones that can get by with __cmp__ and (2) ones that define __eq__ and __ne__ without any of the other four. But for your case, I'd say you're doing it the right way. If you define a lot of classes like Parrot, you might want to try moving the six operators to a common base class: class Comparable: """ Abstract base class for classes using rich comparisons. Objects are compared using their cmp_key() method. """ def __eq__(self, other): return (self is other) or (self.cmp_key() == other.cmp_key()) def __ne__(self, other): return (self is not other) and (self.cmp_key() != other.cmp_key()) def __lt__(self, other): return self.cmp_key() < other.cmp_key() def __le__(self, other): return self.cmp_key() <= other.cmp_key() def __gt__(self, other): return self.cmp_key() > other.cmp_key() def __ge__(self, other): return self.cmp_key() >= other.cmp_key() def cmp_key(self): """Overriden by derived classes to define a comparison key.""" raise NotImplementedError() class Parrot(Comparable): def cmp_key(self): return self.plumage() # ... From tiedon_jano at hotmail.com Wed Jan 3 11:23:28 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Wed, 03 Jan 2007 16:23:28 GMT Subject: array of class / code optimization In-Reply-To: <6UPmh.6785$hr3.92@newsfe24.lga> References: <6UPmh.6785$hr3.92@newsfe24.lga> Message-ID: <4MQmh.145$jr6.14@read3.inet.fi> hg kirjoitti: > mm wrote: > >> Yes, it was the (), equivalent to thiks like new() create new object >> from class xy. >>> s1.append(Word) >> s1.append(Word()) >> >> But I was looking for a "struct" equivalent like in c/c++. >> And/or "union". I can't find it. >> >> Maybe you know a source (URL) "Python for c/c++ programmers" or things >> like that. >> >> >> Yes, I konw whats an object is... > > > A struct in C is unrelated to a struct in C++ as a struct in C++ _is_ a > class. > > > hg > What does your sentence mean, exactly? If I take a C file xyz.c containing a struct definition S, say, rename it to be xyz.cpp and feed it to a C++ compiler, the S sure remains a struct and the C++ compiler has no difficulty in handling it as a struct, so ?!? Cheers, Jussi From erick.lavoie at gmail.com Mon Jan 22 18:26:21 2007 From: erick.lavoie at gmail.com (=?ISO-8859-1?Q?Lavoie_=C9rick?=) Date: Mon, 22 Jan 2007 18:26:21 -0500 Subject: How to get self reference from within a module? Message-ID: <3ca9bbe50701221526p4bb7cffdx767d6737bed0a6a2@mail.gmail.com> Hi, i would like to now how to get a self reference from within a module. The goal is to be able to generate a list of all declared function within the module. Thanks, Erick -------------- next part -------------- An HTML attachment was scrubbed... URL: From mike.klaas at gmail.com Mon Jan 8 15:05:16 2007 From: mike.klaas at gmail.com (Klaas) Date: 8 Jan 2007 12:05:16 -0800 Subject: Traceback of hanged process In-Reply-To: References: Message-ID: <1168286710.482272.33770@11g2000cwr.googlegroups.com> Hynek Hanke wrote: > Hello, > > please, how do I create a pythonic traceback from a python process that > hangs and is not running in an interpreter that I executed manually > or it is but doesn't react on CTRL-C etc? I'm trying to debug a server > implemented in Python, so I need some analog of 'gdb attach' for C. > > Unfortunatelly, googling and reading documentation revealed nothing, so > please excuse if this question is dumb. In python2.5, you can run a background thread that listens on a port or unix socket, and prints a formatted version of sys._current_frames() to stderr. -Mike From steve at holdenweb.com Tue Jan 30 00:26:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Jan 2007 05:26:59 +0000 Subject: Ip address In-Reply-To: References: <1169990510.352536.4760@a34g2000cwb.googlegroups.com> Message-ID: Toby A Inkster wrote: > Steve Holden wrote: > >> There is absolutely no need to know the IP address of "your router" to >> communicate with Internet devices. Either your IP layer is configured to >> know the addresses of one or more routers, or it has discovered those >> address by dynamic means, or you can't get off-net because there aren't >> any routers. > > ... or you can't get off-net because you don't *know* the routers. > What I know or don't know makes absolutely no difference to whether my computer can reach the Internet, it's a matter of whether the IP layes is configured to know the appropriate address to which it can hand off non-local traffic. If you are trying to say that it's necessary to know the IP address of the routers in order to select a specific interface address from the available choices as "the Internet interface" then kindly say so and stop wallowing in semantic obscurity. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From nanjundi at gmail.com Mon Jan 15 20:09:12 2007 From: nanjundi at gmail.com (Nanjundi) Date: 15 Jan 2007 17:09:12 -0800 Subject: for v in l: References: Message-ID: <1168909752.262132.134390@q2g2000cwa.googlegroups.com> Try: l = [i+x for i in l] OR l = map(lambda i: i+x, l) -N Gert Cuykens wrote: > is there a other way then this to loop trough a list and change the values > > i=-1 > for v in l: > i=i+1 > l[i]=v+x > > something like > > for v in l: > l[v]=l[v]+x From fredrik at pythonware.com Thu Jan 4 07:18:05 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 Jan 2007 13:18:05 +0100 Subject: pow() works but sqrt() not!? References: <1167899693.759071.51450@31g2000cwt.googlegroups.com> Message-ID: "siggi" wrote: > Nope, I did not! But I used sqrt(9), and not math.sqrt(9). The latter works > excellent, thank you! From now on, I will use "import math" and > "math.fuction()" for EVERY mathematical function, even for pow() etc. just > to be on the safe side! pow and math.pow are two slightly different things, though. pow() works on any type that supports power-of operations (via the __pow__ hook), while math.pow treats everything as a 64-bit float: >>> math.pow(2, 200) 1.6069380442589903e+060 >>> pow(2, 200) 1606938044258990275541962092341162602522202993782792835301376L pow also takes a third modulo argument (pow(x,y,z) is equivalent to pow(x,y) % z, but can be implemented more efficiently for certain data types). From bthate at gmail.com Tue Jan 30 07:01:28 2007 From: bthate at gmail.com (bthate) Date: 30 Jan 2007 04:01:28 -0800 Subject: ANN: gozerbot IRC and JABBER bot Message-ID: <1170158487.843544.124070@l53g2000cwa.googlegroups.com> gozerbot a python irc and jabber bot see http://code.google.com/p/gozerbot you need: * a shell * python 2.4 or higher * if you want mysql support: the py-MySQLdb module * if you want jabber support: the xmpppy module why gozerbot? * user management by userhost * fleet .. use more than one bot in a program * relaying between fleet bots * use the bot through dcc chat * fetch rss feeds. * keep todo and shop lists * karma * quote * remember items * program your own plugins * builtin webserver * collective, run commands on other bots using their webserver * other stuff we are on channel #dunkbots on IRCnet .. try irc.xs4all.nl From firefoxxer at gmail.com Fri Jan 12 18:23:46 2007 From: firefoxxer at gmail.com (Coby) Date: 12 Jan 2007 15:23:46 -0800 Subject: How to respond to a confirmation prompt automatically In-Reply-To: <87d55j50x4.fsf@smsnet.pl> References: <1168632324.226733.130870@a75g2000cwd.googlegroups.com> <87d55j50x4.fsf@smsnet.pl> Message-ID: <1168644224.673196.186730@l53g2000cwa.googlegroups.com> Thanks Rob. Rob Wolfe wrote: > "Coby" writes: > > > Just to give you some background about my problem: > > > > I execute os.system(command), where command is a string. > > > > On the command line in windows, I get: > > > > "Continue, and unload these objects? [no]" > > > > I need to respond 'y' to continue, but I am uncertain on how to output > > the 'y' automatically. > > You need to use pipe. > > 1. > > p = os.popen(command, "w") > p.write("y\n") > > http://docs.python.org/lib/os-newstreams.html#os-newstreams > > 2. > > from subprocess import Popen, PIPE > p = Popen(command, shell=True, stdin=PIPE) > p.stdin.write("y\n") > > http://docs.python.org/lib/module-subprocess.html > > -- > HTH, > Rob From albert.wellens at gmail.com Tue Jan 16 17:17:51 2007 From: albert.wellens at gmail.com (awel) Date: 16 Jan 2007 14:17:51 -0800 Subject: Check a windows service In-Reply-To: <1168967374.568967.173690@11g2000cwr.googlegroups.com> References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> <1168967374.568967.173690@11g2000cwr.googlegroups.com> Message-ID: <1168985871.686464.198120@v45g2000cwv.googlegroups.com> Sorry, but could you give me an example with a real service 'cause I've tried this script but nothings happened, no error, nothings ; even if I launch it in cmd prompt. Thanks Tim Golden a ?crit : > awel wrote: > > > I'm new in python and I would like to know if it's possible to check if > > a specific windows service is present and if it's possible how can I > > do? > > This is one way: > > http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services > > You'd have to change that example slightly, but I > hope the principal is clear enough. If not, ask again. > > TJG From harvey.thomas at informa.com Tue Jan 16 08:55:25 2007 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 16 Jan 2007 05:55:25 -0800 Subject: re.sub and empty groups References: Message-ID: <1168955722.605022.268870@m58g2000cwm.googlegroups.com> Hugo Ferreira wrote: > Hi! > > I'm trying to do a search-replace in places where some groups are > optional... Here's an example: > > >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola").groups() > ('ola', None) > > >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|").groups() > ('ola', '') > > >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|ole").groups() > ('ola', 'ole') > > The second and third results are right, but not the first one, where > it should be equal to the second (i.e., it should be an empty string > instead of None). This is because I want to use re.sub() and when the > group is None, it blows up with a stack trace... > > Maybe I'm not getting the essence of groups and non-grouping groups. > Someone care to explain (and, give the correct solution :)) ? > > Thanks in advance, > > Hugo Ferreira > > -- > GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 >From the documentation: groups( [default]) Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. Your second group is optional and does not take part in the match in your first example. You can, however, still use this regular expression if you use groups('') rather than groups(). A better way probably is to use a simplified regular expression re.match(r"Image:([^\|]+)\|?(.*)", "Image:ola").groups() i.e. match the text "Image:" followed by at least one character not matching "|" followed by an optional "|" followed by any remaining characters. From sickcodemonkey at gmail.com Tue Jan 30 10:18:40 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 30 Jan 2007 10:18:40 -0500 Subject: Synchronous shutil.copyfile() In-Reply-To: <4e8efcf50701300705v2b787ec4h1c539cab8068d58c@mail.gmail.com> References: <4e8efcf50701300705v2b787ec4h1c539cab8068d58c@mail.gmail.com> Message-ID: <2adc542f0701300718u1ab0a686i3e91ef85c00a543d@mail.gmail.com> First off, I am just learning Python, so if there is a more efficient way to do this, then I am all ears.... (NOTE: The code below is something that I was messing with to learn threads... So some functionality is not applicable for your needs..I just wanted to show you a demonstration) One way that you could get around this, is to use threads. You can lock your thread and when the lock has been released, you could open it and ensure your copy has succeeded. Just a thought.... ~~~~~~~~~~~~~~~~~~~~~~~ import thread def counter(myId, count): for i in range(count): stdoutmutex.acquire() #Copy Your File Here stdoutmutex.release() exitmutexes[myId].acquire() stdoutmutex = thread.allocate_lock() exitmutexes = [] for i in range(2): exitmutexes.append(thread.allocate_lock()) thread.start_new(counter, (i, 2)) for mutex in exitmutexes: while not mutex.locked(): #Open Your File Here print 'Exiting' On 1/30/07, Hugo Ferreira wrote: > > Hi there, > > I have a problem. I'm using calling shutil.copyfile() followed by > open(). The thing is that most of the times open() is called before > the actual file is copied. I don't have this problem when doing a > step-by-step debug, since I give enough time for the OS to copy the > file, but at run-time, it throws an exception. > > Is there anyway to force a sync copy of the file (make python wait for > the completion)? > > Thanks in advance! > > Hugo Ferreira > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.daniels at acm.org Sun Jan 14 00:16:12 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 13 Jan 2007 21:16:12 -0800 Subject: Comparing a matrix (list[][]) ? In-Reply-To: <1168735426.313475.212710@11g2000cwr.googlegroups.com> References: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> <1168735426.313475.212710@11g2000cwr.googlegroups.com> Message-ID: <45a9b1d2$1@nntp0.pdx.net> bearophileHUGS at lycos.com wrote: > mat = [[9, 8, 12, 15], ..., [0, 0, 0, 5]] > > print min(el for row in mat for el in row if el > 0) > ... > If the OP needs the position he/she can do something like: << iterative solution >> Or you can still use min by keeping the position after the value: value, x_pos, y_pos = min( (elem, x, y) for y, row in enumerate(mat) for x, elem in enumerate(row) if elem > 0 ) You get the "first" entry with the minimal value. This code raises ValueError if all entries of mat are <= 0. --Scott David Daniels scott.daniels at acm.org From fumanchu at amor.org Sat Jan 20 15:58:54 2007 From: fumanchu at amor.org (fumanchu) Date: 20 Jan 2007 12:58:54 -0800 Subject: confused on python rpc with apache, is it possible? References: <51ce8uF1k0tl5U1@mid.uni-berlin.de> <1169276359.477277.17930@q2g2000cwa.googlegroups.com> <51etfpF1kappuU1@mid.uni-berlin.de> Message-ID: <1169326734.140275.49660@a75g2000cwd.googlegroups.com> krishnakant Mane wrote: > can I do xml-rpc using the default libraries that come with every > python installer? You can, but others have packaged them up to make it easier. CherryPy includes an xmlrpc tool (and has no dependencies other than standard Python). You can see an example of what your code would look like in the "setup_server" portion of http://www.cherrypy.org/browser/trunk/cherrypy/test/test_xmlrpc.py Further resources on using CherryPy's xml-rpc are just a Google away. Note that some of these may use different syntax as they target different versions of CherryPy (but the basics are the same). http://www.google.com/search?q=cherrypy+xmlrpc Robert Brewer System Architect Amor Ministries fumanchu at amor.org From leonel.gayard at gmail.com Thu Jan 4 15:11:39 2007 From: leonel.gayard at gmail.com (leonel.gayard at gmail.com) Date: 4 Jan 2007 12:11:39 -0800 Subject: A python library to convert RTF into PDF ? In-Reply-To: References: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> <5stnp25m2uffc4n5k7g9e68hk2l85u4fmm@4ax.com> <1167850322.373355.327020@s34g2000cwa.googlegroups.com> Message-ID: <1167941499.204931.99010@42g2000cwt.googlegroups.com> > Why not use OO.org to convert DOC to PDF? It does so natively, IIRC. I can't insert variables if the template is a DOC file. This is why we are using RTF. Felipe Almeida Lessa wrote: > On 3 Jan 2007 10:52:02 -0800, leonel.gayard at gmail.com > wrote: > > I have tried to > > convert them to tex using OpenOffice, but the result is ugly as hell. > > Why not use OO.org to convert DOC to PDF? It does so natively, IIRC. > > -- > Felipe. From paddy3118 at netscape.net Wed Jan 10 14:28:56 2007 From: paddy3118 at netscape.net (Paddy) Date: 10 Jan 2007 11:28:56 -0800 Subject: An iterator with look-ahead In-Reply-To: References: Message-ID: <1168457336.695589.127030@77g2000hsv.googlegroups.com> Neil Cerutti wrote: > On 2007-01-10, Steven Bethard wrote: > > Neil Cerutti wrote: > >> For use in a hand-coded parser I wrote the following simple > >> iterator with look-ahead. > > > > There's a recipe for this: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 > > > > Note that the recipe efficiently supports an arbitrary > > look-ahead, not just a single item. > > > >> I haven't thought too deeply about what peek ought to return > >> when the iterator is exhausted. Suggestions are respectfully > >> requested. > > > > In the recipe, StopIteration is still raised on a peek() > > operation that tries to look past the end of the iterator. > > That was all I could think of as an alternative, but that makes > it fairly inconvenient to use. I guess another idea might be to > allow user to provide a "no peek" return value in the > constructor, if they so wish. > > -- > Neil Cerutti You could raise a different Exception, PeekPastEndEception ? - Paddy. From Thomas.Ploch at gmx.net Tue Jan 9 01:55:08 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Tue, 09 Jan 2007 07:55:08 +0100 Subject: How to write temporary data to file? In-Reply-To: <1168324907.803841.79020@42g2000cwt.googlegroups.com> References: <1168324907.803841.79020@42g2000cwt.googlegroups.com> Message-ID: <45A33C4C.30203@gmx.net> Ravi Teja schrieb: > Thomas Ploch wrote: >> Hi folks, >> >> I have a data structure that looks like this: >> >> d = { >> 'url1': { >> 'emails': ['a', 'b', 'c',...], >> 'matches': ['d', 'e', 'f',...] >> }, >> 'url2': {... >> } >> >> This dictionary will get _very_ big, so I want to write it somehow to a >> file after it has grown to a certain size. >> >> How would I achieve that? >> >> Thanks, >> Thomas > > Pickle/cPickle are standard library modules that can persist data. > But in this case, I would recommend ZODB/Durus. > > (Your code example scares me. I hope you have benevolent purposes for > that application.) > > Ravi Teja. > Thanks, but why is this code example scaring you? Thomas From nmm1 at cus.cam.ac.uk Tue Jan 9 13:23:43 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 9 Jan 2007 18:23:43 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: In article , Tim Peters writes: |> |> Well, just about any technical statement can be misleading if not qualified |> to such an extent that the only people who can still understand it knew it |> to begin with <0.8 wink>. The most dubious statement here to my eyes is |> the intro's "exactness carries over into arithmetic". It takes a world of |> additional words to explain exactly what it is about the example given (0.1 |> + 0.1 + 0.1 - 0.3 = 0 exactly in decimal fp, but not in binary fp) that |> does, and does not, generalize. Roughly, it does generalize to one |> important real-life use-case: adding and subtracting any number of decimal |> quantities delivers the exact decimal result, /provided/ that precision is |> set high enough that no rounding occurs. Precisely. There is one other such statement, too: "Decimal numbers can be represented exactly." What it MEANS is that numbers with a short representation in decimal can be represented exactly in decimal, which is tautologous, but many people READ it to say that numbers that they are interested in can be represented exactly in decimal. Such as pi, sqrt(2), 1/3 and so on .... |> > and how is decimal no better than binary? |> |> Basically, they both lose info when rounding does occur. For example, Yes, but there are two ways in which binary is superior. Let's skip the superior 'smoothness', as being too arcane an issue for this group, and deal with the other. In binary, calculating the mid-point of two numbers (a very common operation) is guaranteed to be within the range defined by those numbers, or to over/under-flow. Neither (x+y)/2.0 nor (x/2.0+y/2.0) are necessarily within the range (x,y) in decimal, even for the most respectable values of x and y. This was a MAJOR "gotcha" in the days before binary became standard, and will clearly return with decimal. Regards, Nick Maclaren. From skip at pobox.com Thu Jan 25 09:33:19 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 25 Jan 2007 08:33:19 -0600 Subject: Python does not play well with others In-Reply-To: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> Message-ID: <17848.49071.20916.590158@montanaro.dyndns.org> Paul> .... We all know that the Python language has issues (or "warts" Paul> as they are popularly called), although some of the most notable Paul> ones don't seem to have been addressed as yet in the plans for Paul> Python 3000 (eg. default argument evaluation), but some of the Paul> most awkward aspects of using Python involve libraries, not some Paul> deficiency of the language.... I think EasyInstall might have some role to play in improving the library status quo. Consider the cgi module. It was originally written in probably 1995 or earlier and for a long time was the only game in town. Consequently, lots of applications used it. Times have changed though and there's a whole new alphabet soup of web application frameworks available. I installed Pylons the other day with "easy_install pylons". No fuss, no muss. Over time (maybe in Python 3) modules like cgi, which arguably no longer belong in the core can be maintained externally and installed only when needed. Skip From fredrik at pythonware.com Wed Jan 3 14:10:59 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Jan 2007 20:10:59 +0100 Subject: When argparse will be in the python standard installation In-Reply-To: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> Message-ID: PengYu.UT at gmail.com wrote: > I feel argparse has some useful things that optparse doesn't have. But > I can't find it argparse in python library reference. I'm wondering > when it will be available in the python standard installation. there's already two different option parsing modules in the standard library. maybe improving one of the existing ones might be a better idea than adding a third one? From mail at microcorp.co.za Tue Jan 9 00:58:56 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 9 Jan 2007 07:58:56 +0200 Subject: Execute binary code References: <1168284300.638111.191440@38g2000cwa.googlegroups.com><1168289145.319706.199950@11g2000cwr.googlegroups.com><4866bea60701081251we2bf7f3vb55a285ee20e91f6@mail.gmail.com> <4866bea60701081252o3acf0470x4607613961da7b5e@mail.gmail.com> Message-ID: <021901c733c8$3fe20000$03000080@hendrik> "Chris Mellon" wrote: > Repost. Is there any chance at all that ML could set the > reply-to to the list instead of the sender? +1 - I regularly hit "reply all", delete the OP, and then I get : "Message has a suspicious header" - Hendrik From gagsl-py at yahoo.com.ar Mon Jan 15 19:02:35 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 21:02:35 -0300 Subject: Problem with win32pipe.popen2 In-Reply-To: <1168856689.749595.74440@q2g2000cwa.googlegroups.com> References: <1168856689.749595.74440@q2g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070115204043.05c85860@yahoo.com.ar> At Monday 15/1/2007 07:24, diego wrote: >I'm trying to understand how popen2 works. Found in this group, that >popen2.popen2 can cause trouble so i chose win32pipe.popen2. > >have a look a the listing of 2 files: >ekmain.py: >************** >import win32pipe > >(stdin1, stdout1) = win32pipe.popen2("test1.py") >stdin1.write("1\n") >print stdout1.readlines() # This will print the result. >************** > >test1.py: >************** >a=raw_input("a=") >print "***a=",a >print "finished!" >************** > > >i do not understand, why ekmain.py produces only following output: >['a='] > >why is the stdin1.write("1\n") command ignored? Using popen4 instead of popen2 we get stderr too, and there is a traceback: ['a=Traceback (most recent call last):\n', ' File "C:\\TEMP\\test1.py", line 1, in ?\n', ' a=raw_input("a=")\n', 'EOFError: EOF when reading a line\n'] Using "python test1.py" as the popen4 argument we get the expected result: C:\TEMP>main.py ['a=***a= 1\n', 'finished!\n'] (I don't know why) >p.s.: i working with python 2.3 on win2000. I used 2.4 on XPSP2. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nmm1 at cus.cam.ac.uk Mon Jan 8 13:39:15 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 8 Jan 2007 18:39:15 GMT Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> <1168277798.302236.184180@s34g2000cwa.googlegroups.com> <1168280213.382178.228020@11g2000cwr.googlegroups.com> Message-ID: In article <1168280213.382178.228020 at 11g2000cwr.googlegroups.com>, "Ziga Seilnacht" writes: |> |> There was a recent bug report identical to your complaints, which |> was closed as invalid. The rationale for closing it was that things |> like: |> |> print ("a, bc", "de f,", "gh), i") |> |> would be extremely confusing if the current behaviour was changed. See |> http://www.python.org/sf/1534769 |> for details. Well, I wasn't complaining - merely querying. If this approach is taken, it would be better to document it, so that authors of derived classes follow the convention. Regards, Nick Maclaren. From tew24 at spam.ac.uk Fri Jan 19 05:57:37 2007 From: tew24 at spam.ac.uk (Tom Wright) Date: Fri, 19 Jan 2007 10:57:37 +0000 Subject: How to find out if another process is using a file References: Message-ID: js wrote: > How about using lock? > Let writing process locks the files before writing, and unlock after > the job's done. Is locking mandatory or co-operative? I don't have any control over the process which is doing the writing, so if it's co-operative it's no good to me. If it's mandatory, then I can try to acquire a lock on the file - if this fails or blocks, then the other process must have it open. Will this work? From gagsl-py at yahoo.com.ar Tue Jan 23 21:15:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Jan 2007 23:15:30 -0300 Subject: Simple Matrix class In-Reply-To: <1169602411.917985.89840@l53g2000cwa.googlegroups.com> References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070123225155.01be96d8@yahoo.com.ar> At Tuesday 23/1/2007 22:33, Paul McGuire wrote: >On Jan 23, 6:59 pm, Robert Kern wrote: > > Paul McGuire wrote: > > > I've posted a simple Matrix class on my website as a small-footprint > > > package for doing basic calculations on matrices up to about 10x10 in > > > size (no theoretical limit, but performance on inverse is exponential). > > > > Why is that? A simple and robust LU decomposition should be no > more than O(n**3). > > > >Well "3" is an exponent isn't it? :) But constant! x**2 is a "power" (or quadratic, or polynomial) function. 2**x is an "exponential" function. They're quite different. >In truth, in my laziness, I didn't *actually* test the performance. >But after measuring inversion times for nxn matrices for n=2 to 12, I >get these results (run on Python 2.4.2, on a 2GHz CPU): > >n seconds ln(seconds) >2 0.000411225449045 -7.79636895604 >3 0.00102247632031 -6.88552782893 >4 0.00437541642862 -5.43175358002 >5 0.0146999129778 -4.21991370509 >6 0.0507813143849 -2.98022681913 >7 0.143077961026 -1.94436561528 >8 0.39962257773 -0.917234732978 >9 1.14412558021 0.134640659841 >10 3.01953516439 1.10510290046 >11 8.76039971561 2.17024153354 >12 21.8032182861 3.0820575867 > >Plotting n vs. ln(seconds) gives a fairly straight line of slope about >1.09, and exp(1.09) = 2.97, so your big-O estimate seems to line up >nicely with the experimental data - I couldn't have fudged it any >better. Nope, such semilog plot shows that time grows exponentially, like t=3*exp(n), and that's really bad! :( The points should be aligned on a log-log plot to be a power function. As Robert Kern stated before, this problem should be not worse than O(n**3) - how have you implemented it? -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jdvolz at gmail.com Mon Jan 8 19:30:03 2007 From: jdvolz at gmail.com (jdvolz at gmail.com) Date: 8 Jan 2007 16:30:03 -0800 Subject: Network failure when using urllib2 In-Reply-To: <1168301738.984509.3030@38g2000cwa.googlegroups.com> References: <1168292352.349983.139260@i15g2000cwa.googlegroups.com> <1168301738.984509.3030@38g2000cwa.googlegroups.com> Message-ID: <1168302603.565442.113760@v33g2000cwv.googlegroups.com> I am fetching different web pages (never the same one) from a web server. Does that make a difference with them trying to block me? Also, if it was only that site blocking me, then why does the internet not work in other programs when this happens in the script. It is almost like something is seeing a lot of traffic from my computer, and cutting it off thinking it is some kind of virus or worm. I am starting to suspect my firewall. Anyone else have this happen? I am going to read over that documentation you suggested to see if I can get any ideas. Thanks for the link. Shuad On Jan 8, 4:15 pm, "Ravi Teja" wrote: > jdv... at gmail.com wrote: > > I have a script that uses urllib2 to repeatedly lookup web pages (in a > > spider sort of way). It appears to function normally, but if it runs > > too long I start to get 404 responses. If I try to use the internet > > through any other programs (Outlook, FireFox, etc.) it will also fail. > > If I stop the script, the internet returns. > > > Has anyone observed this behavior before? I am relatively new to > > Python and would appreciate any suggestions. > > > ShuadI am assuming that you are fetching the full page every little while. > You are not supposed to do that. The admin of the web site you are > constantly hitting probably configured his server to block you > temporarily when that happens. But don't feel bad :-). This is a common > Beginners mistake. > > Read here on the proper way to do this.http://diveintopython.org/http_web_services/review.html > especially 11.3.3. Last-Modified/If-Modified-Since in the next page > > Ravi Teja. From guettli.usenet at thomas-guettler.de Mon Jan 22 10:47:32 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 22 Jan 2007 15:47:32 GMT Subject: OpenOffice 2.0 UNO update Links; need help References: Message-ID: <51k4kkF1krq1vU1@mid.individual.net> Sells, Fred wrote: > I've got a ~100 page document I assemble from ~30 OOo .odt files with some > search and replace functions. I then produce a PDF. So far so good. > > Now I need to get a barcode from our internal website and insert that. The > barcode will vary based on some parameters. Our internal site provides a > .jpg image (or .gif) based on those parameters. You can use pdftk to insert the barcode into the pdf. (No python and OOo involved) I think it is a very bad idea to use a jpg for the barcode. There are many libaries which provide EPS. If you need an image format, please use PNG. Jpeg is for images from a digital camera. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From thinker at branda.to Tue Jan 30 03:39:30 2007 From: thinker at branda.to (Thinker) Date: Tue, 30 Jan 2007 16:39:30 +0800 Subject: Conversion of string to integer In-Reply-To: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> References: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> Message-ID: <45BF0442.30503@branda.to> jupiter wrote: > Hi guys, > > I have a problem. I have a list which contains strings and numeric. > What I want is to compare them in loop, ignore string and create > another list of numeric values. > > I tried int() and decimal() but without success. > > eq of problem is > > #hs=string.split(hs) > hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"] > hs = [.............] import re reo = re.compile(r'^[0-9]+(\.[0-9]+)?$') result = [e for e in hs if reo.match(e)] -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py From jstroud at mbi.ucla.edu Tue Jan 16 18:22:39 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 16 Jan 2007 15:22:39 -0800 Subject: Making a simple script standalone In-Reply-To: <5d1084-5j7.ln1@whisper.very.softly> References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: Rikishi 42 wrote: > Hi, > I'm new to this group. I've tried finding my answer in existing messages, > but no such luck. > > What I want to do is to compile/bundle/prepare/whatever_term a simple > Python script for deployment on a Windows machine. Installing Python > itself on that machine, is not an option. Ideally I would like to obtain > a single executable file, but a script+runtime is acceptable. > > There is nothing graphical, nothing fancy about the script. > The only imports are: os, stat, string and time. > > > Any suggestions on an - easy and clear - path to follow ? pyinstaller + innosetup. James From john at baumanfamily.com Mon Jan 15 19:15:13 2007 From: john at baumanfamily.com (John Bauman) Date: Mon, 15 Jan 2007 19:15:13 -0500 Subject: How naive is Python? In-Reply-To: References: <1168848408.785931.285160@q2g2000cwa.googlegroups.com> <17835.39437.115750.617750@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > Actually, it isn't until I work my way back to 2.3 that I start to see > quadratic behavior: Yes, that's because the behavior was changed for 2.4, so it wouldn't be quadratic in this case. From vineeth.rv at gmail.com Tue Jan 16 05:32:59 2007 From: vineeth.rv at gmail.com (Vineeth Kashyap) Date: 16 Jan 2007 02:32:59 -0800 Subject: I wrote a C++ code generator in Python, would anyone please help me to review the code? :) In-Reply-To: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> References: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> Message-ID: <1168943577.936249.191040@s34g2000cwa.googlegroups.com> Hi, I am interested in your proposal. I am basically a C/C++ programmer, but recently fell in love with python. Please send more details on fgen. We could probably start working. :) Kevin Wan wrote: > fgen is a free command line tool that facilitates cross platform c++ > development, including header generation, cpp file generation, makefile > generation, unit test framework generation, etc. > > http://sf.net/projects/fgen > > I'm not very familiar with Python. Any feedback are appreciated! Or > anyone like to develop it with me? > > Thanks. From bj_666 at gmx.net Thu Jan 4 02:46:58 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 04 Jan 2007 08:46:58 +0100 Subject: code optimization (calc PI) / Full Code of PI calc in Python and C. References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> <1167872076.937415.250340@11g2000cwr.googlegroups.com> Message-ID: In , Michael M. wrote: > * The C is very fast, Python not. > * Target: Do optimization, that Python runs nearly like C. As someone else already asked: Why? You can't beat a compiled to machine code language with an interpreted one when doing integer arithmetic. > counter=c > while 0<=counter+4000: > f.append(2000) # f.append( int(a/5) ) > counter=counter-1 > # b=b+1 Why do you count so complicated here? It's hard to see that this creates a list with 2801 elements. > d = int(d/g) ## needs cast to int Instead of converting the numbers to float by "real" division and then converting back the result you should do integer division: d = d // g or d //= g > pi = pi + str("%04d" % int(e + d/a)) The `str()` call is unnecessary. And again: try to stick to integer arithmetic with ``//``. Here is my attempt to convert the C code, not written with speed in mind and I was too lazy too time it. :-) from itertools import izip def pi(): result = list() d = 0 e = 0 f = [2000] * 2801 for c in xrange(2800, 0, -14): for b, g in izip(xrange(c, 1, -1), xrange((c * 2) - 1, 0, -2)): d += f[b] * 10000 h, f[b] = divmod(d, g) d = h * b h, i = divmod(d, 10000) result.append('%.4d' % (e + h)) e = i return ''.join(result) Ciao, Marc 'BlackJack' Rintsch From theller at ctypes.org Thu Jan 11 15:13:24 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 11 Jan 2007 21:13:24 +0100 Subject: py2exe: zipfile=None raised ImportError In-Reply-To: <1168543966.212663.141840@i56g2000hsf.googlegroups.com> References: <1168543966.212663.141840@i56g2000hsf.googlegroups.com> Message-ID: <45A69A64.20204@ctypes.org> (I forgot to copy the list ;-) Tim schrieb: > > I'm at the end of my limited experience... > > > > I'm using py2exe to create an executable. I'm using bundle level 1. > > When I don't use the zipfile option, the executable and library.zip get > > created and the executable works correctly. > > > > When I add the zipfile=None option to put everything into the exe, the > > exe doesn't work. It raises an ImportError whose traceback is: > > > > File "...boot_common.py" ... no module name linecache > > File " ... no module named zipextimporter > > File "my.py" ... no module name optparse > > > > It looks like the imported modules are not being found in the zip, or > > something didn't get included that needed to be included. > > > > Does anybody know what's happening and how to fix it? I have don't know if this helps or not, but you should better clean everything (remove the build and the dist subdirectories) when you are changing the options in the setup script and 'recompile'. Another tip: You can examine what is in the zipfile, or the exe (if using zipfile=None) when you rename the file to a *.zip file, and open it with winzip or another archiver. Thomas From stuart at bmsi.com Tue Jan 16 00:23:35 2007 From: stuart at bmsi.com (Stuart D. Gathman) Date: Tue, 16 Jan 2007 00:23:35 -0500 Subject: Debugging SocketServer.ThreadingTCPServer Message-ID: I have a ThreadingTCPServer application (pygossip, part of http://sourceforge.net/projects/pymilter). It mostly runs well, but occasionally goes into a loop. How can I get a stack trace of running threads to figure out where the loop is? Is there some equivalent of sending SIGQUIT to Java to get a thread dump? If needed, I can import pdb and set options at startup, but there needs to be some external way of triggering the dump since I can't reproduce it at will. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From deets at nospam.web.de Tue Jan 2 09:36:53 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Jan 2007 15:36:53 +0100 Subject: mutable numeric type In-Reply-To: <459A46A8.3050706@skynet.be> References: <1167735454.604184.110630@i12g2000cwa.googlegroups.com> <459A46A8.3050706@skynet.be> Message-ID: <4vv906F1dkfheU1@mid.uni-berlin.de> Helmut Jarausch schrieb: > pgarrone at acay.com.au wrote: >> Way to go. >> Try doing this. >> x = MutableNumeric(42) > ^^^^^^^^^^^^^^ > where is this defined? In the OPs example. Diez From gert.cuykens at gmail.com Mon Jan 15 18:43:08 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Tue, 16 Jan 2007 00:43:08 +0100 Subject: whats wrong with my reg expression ? In-Reply-To: <7.0.1.0.0.20070115195902.05c75aa0@yahoo.com.ar> References: <7.0.1.0.0.20070115195902.05c75aa0@yahoo.com.ar> Message-ID: thx PS i also cant figure out what is wrong here ? rex=re.compile('^"(?P[^"]*)"$',re.M) for v in l: v=rex.match(v).group('value') v=v.replace('""','"') return(l) v=rex.match(v).group('value') AttributeError: 'NoneType' object has no attribute 'group' From Hieu.D.Hoang at gmail.com Tue Jan 30 23:21:49 2007 From: Hieu.D.Hoang at gmail.com (Hieu.D.Hoang at gmail.com) Date: 30 Jan 2007 20:21:49 -0800 Subject: Unicode error handler In-Reply-To: References: Message-ID: <1170217309.125918.214060@v33g2000cwv.googlegroups.com> On Jan 30, 11:28 pm, Walter D?rwald wrote: > > codecs.register_error("transliterate", transliterate) > > Walter Really, really slick solution. Though, why was it [:1], not [0]? ;-) And one more thing: > def transliterate(exc): > if not isinstance(exc, UnicodeEncodeError): > raise TypeError("don'ty know how to handle %r" % r) I don't understand what %r and r are and where they are from. The man 3 printf page doesn't have %r formatting. Thanks for the tip. Hieu From no-spam at no-spam-no-spam.invalid Thu Jan 11 05:11:51 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 11 Jan 2007 11:11:51 +0100 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <7x8xga215f.fsf@ruckus.brouhaha.com> Message-ID: Nick Maclaren wrote: > In article <7x8xga215f.fsf at ruckus.brouhaha.com>, > Paul Rubin writes: > |> > |> > Yes, I know that it is a bit Irish for the best way to use a shared > |> > memory system to be to not share memory, but that's how it is. > |> > |> But I thought serious MPI implementations use shared memory if they > |> can. That's the beauty of it, you can run your application on SMP > |> processors getting the benefit of shared memory, or split it across > |> multiple machines using ethernet or infiniband or whatever, without > |> having to change the app code. > > They use it for the communication, but don't expose it to the > programmer. It is therefore easy to put the processes on different > CPUs, and get the memory consistency right. > Thus communicated data is "serialized" - not directly used as with threads or with custom shared memory techniques like POSH object sharing. Robert From weekender_ny at yahoo.com Sat Jan 13 15:15:44 2007 From: weekender_ny at yahoo.com (John) Date: 13 Jan 2007 12:15:44 -0800 Subject: Threaded for loop Message-ID: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> I want to do something like this: for i = 1 in range(0,N): for j = 1 in range(0,N): D[i][j] = calculate(i,j) I would like to now do this using a fixed number of threads, say 10 threads. What is the easiest way to do the "parfor" in python? Thanks in advance for your help, --j From harvey.thomas at informa.com Thu Jan 18 06:40:55 2007 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 18 Jan 2007 03:40:55 -0800 Subject: One more regular expressions question In-Reply-To: <1169117912.193536.321260@a75g2000cwd.googlegroups.com> References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> <1169117912.193536.321260@a75g2000cwd.googlegroups.com> Message-ID: <1169120455.276931.170810@38g2000cwa.googlegroups.com> Victor Polukcht wrote: > My pattern now is: > > (?P[^(]+)(?P\d+)\)\s+(?P\d+) > > And i expect to get: > > var1 = "Unassigned Number " > var2 = "1" > var3 = "32" > > I'm sure my regexp is incorrect, but can't understand where exactly. > > Regex.debug shows that even the first block is incorrect. > > Thanks in advance. > > On Jan 18, 1:15 pm, Roberto Bonvallet > wrote: > > Victor Polukcht wrote: > > > My actual problem is i can't get how to include space, comma, slash.Post here what you have written already, so we can tell you what the > > problem is. > > > > -- > > Roberto Bonvallet You are missing \( after the first group. The RE should be: '(?P[^(]+)\((?P\d+)\)\s+(?P\d+)' From larry.bates at websafe.com Tue Jan 9 11:54:24 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 09 Jan 2007 10:54:24 -0600 Subject: Using with CSV library in Python 2.2!!! In-Reply-To: <1168348224.843657.27330@42g2000cwt.googlegroups.com> References: <1168348224.843657.27330@42g2000cwt.googlegroups.com> Message-ID: <-vqdnaYTVsAgVT7YnZ2dnUVZ_ubinZ2d@comcast.com> mohan wrote: > Hi Guys, > > I'm back one more basic question, this time on using CSV (Comma > Seperated Value) library with Python 2.2. At my workplace I have Python > 2.2 installed and am using PythonWin 2.2.1 IDE from Mark Hammond. > > I want to use the CSV library module for reading data from the .csv > files and when I try to import the module, I get the error "CSV module > is not found". The reason, CSV module is missing from the Python root > directories. Now my first question is, > > 1. Does Python 2.2 come with CSV library module or not? If yes, have I > lost it somewhere?? > > 2. If Python 2.2 does not come with CSV module, is it possible to add > the CSV module to the Python root and start working?? > > 3. If yes, where do I get this module from?? > > Would be glad to have an answer for these questions. Thanks in advance. > > Cheers, > Mohan. > Object Craft wrote the csv library that predated the one released in Python 2.3. You can still get it for earlier Python versions here: http://www.object-craft.com.au/projects/csv/download.html -Larry From liberty2777 at yahoo.com Mon Jan 1 20:26:36 2007 From: liberty2777 at yahoo.com (J. Richards) Date: Mon, 1 Jan 2007 17:26:36 -0800 (PST) Subject: HowTo feed AcctName and Password into a website via HTTP Message-ID: <20070102012636.98394.qmail@web60522.mail.yahoo.com> I'm doing QA testing of a WebApp. First step before crawling the links is to enter the two texts mentioned. Do I extract the login page using: import sys, os, urllib, urlparse Then figure out the HTTP string and then feed that into a HTTP Post ? Or do I use Forms, CGI or Pamie ?? Whats the best way on Linux? Whats the best way on Windows. Thank you. __________________________________________________ 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 careo at fastmail.fm Sat Jan 20 03:06:53 2007 From: careo at fastmail.fm (Dane Jensen) Date: Sat, 20 Jan 2007 00:06:53 -0800 Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: <01bc01c73c5f$75e8cfe0$03000080@hendrik> References: <01bc01c73c5f$75e8cfe0$03000080@hendrik> Message-ID: <200701200006.53698.careo@fastmail.fm> On Friday 19 January 2007 22:51, Hendrik van Rooyen wrote: > "Steven D'Aprano" wrote: > > Or perhaps I should say: > > > > .snoitnevnoc > > hsilgnE tpada )ylbissop revenehw( dluohs ew os dna ,naitraM ton > > ,puorgswen egaugnal hsilgnE na no er'ew ,segaugnal hcus era ereht fi neve > > tuB > > First I thought it was Welsh or Cornish or something. > > Then it was like being in my first year of school again- > reading letter by letter. Never realised how difficult it is. > > I suppose it will improve with practice. Not to steer this topic even futher off topic, but this is something that's been on my mind lately... The biggest problem with it that the letters were forwards and not also backwards (and the parens). But then, it's my understanding that as a left-handed person, reading and writing backwards is far easier for me than for the majority that is right-handed. Have any other lefties found that the case? -Dane From igouy at yahoo.com Fri Jan 19 22:53:12 2007 From: igouy at yahoo.com (Isaac Gouy) Date: 19 Jan 2007 19:53:12 -0800 Subject: Py 2.5 on Language Shootout In-Reply-To: <1169258423.824108.228810@s34g2000cwa.googlegroups.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> Message-ID: <1169265192.891496.194550@q2g2000cwa.googlegroups.com> pgarrone at acay.com.au wrote: > Alioth is a great site for selecting the language in which to implement > primitives. Usually it's C. And for selecting a language for which you might need to implement primitives in C :-) > > Two of the alioth benchmarks, Partial-sums and Spectral-norm, could be > done using Numarray, or would be done with Numarray if most of the > program was in Python and there was a need to implement a similar > numerical procedure. The speed would be up near the compiled language > benchmarks. However the specific wording of these benchmarks prohibits > this approach. Spectral-norm must pretend the dataset is infinite, and > Partial-sums has to be implemented in a simple dumb loop. And we wouldn't use a na?ve recursive algorithm to find fibonnaci numbers ... unless we were interested in recursion for its own sake. Maybe the author of spectral-norm was interested in function calls. Maybe the author of partial-sums was interested in simple dumb loops and simple dumb Math. > Looking over the benchmarks, one gains the impression that Python is a > slow language. What does that even mean - a slow language? > My first serious Python programming exercise involved converting a 900 > line Bash Shell program to a 500 line Python program, with a speedup > factor of 17. Using Python allowed an OO structure and advanced > containers, meaning the program was more maintainable and portable, > which were the main aims of the exercise. The speedup was a surprising > and welcome side benefit. I think it was mosly because the Python > byte-code interpreter is probably an order of magnitude faster than > Bash's direct interpretation, and because in Python system calls to > recurse directories and create symbolic links were not forked to > separate processes. In fact I would guess that the overall speed of the > Python program would be little less than a C program, given that most > of the time would be spent in system calls. /I would guess/ > Its almost possible to make a large Python program arbitrarily fast by > profiling it and implementing slow bits as primitives. Size is probably > of greater concern. We could read that simply as - /it's not possible/ to make a large Python program arbitrarily fast. Is that what you meant? From greg at cosc.canterbury.ac.nz Tue Jan 30 05:38:45 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 30 Jan 2007 23:38:45 +1300 Subject: ANN: Pyrex 0.9.5.1 Message-ID: Pyrex 0.9.5.1 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ This is a minor release to fix a few bugs introduced in 0.9.5. See the CHANGES for details. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From __peter__ at web.de Wed Jan 3 15:16:40 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Jan 2007 21:16:40 +0100 Subject: Sorting on multiple values, some ascending, some descending References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> <1167852652.416990.158610@k21g2000cwa.googlegroups.com> Message-ID: Raymond Hettinger wrote: > dwelden wrote: >> I have successfully used the sort lambda construct described in >> http://mail.python.org/pipermail/python-list/2006-April/377443.html. >> However, how do I take it one step further such that some values can be >> sorted ascending and others descending? Easy enough if the sort values >> are numeric (just negate the value), but what about text? >> >> Is the only option to define an external sorting function to loop >> through the list and perform the comparisons one value at a time? > > The simplest way is to take advantage of sort-stability and do > successive sorts. For example, to sort by a primary key ascending and > a secondary key decending: > > L.sort(key=lambda r: r.secondary, reverse=True) > L.sort(key=lambda r: r.primary) > > A less general technique is to transform fields in a way that reverses > their comparison order: > > L.sort(key=lambda r: (-r.age, r.height)) # sorts descending age > and ascending height You can get generality if you are willing to pay the performance penalty: >>> items [(3, 1), (2, 2), (1, 1), (1, 3), (2, 1), (2, 3), (1, 2)] >>> class Reverse: ... def __cmp__(self, other): ... return -cmp(self.value, other.value) ... def __init__(self, value): ... self.value = value ... >>> items.sort(key=lambda (x, y): (x, Reverse(y))) >>> items [(1, 3), (1, 2), (1, 1), (2, 3), (2, 2), (2, 1), (3, 1)] Peter From adam at atlas.st Wed Jan 10 00:45:20 2007 From: adam at atlas.st (Adam Atlas) Date: 9 Jan 2007 21:45:20 -0800 Subject: Announcement -- ZestyParser Message-ID: <1168407920.281020.147680@k58g2000hse.googlegroups.com> This has been on Cheese Shop for a few weeks now, being updated now and then, but I never really announced it. I just now put up a real web page for it, so I thought I'd take the opportunity to mention it here. ZestyParser is my attempt at a flexible toolkit for creating concise, precise, and Pythonic parsers. None of the existing packages really met my needs; Pyparsing came the closest, but I find it still has some shortcomings. ZestyParser is simply an abstract implementation of how I think about parsing; I don't expect it'll meet everyone's parsing needs, but I hope it'll make typical parsing tasks more joyful. Here's the web page: http://adamatlas.org/2006/12/ZestyParser/ Here's the Cheese Shop page: http://cheeseshop.python.org/pypi/ZestyParser (I recommend you get the source package, as it includes the examples.) Check it out and let me know what you think! From gheissenberger at gmail.com Thu Jan 11 16:28:14 2007 From: gheissenberger at gmail.com (gheissenberger at gmail.com) Date: 11 Jan 2007 13:28:14 -0800 Subject: Python nuube needs Unicode help Message-ID: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> HELP! Guy who was here before me wrote a script to parse files in Python. Includes line: print u where u is a line from a file we are parsing. However, we have started recieving data from Brazil. If I open file to parse in VI, looks like: References: <1167986947.735415.99970@s34g2000cwa.googlegroups.com> <459E1988.8060807@v.loewis.de> Message-ID: <1167996955.467665.286170@42g2000cwt.googlegroups.com> Martin v. L?wis skrev: > Sheldon schrieb: > > Can anyone tell me what this error mean: > > #0 0x4008376e in PyType_IsSubtype () from /usr/lib/libpython2.3.so.1.0 > > It's not an error. It is just a frame from the backtrace. > > To understand the crash better, one would need to see more frames from > the backtrace. Ideally, one would run the program in a debugger to > analyse it further. > > Regards, > Martin I ran the program in GDB and it crashed giving the following backtrace: #0 0x4008376e in PyType_IsSubtype () from /usr/lib/libpython2.3.so.1.0 #1 0x4047730c in ?? () from /usr/lib/python2.3/site-packages/Numeric/_numpy.so #2 0x000000f2 in ?? () #3 0x08d9dd34 in ?? () #4 0x4046c780 in PyArray_Return () from /usr/lib/python2.3/site-packages/Numeric/_numpy.so #5 0x08d9dd44 in ?? () #6 0x40100300 in PyBaseString_Type () from /usr/lib/libpython2.3.so.1.0 #7 0x08105718 in ?? () #8 0x4007490d in PyObject_Init () from /usr/lib/libpython2.3.so.1.0 #9 0x08105ae0 in ?? () Can you make head or tail of this? /Sheldon From pavlovevidence at gmail.com Sun Jan 21 22:51:47 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 21 Jan 2007 19:51:47 -0800 Subject: Reading Fortran Data In-Reply-To: <1169436377.634274.172460@s34g2000cwa.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> <1169424273.929396.133880@m58g2000cwm.googlegroups.com> <1169429808.910298.10240@11g2000cwr.googlegroups.com> <1169433752.130978.133210@a75g2000cwd.googlegroups.com> <1169436377.634274.172460@s34g2000cwa.googlegroups.com> Message-ID: <1169437907.263295.64840@q2g2000cwa.googlegroups.com> Beliavsky wrote: > Carl Banks wrote: > > > > > > A Fortran > > > list-directed write can print results in an almost arbitrary format, > > > depending on the compiler. Many compilers will separate integers by > > > several spaces, not just one, and they could use commas instead of > > > spaces if they wanted. > > > > 1. Hardly any compiler will produce a line of two integers, or reals, > > that another compiler couldn't read back. > > Yes, but for more than three numbers, the statement is wrong. Intel > Fortran prints four double precision random n > as > > 0.555891433847495 0.591161642339424 0.888434673900224 > > 0.487293557925127 > > but g95 prints them on a single line. Did you try to use one compiler's program's output as the other's input? How did it work? > I advise against using > list-directed Fortran writes to create files that other programs will > read, and I think most experienced Fortran programmers would agree. It's been awhile, but I'd consider myself an experienced Fortran programner. I don't really agree. Carl Banks From pretoriano_2001 at hotmail.com Mon Jan 8 08:29:51 2007 From: pretoriano_2001 at hotmail.com (vizcayno) Date: 8 Jan 2007 05:29:51 -0800 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <50ehtmF1fh46iU1@mid.uni-berlin.de> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <50ehtmF1fh46iU1@mid.uni-berlin.de> Message-ID: <1168262991.007239.118840@s34g2000cwa.googlegroups.com> Diez B. Roggisch ha escrito: > vizcayno schrieb: > > Hello: > > Need your help in the "correct" definition of the next function. If > > necessary, I would like to know about a web site or documentation that > > tells me about best practices in defining functions, especially for > > those that consider the error exceptions management. > > I have the next alternatives but I think there are better: > > > > IMHO none of them is good. Python has exceptions. Use them. There is no > need to awkwardly communicate error conditions using return-values. Use > return values to return values. Use exceptions in case of errors. > > Diez Diez, in that case I woul prefer not to use exceptions and wait for Python to abort itself and wait to see the message it issues. From mh at ohm.pixar.com Tue Jan 30 12:11:26 2007 From: mh at ohm.pixar.com (Mark Harrison) Date: Tue, 30 Jan 2007 17:11:26 GMT Subject: test,please ignore 2 qrm Message-ID: <2%Kvh.1991$4H1.1305@newssvr17.news.prodigy.net> please ignore From no-spam at no-spam-no-spam.invalid Fri Jan 12 06:29:41 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 12 Jan 2007 12:29:41 +0100 Subject: Is there a way to protect a piece of critical code? In-Reply-To: References: Message-ID: Hendrik van Rooyen wrote: > "robert" wrote: > > >> pushing data objects through an inter-thread queue is a major source for > trouble - as this thread shows again. >> Everybody builds up a new protocol and worries about Empty/Full, > Exception-handling/passing, None-Elements, ... >> I've noticed that those troubles disappear when a functional queue is used - > which is very easy with a functional language like Python. >> For example with > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 >> >> One would just use a cq=CallQueue() >> >> On the producer side one would just write the functional code one wants to > execute in a target thread: >> cq.call( what_i_want_do_func ) >> >> >> The consumer/receiver thread would just do (periodically) a non-blocking >> >> cq.receive() >> >> >> => Without any object fumbling, protocol worries and very fast. >> >> And note: This way - working with functional jobs - one can also "protect a > piece of critical code" most naturally and specifically for certain threads > without spreading locks throughout the code. >> Even things which are commonly claimed "forbidden" (even when using lots of > locks) can be magically done in perfect order and effectively this way. Think of > worker threads doing things in the GUI or in master / database owner threads > etc. >> Similarly discrete background thread jobs can be used in a functional style > this way: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491280 >> ( an alternative for the laborious OO-centric threading.Thread which mostly is > a lazy copy from Java ) >> or for higher job frequencies by using "default consumer threads" as also > shown in the 1st example of >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 >> > > Thank you - had a (very) quick look and I will return to it > later - It is not immediately obvious to my assembler > programmer's mentality - looks like in the one case > the thread starts up, does its job and then dies, and in > the other its a sort of "remote" daemon like engine, > that you can "tell what to do", from "here"... > > Both concepts seem nice and I will try to wrap my head > around them properly. > > So far I have only used dicts to pass functions around > in a relatively unimaginative static jump table like way... Probably one has just to see that one can a pass a function object (or any callable) around as any other object. Similar to a function address in assembler/C but very comfortable and with the comfort of closures (which automatically hold the status of local variables): def f(): print "hello" def g(func): print "I'll do it ..." func() print "done." def run(x): g(f) a="local variable\n" def h(): b="inner local" print "inner function" print x,a,b g(h) g(lambda:sys.stdout.write(a)) run(1) From there its just natural to not pass dead objects through an inter-thread queue, but just code as it or even a "piece of critical code" ... A small step in thought, but a big step in effect - soon eliminating bunches of worries about queues, pop-races/None objects, protocol, serialization, critical sections, thousands of locks etc. Robert From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 11:03:04 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 03:03:04 +1100 Subject: Iterator length References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> <1169167258.553202.190130@m58g2000cwm.googlegroups.com> <1169168139.350836.79790@s34g2000cwa.googlegroups.com> <1169211840.951796.87080@q2g2000cwa.googlegroups.com> Message-ID: On Fri, 19 Jan 2007 05:04:01 -0800, bearophileHUGS wrote: > Steven D'Aprano: >> > s = "aaabbbbbaabbbbbb" >> > from itertools import groupby >> > print [(h,leniter(g)) for h,g in groupby(s)] >> >> s isn't an iterator. It's a sequence, a string, and an iterable, but not >> an iterator. > > If you look better you can see that I use the leniter() on g, not on s. > g is the iterator I need to compute the len of. Oops, yes you're right. But since g is not an arbitrary iterator, one can easily do this: print [(h,len(list(g))) for h,g in groupby(s)] No need for a special function. >> I hope you know what sequences and strings are :-) > > Well, I know little still about the C implementation of CPython > iterators :-) > > But I agree with the successive things you say, iterators may be very > general things, and there are too many drawbacks/dangers, so it's > better to keep leniter() as a function separated from len(), with > specialized use. I don't think it's better to have leniter() at all. If you, the iterator creator, know enough about the iterator to be sure it has a predictable length, you know how to calculate it. Otherwise, iterators in general don't have a predictable length even in principle. -- Steven. From mail at microcorp.co.za Tue Jan 16 01:39:14 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 16 Jan 2007 08:39:14 +0200 Subject: Maths error References: Message-ID: <004c01c73939$0acbdc80$03000080@hendrik> "Nick Maclaren" wrote: [Tim Roberts] > |> Actually, this is a very well studied part of computer science called > |> "interval arithmetic". As you say, you do every computation twice, once to > |> compute the minimum, once to compute the maximum. When you're done, you > |> can be confident that the true answer lies within the interval. > > The problem with it is that it is an unrealistically pessimal model, > and there are huge classes of algorithm that it can't handle at all; > anything involving iterative convergence for a start. It has been > around for yonks (I first dabbled with it 30+ years ago), and it has > never reached viability for most real applications. In 30 years, it > has got almost nowhere. > > Don't confuse interval methods with interval arithmetic, because you > don't need the latter for the former, despite the claims that you do. > > |> For people just getting into it, it can be shocking to realize just how > |> wide the interval can become after some computations. > > Yes. Even when you can prove (mathematically) that the bounds are > actually quite tight :-) This sounds like one of those pesky: "but you should be able to do better" - kinds of things... - Hendrik From oliver at obeattie.com Fri Jan 5 12:39:17 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 5 Jan 2007 09:39:17 -0800 Subject: Encoding / decoding strings In-Reply-To: References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> <1168010144.000928.131920@42g2000cwt.googlegroups.com> Message-ID: <1168018757.397170.216870@11g2000cwr.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1168010144.000928.131920 at 42g2000cwt.googlegroups.com>, > oliver at obeattie.com wrote: > > > Basically, I want to encode an email address so that it looks something > > like 8d2e23c0a835598510c88a758c6b215a - this way the user does not know > > the email address they are looking at. They are public-facing views and > > they are to get info about other users, therefore anonymity is > > important. > > > > Any suggestions? > > Don't deliver encoded e-mail addresses to other users. They might decode > them and the anonymity is gone. > > What exactly are you trying to do? Why should users see encrypted e-mail > addresses of others? > > Ciao, > Marc 'BlackJack' Rintsch Basically, what I am trying to do is display all comments by a specified user on the website. As the only thing which has =always= been used to identify users which never changes is their e-mail addresses, this is the only thing which I can use. Obviously, I can't display this e-mail address though. From gagsl-py at yahoo.com.ar Wed Jan 3 19:52:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Jan 2007 21:52:57 -0300 Subject: code optimization (calc PI) In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> Message-ID: <7.0.1.0.0.20070103213856.055bae58@yahoo.com.ar> At Wednesday 3/1/2007 12:50, mm wrote: >Hmm... it's a question. It was not that easy to translate this #@*?%! >C-Program into readable code and then to Python. But it works. Because that code was written with C in mind, and uses some C subtlecies (uhm, got it right?) obscuring the original algorithm. BTW, do you know where the algorithm was taken from? >while c*2: `while c:` does *exactly* the same without computing (and discarding) an intermediate object. > while (b-1): If b>=1 initially (as it should, else this will be a loooooong loop), this is the same as `while b>1:` but without computing (and discarding) an intermediate object. > b=b-1 ## just for while-loop condition. I'm not sure if the compiler is smart enough to translate this into `b -= 1` > c = c-14; ## this is code vor the 1st while-loop, BUT bust run after Same as above > pi = pi + str("%04d" % int(e + d/a)) ## this should be fast?! I dont Someone else already pointed out how to improve this. You don't show the rest of the code... -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From GatlingGun at gmail.com Wed Jan 31 11:30:17 2007 From: GatlingGun at gmail.com (TOXiC) Date: 31 Jan 2007 08:30:17 -0800 Subject: Regex with ASCII and non-ASCII chars In-Reply-To: References: <1170243969.504255.134100@v33g2000cwv.googlegroups.com> <1170257547.041535.20770@a75g2000cwd.googlegroups.com> Message-ID: <1170261017.718665.179530@a75g2000cwd.googlegroups.com> It wont work with utf-8,iso or ascii... From horpner at yahoo.com Thu Jan 11 14:00:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Jan 2007 20:00:15 +0100 Subject: Fixed keys() mapping References: <1168535970.585977.317760@p59g2000hsd.googlegroups.com> Message-ID: On 2007-01-11, George Sakkis wrote: > I wrote an 'fkdict' dict-like class for mappings with a fixed > set of keys but I'm wondering if there's a simpler way to go > about it. > > First off, the main motivation for it is to save memory in case > of many dicts with the same keys, for example when reading from > a csv.DictReader or constructing dicts out of rows fetched from > a database. For example, test_mem(dict) takes up around 246 MB > according to the Windows task manager while test_mem(fkdict) > takes around 49 MB: It occurs to me you could create custom classes using __slots__ to get something similar. It's not terribly convenient. class XYDict(object): __slots__ = ['x', 'y'] def __getitem__(self, item): return self.__getattribute__(item) def __setitem__(self, key, item): return self.__setattr__(key, item) This isn't terribly convenient because you have to create a new class for every new set of keys. It isn't obvious to me how to program a metaclass to automate the process. A lot more boilerplate is necessary to act like a dict. > def test_mem(maptype): > d = [(i,str(i)) for i in range(1000)] > ds = [maptype(d) for i in xrange(10000)] > raw_input('finished') > > An additional benefit is predictable ordering (e.g. > fkdict.fromkeys('abcd').keys() == list('abcd')), like several > ordered-dict recipes. > > The implementation I came up with goes like this: each fkdict > instance stores only the values as a list in self._values. The > keys and the mapping of keys to indices are stored in a > dynamically generated subclass of fkdict, so that self._keys > and self._key2index are also accessible from the instance. The > dynamically generated subclasses are cached so that the second > time an fkdict with the same keys is created, the cached class > is called. > > Since the keys are determined in fkdict.__init__(), this scheme > requires changing self.__class__ to the dynamically generated > subclass. As much as I appreciate Python's dynamic nature, I am > not particularly comfortable with objects that change their > class and the implications this may have in the future (e.g. > how well does this play with inheritance). Is this a valid use > case for type-changing behavior or is there a better, more > "mainstream" OO design pattern for this ? I can post the > relevant code if necessary. Since the type gets changed before __init__ finishes, I don't see any problem with it. It sounds cool. -- Neil Cerutti It isn't pollution that is hurting the environment; it's the impurities in our air and water that are doing it. --Dan Quayle From inq1ltd at verizon.net Mon Jan 15 17:33:43 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Mon, 15 Jan 2007 17:33:43 -0500 Subject: download win32file Message-ID: <200701151733.43380.inq1ltd@verizon.net> Where can I download win32file / win32ui? The links below are broken. Mark Hammond should be made aware of this. URL below has two links that send you no place http://mail.python.org/pipermail/python-list/2002-October/167638.html Links: http://starship.python.net/crew/mhammond/win32/Downloads.html http://starship.python.net/crew/mhammond/downloads/win32all-148.exe Produce; The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error. jim-on-linux From ziade.tarek at gmail.com Sat Jan 6 04:47:17 2007 From: ziade.tarek at gmail.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Sat, 6 Jan 2007 10:47:17 +0100 Subject: python, zlib, and fedora 64bits Message-ID: <94bdd2610701060147i6725e52bgdcc3d81377366ecd@mail.gmail.com> Hello, I am trying to compile Python on a Fedora 64bits, and I can't make zlib work. a python setup.py build leads to : ... building 'zlib' extension gcc -pthread -shared build/temp.linux-x86_64-2.4/usr/local/src/Python-2.4.4/Modules/zlibmodule.o -L/opt/python-2.4.4/lib -L/usr/local/lib -lz -o build/lib.linux-x86_64-2.4 /zlib.so /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libz.a: could not read symbols: Bad value collect2: ld gab 1 als Ende-Status zur?ck running build_scripts running install_lib ... I've tried to recompile zlib, but didn't find any way to avoid this error any ideas ? Otherwise, does anyone has a zlib.so for fedora 64bits to send me ? Thx Tarek -- Tarek Ziad? | Association AfPy | www.afpy.org Blog FR | http://programmation-python.org Blog EN | http://tarekziade.wordpress.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Jan 29 12:25:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 Jan 2007 18:25:52 +0100 Subject: Can I undecorate a function? References: Message-ID: <526p10F1mbuekU2@mid.uni-berlin.de> Matthew Wilson wrote: > The decorator as_string returns the decorated function's value as > string. In some instances I want to access just the function f, > though, and catch the values before they've been decorated. > > Is this possible? > > def as_string(f): > def anon(*args, **kwargs): > y = f(*args, **kwargs) > return str(y) > return anon > > @as_string > def f(x): > return x * x Untested: def as_string(f): def anon(*args, **kwargs): y = f(*args, **kwargs) return str(y) andon.the_function = f return anon @as_string def f(x): return x * x print f.the_function(10) Diez From sxn02 at yahoo.com Wed Jan 10 17:32:44 2007 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Wed, 10 Jan 2007 14:32:44 -0800 (PST) Subject: Python 2.5 install on Gentoo Linux: failed dmb and _tkinter Message-ID: <514037.92809.qm@web56003.mail.re3.yahoo.com> Hi All, After a disaster in which I lost my whole harddrive, I decided to install the newest everything that I use. I put the latest Gentoo Linux, with gcc 4.1.1, installed tcl/tk 8.4.14 and tried Python 2.5. I tried with and without the suggested -fwrapv compiler option, and make gave me the same: # make case $MAKEFLAGS in \ *-s*) CC='gcc -pthread -fwrapv' LDSHARED='gcc -pthread -fwrapv -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ *) CC='gcc -pthread -fwrapv' LDSHARED='gcc -pthread -fwrapv -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ esac running build running build_ext db.h: found (4, 2) in /usr/include db lib: using (4, 2) db-4.2 building 'dbm' extension gcc -pthread -fwrapv -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DHAVE_GDBM_NDBM_H -I. -I/plus/install/Python-2.5/./Include -I./Include -I. -I/usr/local/include -I/plus/install/Python-2.5/Include -I/plus/install/Python-2.5 -c /plus/install/Python-2.5/Modules/dbmmodule.c -o build/temp.linux-i686-2.5/plus/install/Python-2.5/Modules/dbmmodule.o gcc -pthread -fwrapv -shared build/temp.linux-i686-2.5/plus/install/Python-2.5/Modules/dbmmodule.o -L/usr/local/lib -lgdbm -o build/lib.linux-i686-2.5/dbm.so *** WARNING: renaming "dbm" since importing it failed: build/lib.linux-i686-2.5/dbm.so: undefined symbol: dbm_firstkey building '_tkinter' extension gcc -pthread -fwrapv -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/plus/install/Python-2.5/./Include -I./Include -I. -I/usr/local/include -I/plus/install/Python-2.5/Include -I/plus/install/Python-2.5 -c /plus/install/Python-2.5/Modules/_tkinter.c -o build/temp.linux-i686-2.5/plus/install/Python-2.5/Modules/_tkinter.o gcc -pthread -fwrapv -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I. -I/plus/install/Python-2.5/./Include -I./Include -I. -I/usr/local/include -I/plus/install/Python-2.5/Include -I/plus/install/Python-2.5 -c /plus/install/Python-2.5/Modules/tkappinit.c -o build/temp.linux-i686-2.5/plus/install/Python-2.5/Modules/tkappinit.o gcc -pthread -fwrapv -shared build/temp.linux-i686-2.5/plus/install/Python-2.5/Modules/_tkinter.o build/temp.linux-i686-2.5/plus/install/Python-2.5/Modules/tkappinit.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib -L/usr/local/lib -ltk8.4 -ltcl8.4 -lX11 -o build/lib.linux-i686-2.5/_tkinter.so *** WARNING: renaming "_tkinter" since importing it failed: libtk8.4.so: cannot open shared object file: No such file or directory running build_scripts I have libtk: # ls -l /usr/local/lib/libtk8.4.so -r-xr-xr-x 1 root root 906285 Jan 10 16:08 /usr/local/lib/libtk8.4.so I can start wish. I need Tkinter for sure, and I'll like to have dbm. How should I proceed? Thanks for your advice, Sorin ____________________________________________________________________________________ Have a burning question? Go to www.Answers.yahoo.com and get answers from real people who know. From arkanes at gmail.com Wed Jan 24 16:56:45 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 15:56:45 -0600 Subject: wxPython: panel not fully painted In-Reply-To: <1169674550.837006.304370@q2g2000cwa.googlegroups.com> References: <1169674550.837006.304370@q2g2000cwa.googlegroups.com> Message-ID: <4866bea60701241356r46e287ebs484d488e6b7ce792@mail.gmail.com> On 24 Jan 2007 13:35:51 -0800, citronelu at yahoo.com wrote: > Hi, > > I'm new to wxpython, and the following code is my first serious > attempt: > > > #~ start code > import wx > > class MyPanel(wx.Panel): > def __init__(self, parent, id): > wx.Panel.__init__(self, parent, id) > self.parent = parent > button = wx.Button(self, -1, "Refresh") > button.SetPosition((100, 100)) > button.SetFocus() > > self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button) > > def OnCloseMe(self, event): > self.parent.f_redraw(self) > pass > > > class MyFrame(wx.Frame): > def __init__( > self, parent, ID, title, pos=wx.DefaultPosition, > size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE > ): > > wx.Frame.__init__(self, parent, ID, title, pos, size, style) > > def f_redraw(self, kill_window): > kill_window.Destroy() > MyPanel(self, -1) > #~ self.SendSizeEvent() > > > wxApp = wx.App() > f = MyFrame(None, -1, "App Title") > MyPanel(f, -1) > f.Show() > wxApp.MainLoop() > > > #~ end code > > > My problem is: when I press the "refresh" button, the new panel is > painted only as a 20x20 pixels square on the top right side of the > frame. If I resize the frame, the panel is repainted correctly (that's > why I inserted the self.SendSizeEvent() line - commented above). > > Is there something I'm missing, or this is normal ? > > I'm using python 2.4.3 and wxpython 2.8.1.1 unicode, on WinXP SP2. > Windows extensions are also installed. > This is expected. Note that your "redraw" is no such thing - you are destroying the window and creating a new one. A feature of the wx.Frame class is that if it has one and only one child, that child is sized to fill the client area of the frame. However, this sizing happens in response to size events of the frame itself, so when you create the new panel, it is shown at its default size until you resize the frame (or emulate resizing the frame via SendSizeEvent). From pgarrone at acay.com.au Tue Jan 2 05:57:34 2007 From: pgarrone at acay.com.au (pgarrone at acay.com.au) Date: 2 Jan 2007 02:57:34 -0800 Subject: mutable numeric type In-Reply-To: References: Message-ID: <1167735454.604184.110630@i12g2000cwa.googlegroups.com> Way to go. Try doing this. x = MutableNumeric(42) y = x x += 42 print y From Roland.Puntaier at br-automation.com Wed Jan 10 10:55:21 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Wed, 10 Jan 2007 16:55:21 +0100 Subject: call graph using python and cscope In-Reply-To: <1168348224.843657.27330@42g2000cwt.googlegroups.com> Message-ID: """ Sometimes it is nice to have the data used by cscope accessible in a programatic way. The following python script extract the "functions called" information from cscope (function: callGraph) and produced an html file from them. from csCallGraph import * acg=callGraph(entryFun,workingDir) entryFun is the function to start with (e.g. main) workingDir is the directory where cscope.out is located As a script it can be called like: csCallGraph main > myprogram.html """ import subprocess , os, sys def functionsCalled(entryFun,workingDir): cmd = "cscope -d -l -L -2%s"%entryFun process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, cwd=workingDir) csoutput= process.stdout.read() del process cslines=[arr.strip().split(' ') for arr in csoutput.split('\n') if len(arr.split(' '))>1] funsCalled={} for fl in cslines: if funsCalled.has_key(fl[0]): funsCalled[fl[0]]|=set([fl[1]]) else: funsCalled[fl[0]]=set([fl[1]]) allFuns=set(map(lambda x:x[1],cslines)) return (allFuns,funsCalled) def callGraph(entryFun,workingDir,cg={}): if not cg.has_key(entryFun): allFuns,funsCalled=functionsCalled(entryFun,workingDir) cg[entryFun]=funsCalled for af in allFuns: cg=callGraph(af,workingDir,cg) return cg def textCallGraph(acg): innerFuns=[(f,d,len(reduce(lambda x,y:x|y,d.values()))) for f,d in acg.items() if len(d)>0 ] leafFuns=[(f,d,0) for f,d in acg.items() if not len(d)>0 ] innerFuns.sort(lambda x,y: y[2]-x[2]) innerLen=len(innerFuns) leafLen=len(leafFuns) title=lambda aFun: '\n' + aFun + '\n' + '-'*len(aFun) def ff(aFun,funsCalled): fileFuns=zip(funsCalled.keys(),[' '+',\n '.join(funsCalledInFile) for funsCalledInFile in funsCalled.values()]) funIn=lambda f: '\n%s in '%f return title(aFun) + funIn(aFun) + funIn(aFun).join(map(lambda x:'%s:\n%s'%(x[0],x[1]),fileFuns)) strInner='\n'.join([ff(f[0],f[1]) for f in innerFuns]) strLeaves='\n'.join(map(lambda x:title(x[0]),leafFuns)) return strInner+'\n'+strLeaves def funWeights(acg): funWeights=dict([(f,reduce(lambda x,y:x|y,d.values())) for f,d in acg.items() if len(d)>0 ]+ [(f,[]) for f,d in acg.items() if not len(d)>0 ]) weights={} def calcWeights(af): if not weights.has_key(af): subFuns=funWeights[af] weights[af]=1 for f in subFuns: calcWeights(f) weights[af]+=weights[f] for af in funWeights.keys(): calcWeights(af) return weights def htmlCallGraph(acg): funW=funWeights(acg) innerFuns=[(f,d,funW[f]) for f,d in acg.items() if len(d)>0 ] leafFuns=[(f,d,0) for f,d in acg.items() if not len(d)>0 ] #innerFuns.sort(lambda x,y: y[2]-x[2])) def cfun(a,b): if b > a: return 1 elif b < a: return -1 return 0 innerFuns.sort(lambda x,y: cfun(x[2],y[2])) innerLen=len(innerFuns) leafLen=len(leafFuns) funDict=dict(zip(map(lambda x:x[0],innerFuns)+map(lambda x:x[0],leafFuns),range(innerLen+leafLen))) title=lambda aFun: '

' + aFun + ' (%i)'%funW[aFun] + '

\n' def ff(aFun,funsCalled): fun=lambda y:''+y+'' fileFuns=zip(funsCalled.keys(),[',\n'.join(map(fun,funsCalledInFile)) for funsCalledInFile in funsCalled.values()]) funIn=lambda f: '
%s in '%f return title(aFun) + funIn(aFun) + funIn(aFun).join(map(lambda x:'%s:\n%s'%(x[0],x[1]),fileFuns)) strInner='\n'.join([ff(f[0],f[1]) for f in innerFuns]) strLeaves='\n'.join(map(lambda x:title(x[0]),leafFuns)) return '\n\n'+strInner+'\n'+strLeaves+"\n\n" if __name__ == '__main__': if len(sys.argv) < 2: print 'Usage: csGragh.py entryFunction' sys.exit() entryFun=sys.argv[1] workingDir=os.getcwd() acg=callGraph(entryFun,workingDir) print htmlCallGraph(acg) From steve at holdenweb.com Thu Jan 25 04:16:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 25 Jan 2007 09:16:18 +0000 Subject: Python does not play well with others In-Reply-To: <1169678399.502252.123450@j27g2000cwj.googlegroups.com> References: <1169660807.369400.120220@h3g2000cwc.googlegroups.com> <1169678399.502252.123450@j27g2000cwj.googlegroups.com> Message-ID: Kay Schluehr wrote: > On 25 Jan., 04:46, "Paul Boddie" wrote: > >>> That's because, in those worlds, either the >>> development team for the language or the development team >>> for the subsystem takes responsibility for making them work. >>> Only Python doesn't do that.And this is where I'd almost reach agreement with you. It's not enough >> for the language to keep growing new features if the libraries are >> broken or appear archaic, and this task seems to be outside the "core >> developers" area of interest. > > But it shouldn't be - although this is not a request for the core > developers to maintain any 3rd party package in the world, of course. A > while ago someone on python-dev suggested to use builtbot to monitor > were 3rd party packages get broken by new Python releases and offered > this as a service to library developers. I do think this and similar > ideas are relevant to improve overall quality, not only that of the > CPython interpreter. I would also suggest stricter policies for PyPI > were unmaintained packages might be removed after a period ( or at > least tagged in a certain way ). > > But maybe admitting quality problems of free software that is affecting > the whole community ( and not just isolated projects ) is just too much > negative PR on a "competitive language market"? We all know Ruby makes > us happy and Haskell is driven by real academics, who are doing > software engineering right, by default. Maybe Python could survive only > leaving the impression that it binds to everything and has an ever > growing code base of high quality? > Looking at the history of the bug, it ends with a request from Martin von Loewis that James Eagan (the author of the patch, for which we should be grateful) provide unit tests and documentation to go with the code already contributed, finally followed by a comment from James that it will be a while before he has time to make the necessary changes. I don't think there's any attempt here to avoid admitting that there's a quality problem with the existing code. Adding new functionality without tests and documentation certainly wouldn't improve things. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From garryknight at gmx.net Sun Jan 28 21:35:46 2007 From: garryknight at gmx.net (Garry Knight) Date: Mon, 29 Jan 2007 02:35:46 +0000 Subject: IP address References: Message-ID: <1170038148.54673.0@demeter.uk.clara.net> Klaus Alexander Seistrup wrote: > urllib.urlopen("http://myip.dk/") http://whatismyip.org gives it to you in a more usable format. But, as others have pointed out, it might return your router's IP. -- Garry Knight garryknight at gmx.net From kay.schluehr at gmx.net Wed Jan 3 09:50:13 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 3 Jan 2007 06:50:13 -0800 Subject: function without brackets ? In-Reply-To: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> References: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> Message-ID: <1167835813.229187.93190@i12g2000cwa.googlegroups.com> Stef Mientki schrieb: > If I call a parameterless function without brackets at the end, > the function is not performed, but ... > I don't get an error message ??? > > Is this normal behavior ? Yes, this is perfectly o.k. because each function is a first class citizen in Python. The difference between foo() and foo is simply that foo() is the value returned by the function call on foo and foo is a function object. Kay From sturlamolden at yahoo.no Wed Jan 10 12:22:42 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 Jan 2007 09:22:42 -0800 Subject: Parallel Python In-Reply-To: <1168417065.105920.319970@o58g2000hsb.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> Message-ID: <1168449762.738411.128240@i56g2000hsf.googlegroups.com> parallelpyt... at gmail.com wrote: > That's right. ppsmp starts multiple interpreters in separate > processes and organize communication between them through IPC. Thus you are basically reinventing MPI. http://mpi4py.scipy.org/ http://en.wikipedia.org/wiki/Message_Passing_Interface From arkanes at gmail.com Thu Jan 11 09:41:13 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 11 Jan 2007 08:41:13 -0600 Subject: Type casting a base class to a derived one? In-Reply-To: References: Message-ID: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> On 11 Jan 2007 15:01:48 +0100, Neil Cerutti wrote: > On 2007-01-11, Frederic Rentsch wrote: > > If I derive a class from another one because I need a few extra > > features, is there a way to promote the base class to the > > derived one without having to make copies of all attributes? > > > > class Derived (Base): > > def __init__ (self, base_object): > > # ( copy all attributes ) > > ... > > > > This looks expensive. Moreover __init__ () may not be available > > if it needs to to something else. > > > > Thanks for suggestions > > How does it make sense to cast a base to a derived in your > application? > I can't figure out any circumstance when you'd need to do this in Python. Upcasting like this is something you do in statically typed languages. I suspect that the OP doesn't really believe dynamic casting works and doesn't want to pass a derived class for some reason. From ccurvey at gmail.com Wed Jan 31 12:22:40 2007 From: ccurvey at gmail.com (Chris Curvey) Date: 31 Jan 2007 09:22:40 -0800 Subject: how to make a python windows service know it's own identity Message-ID: <1170264160.124454.6270@j27g2000cwj.googlegroups.com> Hi all, I have used the win32com libraries to set up a service called MyService under Windows. So far, so good. Now I need to run multiple copies of the service on the same machine. I also have that working. For monitoring and logging, I'd like each instance of the service to know it's own identity (MyService1, MyService2, etc.) But I can't quite seem to grasp how to do this. In the code below, the command line parameter "-i" gives the service an identity, but how do I get the service to understand it's identity when it is started? Many thanks! class MyService(win32serviceutil.ServiceFramework): """NT Service.""" _svc_name_ = "MyService" _svc_display_name_ = "My Service" _id_ = '' def SvcDoRun(self): provider = MyServiceClass(identifier=self._id_) provider.start() # now, block until our event is set... win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE) # __init__ and SvcStop snipped ########################################################################### if __name__ == '__main__': import optparse parser = optparse.OptionParser() parser.add_option("-i", "--identifier", dest="identifier") (opts, args) = parser.parse_args() if opts.number is not None: MyService._svc_name_ += opts.identifier MyService._svc_display_name_ += opts.identifier MyService._provider_id_ = opts.identifier win32serviceutil.HandleCommandLine(MyService, customInstallOptions="i:") From gdamjan at gmail.com Thu Jan 25 19:13:16 2007 From: gdamjan at gmail.com (Damjan) Date: Fri, 26 Jan 2007 01:13:16 +0100 Subject: Question about docutils References: <45b7fca1$0$49206$14726298@news.sunsite.dk> <1169686142.135007.127760@m58g2000cwm.googlegroups.com> Message-ID: <45b947d1$0$49197$14726298@news.sunsite.dk> >> I'm using docutils 0.4. >> Is it possible to define special custom 'tags' (or something) that will >> invoke my own function? The function would then return the real content >> in the ReST document. > > I -think- this is what you're looking for: > http://docutils.sourceforge.net/docs/howto/rst-roles.html > > Hope it helps. Thanks, it looks to be exactly what I need... I'm reading it now, and will try to implement it. -- damjan From jgodoy at gmail.com Sat Jan 20 13:42:16 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 20 Jan 2007 16:42:16 -0200 Subject: OT Annoying Habits References: <1169317608.819304.321210@l53g2000cwa.googlegroups.com> Message-ID: <87bqkt5ylz.fsf@gmail.com> "John Machin" writes: > Michael.Coll-Barth at VerizonWireless.com wrote: > [snip] > >> The information contained in this message and any attachment may be >> proprietary, confidential, and privileged or subject to the work >> product doctrine and thus protected from disclosure. If the reader >> of this message is not the intended recipient, or an employee or >> agent responsible for delivering this message to 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 me >> immediately by replying to this message and deleting it and all >> copies and backups thereof. Thank you. > > ... and while we're talking about annoyances ... For those there is always http://www.goldmark.org/jeff/stupid-disclaimers/ :-) Be seeing you, -- Jorge Godoy From garyjefferson123 at yahoo.com Fri Jan 19 02:08:18 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 18 Jan 2007 23:08:18 -0800 Subject: selective logger disable/enable Message-ID: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> Suppose I have 3 modules that belong to a project, 'A', 'A.a' and 'B', and each module has its own logger, created with: module1logger = logging.getLogger('project.A') and module2logger = logging.getLogger('project.A.a') and module3logger = logging.getLogger('project.B') And I want to selectively enable/disable these, per module (for example, I only want logging from A and A.a, or just from B, etc). It seems like logging.Filter is supposed to let me do this, but I can't see how to apply it globally. Is there really no other way that to add a addFilter(filter) call to each of these loggers individually? logging.basicConfig gets inherited by all loggers, but it doesn't seem capable of giving a Filter to all loggers. Is there any way to do this? From aboudouvas at panafonet.gr Thu Jan 18 05:25:54 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 18 Jan 2007 02:25:54 -0800 Subject: PyODBC Stored proc calling Message-ID: <1169115954.917268.74210@51g2000cwl.googlegroups.com> Hi to all, can anyone give me a jump-start about how to call Stored Procedures from PyODBC ?? I want to execute a very simple testing Stored Procedure on an Sql Server database. I started using PyODBC and code like the following cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=hercules;DATABASE=pubs;UID=sa;PWD=pwd'') for row in cnxn.execute("select au_fname from authors"): print row.au_fname cnxn.close() and based on this, i can now write more complex ad-hoc sql string to get/update data. But how i can actually call Stored Procedures and passing parameters to them ?? Let's say i have the following SP: create procedure test_bed(@data varchar(100)) as // do something here. Any help ?? Thanks in advance From robert.kern at gmail.com Fri Jan 12 01:28:43 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 12 Jan 2007 00:28:43 -0600 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> Message-ID: Travis E. Oliphant wrote: > If you use numpy.fromfile, you need to skip past the initial header row > yourself. Something like this: > > fid = open('somename.csv') # I think you also meant to include this line: header = fid.readline() > data = numpy.fromfile(fid, sep=',').reshape(-1,6) > # for 6-column data. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From codecraig at gmail.com Tue Jan 9 09:33:25 2007 From: codecraig at gmail.com (abcd) Date: 9 Jan 2007 06:33:25 -0800 Subject: Determine an object is a subclass of another Message-ID: <1168353205.066357.39530@42g2000cwt.googlegroups.com> How can tell if an object is a subclass of something else? Imagine... class Thing: pass class Animal: pass class Dog: pass d = Dog() I want to find out that 'd' is a Dog, Animal and Thing. Such as... d is a Dog d is a Animal d is a Thing Thanks From gagsl-py at yahoo.com.ar Thu Jan 18 23:13:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 01:13:36 -0300 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: <3feaf$45aff382$d443bb3a$12046@news.speedlinq.nl> References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> <1168904865.253014.210140@m58g2000cwm.googlegroups.com> <8ab5f$45ad5c12$d443bb3a$7243@news.speedlinq.nl> <5d831$45aea748$d443bb3a$26464@news.speedlinq.nl> <3feaf$45aff382$d443bb3a$12046@news.speedlinq.nl> Message-ID: <7.0.1.0.0.20070119011101.038ee750@yahoo.com.ar> At Thursday 18/1/2007 19:24, Stef Mientki wrote: > > str(key)[7:-2] => key.__name__ >I didn't know that one It's here: http://docs.python.org/lib/specialattrs.html -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Sun Jan 28 21:00:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Jan 2007 23:00:37 -0300 Subject: Python interfacing with COM In-Reply-To: <1170002486.751749.23180@m58g2000cwm.googlegroups.com> References: <1170002486.751749.23180@m58g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20070128225544.047164d8@yahoo.com.ar> At Sunday 28/1/2007 13:41, Viewer T. wrote: >I am quite a newbie and I am trying to interface with Microsoft Word >2003 COM with Python. Please what is the name of the COM server for >Microsoft Word 2003? Just use Word.Application, will launch the currently installed Word: py> import win32com.client py> word = win32com.client.Dispatch("Word.Application") py> word.Visible = 1 py> word.Documents.Open(FileName=r"c:\any\filename.doc") py> word.Quit() -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From mail at microcorp.co.za Sat Jan 13 04:49:24 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 13 Jan 2007 11:49:24 +0200 Subject: Rational Numbers References: Message-ID: <000501c73797$3ef23ac0$03000080@hendrik> From: "Nick Maclaren" wrote: > Financial calculations need decimal FIXED-point, with a precisely > specified precision. It is claimed that decimal FLOATING-point > helps with providing that, but that claim is extremely dubious. > I can explain the problem in as much detail as you want, but would > very much rather not. Ok I will throw in a skewed ball at this point - use integer arithmetic, and work in tenths of cents or pennies or whatever, and don't be too lazy to do your own print formatting... To represent $121.23 as a float is just asking for trouble when you are trying to deal with something that can take a value like: $123 456 789 012 345 678 901.07 - and you are worried about the seven cents for accounting purposes... Remember that its not only money that is measured like that, but debt too... -Hendrik From aboudouvas at panafonet.gr Fri Jan 5 08:45:52 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 5 Jan 2007 05:45:52 -0800 Subject: program deployment In-Reply-To: <1168002070.704739.76470@q40g2000cwq.googlegroups.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> Message-ID: <1168004752.091662.178060@s80g2000cwa.googlegroups.com> > Python code is normally deployed as straight source code. But isn't this a problem of its own ?? I mean, many people do not feel good if the know that their source code is lying around on other machines... From tubby at bandaheart.com Wed Jan 3 20:07:56 2007 From: tubby at bandaheart.com (tubby) Date: Wed, 03 Jan 2007 20:07:56 -0500 Subject: new office formats, REs and Python Message-ID: How are Python users dealing with some of the new OASIS Open Document formats (Open Office) or MS Open XML formats. These formats store data in a file which is actual a zip archive that contains numerous files and folders. For example, a file saved from Open Office 2.0 named 'test.odt' can be unzipped into many parts... content.xml, meta.xml, settings.xml, etc, etc. How can I read these files do re searching and matching on them, etc? content.xml may have a string I'm searching for, but how would I attach that back to the original 'test.odt' file? Perl seems to have a module to handle this, does Python? http://search.cpan.org/dist/OpenOffice-OODoc/ From martin at v.loewis.de Sun Jan 21 18:56:23 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 22 Jan 2007 00:56:23 +0100 Subject: mmap caching In-Reply-To: <1169422167.683707.264180@a75g2000cwd.googlegroups.com> References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <45B3DD4D.3010009@v.loewis.de> <1169422167.683707.264180@a75g2000cwd.googlegroups.com> Message-ID: <45B3FDA7.9030702@v.loewis.de> George Sakkis schrieb: >> You must be misinterpreting what you are seeing. It's the operating >> system that decides what part of a memory-mapped file are held in >> memory, and that is certainly not without limits. > > Sure; what I meant was that that whatever the limit is, it's high > enough that a MemoryError is raised before the limit is reached. The operating system will absolutely, definitely, certainly release any cached data it can purge before reporting it is out of memory. So if you get a MemoryError, it is *not* because the operating system has cached too much data. In fact, memory that is read in because of mmap should *never* cause a MemoryError. Python calls MapViewOfFile when mmap.mmap is invoked, at which point the operating commits to providing that much address space to the application, along with backing storage on disk (typically, from the file being mapped, unless it is an anonymous map). Later access to the mapped range cannot fail (except for hardware errors), and if it would, you wouldn't see a MemoryError. > It's the one in the 'Processes' tab of the Windows task manager (XP > proffesional). By the way, I ran the same program on a box with more > physical memory and the mem. usage stops growing at around 430MB, by > which time the whole file is most likely cached. I'd be interested in > any suggestions other than "buy more RAM" :) (these are not my machines > anyway). As a starting point, try understanding better what is really happening. Turn on "Virtual Memory Size" in "View/Select Columns" also, and perhaps a few additional counters as well. Also take a look at the "Commit Charge", which takes into account swap file usage as well. Try increasing the size of the swap file. Regards, Martin From nospam at nospam.com Mon Jan 29 11:13:46 2007 From: nospam at nospam.com (Hampton Din) Date: Mon, 29 Jan 2007 10:13:46 -0600 Subject: Excellent Interview with Dennis D'Souza, full of laughs References: <1170083292.991070.79560@v33g2000cwv.googlegroups.com> Message-ID: <45be1d27$0$97248$892e7fe2@authen.yellow.readfreenews.net> stupid troll From manouchk at gmail.com Thu Jan 18 11:34:55 2007 From: manouchk at gmail.com (manouchk) Date: 18 Jan 2007 08:34:55 -0800 Subject: nsis and command-line argument Message-ID: <1169138095.499650.8530@m58g2000cwm.googlegroups.com> Hi, is there a standart way to prepare a single exe with nsis that pass the command line to an exe created by py2exe on windows? py2exe allows to prepare an exe that get the command-line but needs some lib file so that it is not so elegant to ditribute. I tried a simple setup.nsis script to prepare a single file exe with works fine except that it does get the command-line. Is there a way do get the command line with the setup.nsis script? or any other simple method ? From practicalperl at gmail.com Fri Jan 19 05:54:33 2007 From: practicalperl at gmail.com (Jm lists) Date: Fri, 19 Jan 2007 18:54:33 +0800 Subject: Why this script can work? In-Reply-To: <51bjskF1jbnhrU1@mid.uni-berlin.de> References: <51bjskF1jbnhrU1@mid.uni-berlin.de> Message-ID: Thanks for all the helps. I'm not habitual for this usage of 'else',other languages seem don't support this syntax. i.g,writting the codes below by Perl would get an error: # perl -le 'for $i (1..10){print $i} else{print "finished"}' syntax error at -e line 1, near "}else" Execution of -e aborted due to compilation errors. 2007/1/19, Diez B. Roggisch : > Jm lists wrote: > > > Please help with this script: > > > > class ShortInputException(Exception): > > '''A user-defined exception class.''' > > def __init__(self,length,atleast): > > Exception.__init__(self) > > self.length=length > > self.atleast=atleast > > > > try: > > s=raw_input('Enter something --> ') > > if len(s)<3: > > raise ShortInputException(len(s),3) > > # Other work can continue as usual here > > except EOFError: > > print '\nWhy did you do an EOF on me?' > > except ShortInputException,x: > > print 'ShortInputException: The input was of length %d, was > > expecting at least %d' %(x.length,x.atleast) > > else: > > print 'No exception was raised.' > > > > > > My questions are: > > > > 1) ShortInputException,x: what's the 'x'? where is it coming? > > except , : > > will catch an exception of the kind specified in (it might > actually be more than one), and store the exception object in the variable > named > > > 2) The 'if' and 'else' are not in the same indent scope,why this can work? > > > Because additionally to if, also for and try have else-clauses. The latter > two are only being called if the body of the control structure hasn't been > left due to "unnatural" circumstances. See this: > > > > > for i in xrange(10): > pass > else: > print "test 1" > > for i in xrange(10): > break > else: > print "test 2" > > try: > pass > except: > pass > else: > print "test 3" > > try: > raise "I know I shouldn't rais strings..." > except: > pass > else: > print "test 4" > > > > It will only print > > test 1 > test 3 > > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From gandalf at designaproduct.biz Fri Jan 5 12:04:23 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 18:04:23 +0100 Subject: importing / loading a module / class dynamically In-Reply-To: References: Message-ID: <459E8517.7040901@designaproduct.biz> > Thanks, > > What I am doing is adding plugin support to PyCrust ... so I'm looking for a > mechanism where anyone can develop a plugin and have it loaded by pycrust. > > the .py was a typo > > > why the "...Have at least an empty plugin/name1/__init__.py file..." ? > When you do import plugins.name1.name1 then "plugins" and "plugins/name1" should be a package, not a module. A package is a special directory that contains package initialization code in a __init__.py file. If you do not have the file, then the "plugins" directory will be only a directory, and it cannot be imported. For details, see: http://docs.python.org/tut/node8.html#SECTION008400000000000000000 Laszlo From Thomas.Ploch at gmx.net Tue Jan 9 09:57:02 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Tue, 09 Jan 2007 15:57:02 +0100 Subject: How to write temporary data to file? In-Reply-To: <45A362EF.1080006@designaproduct.biz> References: <45A31767.9030404@gmx.net> <45A362EF.1080006@designaproduct.biz> Message-ID: <45A3AD3E.1090500@gmx.net> Laszlo Nagy schrieb: > Thomas Ploch ?rta: >> Hi folks, >> >> I have a data structure that looks like this: >> >> d = { >> 'url1': { >> 'emails': ['a', 'b', 'c',...], >> 'matches': ['d', 'e', 'f',...] >> }, >> 'url2': {... >> } >> >> This dictionary will get _very_ big, so I want to write it somehow to a >> file after it has grown to a certain size. >> >> How would I achieve that? >> > How about dbm/gdbm? Since urls are strings, you can store this dict in a > database instance and actually use it from your program as it were a dict? > > Laszlo > Well, but how do I save the nested dict values? I don't want to eval them, so this is no option for me. Thomas From fuzzyman at gmail.com Fri Jan 5 15:52:58 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2007 12:52:58 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: <1168030378.766579.48900@v33g2000cwv.googlegroups.com> Stef Mientki wrote: > Not sure I wrote the subject line correct, > but the examples might explain if not clear > > > *** first attempt *** > class pin: > def __init__ (self): > self.Name = 'Unknown Pin' > > aap = pin() # create an instance > aap.Name = 'aap' # set it's name > print aap.Name # print it's name > # but why should I set it's name ?? > print 'aap' # I can just as well print a constant string !! > # (ok there will be an extra check) > > > *** second attempt *** > class pin2: > def __init__ (self, naam): > self.Name = naam > > aap2 = pin2('aap2') # seems completely redundant to me. > print aap2.Name > print 'aap2' > > > Can this be achieved without redundancy ? > Uhm.. if your code can work with a constant then creating an object to hold it as an attribute is redundant. If on the other hand you want an object to hold several attributes, and methods for working with them, and then want to pass these objects around your code with a single reference - then maybe an object is the best way. If you don't need custom classes then don't use them... Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > thanks, > Stef Mientki From fairwinds at eastlink.ca Mon Jan 1 10:08:30 2007 From: fairwinds at eastlink.ca (David Pratt) Date: Mon, 01 Jan 2007 11:08:30 -0400 Subject: Collecting list of module dependencies In-Reply-To: <17817.8145.709408.736456@montanaro.dyndns.org> References: <45991BE2.2010803@eastlink.ca> <17817.8145.709408.736456@montanaro.dyndns.org> Message-ID: <459923EE.40303@eastlink.ca> Hi skip. Many thanks for this. Exactly what I need :-) Regards, David skip at pobox.com wrote: > David> Hi. Is anyone aware of any code to create a list of dependent > David> modules for a python module. > > modulefinder: http://docs.python.org/lib/module-modulefinder.html > > Added to Python in 2.3. > > Skip > From Thomas.Ploch at gmx.net Wed Jan 3 11:29:00 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Wed, 03 Jan 2007 17:29:00 +0100 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: <1167839629.435980.311750@k21g2000cwa.googlegroups.com> References: <1167839629.435980.311750@k21g2000cwa.googlegroups.com> Message-ID: <459BD9CC.1060702@gmx.net> Matimus schrieb: > I don't know of a converter, one may exist. I have seen similar > requests though and will give you a similar response to what I have > seen. A converter, if it exists, may be able to produce working code > but _not_ readable code. Python is a language whose strength comes > from, among other things, its readability and conventions. Learning > python is best done by using the online documentation > (http://docs.python.org/tut/tut.html) and reading existing code (take a > look at the built in modules). > > My biggest fear of teaching someone to program by using a program to > convert perl to python is that they will end up writing python that > still looks like perl. > > I don't know if it helps, but I know others will give you similar > advice. > > -Matt > I think that it *is* possible to do it, but a whole lot of work had to be done to achieve this. It is all about how many rules (like how to convert this block of unreadable code of language X into a readable python block) you are willing to find/program (and these are a lot). It is a almost gigantic task to make this work proper, but it definitely *is* possible. Something like this doesn't exist yet, but people (especially Computational Linguists) are working on this. Thomas From nmm1 at cus.cam.ac.uk Wed Jan 24 16:22:43 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 24 Jan 2007 21:22:43 GMT Subject: The reliability of python threads References: Message-ID: In article , aahz at pythoncraft.com (Aahz) writes: |> |> My response is that you're asking the wrong questions here. Our database |> server locked up hard Sunday morning, and we still have no idea why (the |> machine itself, not just the database app). I think it's more important |> to focus on whether you have done all that is reasonable to make your |> application reliable -- and then put your efforts into making your app |> recoverable. Absolutely! Shit happens. In a well-designed world, that would not be the case, but we don't live in one. Until you have identified the cause, you can't tell if threading has anything to do with the failure - given what we know, it seems likely, but what Aahz says is how to tackle the problem WHATEVER the cause. Regards, Nick Maclaren. From wolf_tracks at invalid.com Sun Jan 7 11:22:07 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 07 Jan 2007 16:22:07 GMT Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: Jussi Salmela wrote: > W. Watson kirjoitti: >> Thomas Ploch wrote: > > >>> https://sourceforge.net/projects/pywin32/ >>> >>> I think this is the place to go >>> >>> Thomas >>> >>> >> That gets me the python program (pywin), which I got from a URL in a >> post above (python-win.msi). I guess these are the same or at least >> just the interpreter, and do not provide the IDE-debugger. I can't get >> pythonwin, the debugger and IDE. The link was broken last night when I >> tried it. Well, let me try now. Nope, it still reports "Error 404: >> File Not Found" > > > I don't understand your difficulties. If you've got Python installed and > want to install the "Python for Windows extensions" aka pywin32, the > above link is the way to go. > > Clicking it gets you to a Sourceforge page, where you can click > "download" which gets you to ap page where you can choose which version > of pywin32 build 210 you want. Choose the exe that was built for the > Python version (e.g. 2.5) you are using, download and run it to install > pywin32. > > HTH, > Jussi As I understand it, there are two files I'm after: 1. python interpreter, and 2. a python editor. It's #2 that I'm having trouble downloading. The link is broken. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet ""I do not fear death. I had been dead for billions and billions of years before I was born, and had not suffered the slightest inconvenience from it." -- Mark Twain (a nod to evolution) -- Web Page: From jmfbahciv at aol.com Wed Jan 10 09:31:36 2007 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 10 Jan 07 14:31:36 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: In article , zoara wrote: >On 9 Jan 2007 06:58:15 -0800, octabox at gmail.com wrote: > >> Hello all, >> >> I represent Octabox, an Internet Start-up developing a wide-scale >> platform for Internet services. We are very interested to know your >> thoughts on Internet productivity and how it might be improved, and to >> that end we have set up a short survey at our website - >> http://www.octabox.com/productivity_poll.php >> We would very much appreciate if you would take a couple of minutes to >> fill it up and influence our direction and empahsis. > >Well, that was too tempting to pass up. Amusing answers related to dirty >bastard time-wasting spammers duly entered and submitted. My hope is that one of these groups of kids will learn from the nose-wiping service a.f.c. gives them and we get a query back full of curiosity. It is ironic that these ads ask for expert help and then get rude when it's given. /BAH From paddy3118 at netscape.net Tue Jan 9 01:16:08 2007 From: paddy3118 at netscape.net (Paddy) Date: 8 Jan 2007 22:16:08 -0800 Subject: Colons, indentation and reformatting. (2) Message-ID: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> I was just perusing a Wikipedia entry on the "off side rule" at http://en.wikipedia.org/wiki/Off-side_rule . It says that the colon in Python is purely for readability, and cites our FAQ entry http://www.python.org/doc/faq/general.html#why-are-colons-required-fo... . However, near the top of the Alternatives section, it states that for C type, curly braces using languages: "An advantage of this is that program code can be automatically reformatted and neatly indented without fear of the block structure changing". Thinking about it a little, it seems that a colon followed by non-indented code that has just been pasted in could also be used by a Python-aware editor as a flag to re-indent the pasted code. Tell me it is not so, or I will be editing the Wikipedia page I think. - Paddy. From michele.simionato at gmail.com Wed Jan 31 14:17:04 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 31 Jan 2007 11:17:04 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> References: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> Message-ID: <1170271023.955808.314010@q2g2000cwa.googlegroups.com> On Jan 31, 5:23 pm, "Frank Potter" wrote: > I want to find a multithreaded downloading lib in python, > can someone recommend one for me, please? > Thanks~ Why do you want to use threads for that? Twisted is the obvious solution for your problem, but you may use any asynchronous framework, as for instance the good ol Tkinter: """ Example of asynchronous programming with Tkinter. Download 10 times the same URL. """ import sys, urllib, itertools, Tkinter URL = 'http://docs.python.org/dev/lib/module-urllib.html' class Downloader(object): chunk = 1024 def __init__(self, urls, frame): self.urls = urls self.downloads = [self.download(i) for i in range(len(urls))] self.tkvars = [] self.tklabels = [] for url in urls: var = Tkinter.StringVar(frame) lbl = Tkinter.Label(frame, textvar=var) lbl.pack() self.tkvars.append(var) self.tklabels.append(lbl) frame.pack() def download(self, i): src = urllib.urlopen(self.urls[i]) size = int(src.info()['Content-Length']) for block in itertools.count(): chunk = src.read(self.chunk) if not chunk: break percent = block * self.chunk * 100/size msg = '%s: downloaded %2d%% of %s K' % ( self.urls[i], percent, size/1024) self.tkvars[i].set(msg) yield None self.tkvars[i].set('Downloaded %s' % self.urls[i]) if __name__ == '__main__': root = Tkinter.Tk() frame = Tkinter.Frame(root) downloader = Downloader([URL] * 10, frame) def next(cycle): try: cycle.next().next() except StopIteration: pass root.after(50, next, cycle) root.after(0, next, itertools.cycle(downloader.downloads)) root.mainloop() Michele Simionato From robin at reportlab.com Wed Jan 17 11:05:03 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 17 Jan 2007 16:05:03 +0000 Subject: 2.3-2.5 what improved? In-Reply-To: <17838.13871.896086.9204@montanaro.dyndns.org> References: <45ADFACC.6080807@chamonix.reportlab.co.uk> <17838.13871.896086.9204@montanaro.dyndns.org> Message-ID: <45AE492F.9000504@chamonix.reportlab.co.uk> skip at pobox.com wrote: > Robin> I sort of remember claims being made about 2.5 being 10% faster > Robin> than 2.4/2.3 etc etc. Can anyone say where the speedups were? > > What's New might be enlightening: > > http://www.google.com/search?q=what%27s+new+site%3Apython.org > > Skip thanks -- Robin Becker From gagsl-py at yahoo.com.ar Wed Jan 10 23:24:03 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 01:24:03 -0300 Subject: SubProcess _make_inheritable In-Reply-To: References: Message-ID: <7.0.1.0.0.20070111011800.03d03258@yahoo.com.ar> At Wednesday 10/1/2007 13:10, Roland Puntaier wrote: >SubProcess.py needs to be patched - at least in 2.4 - to work from >windows GUIs: > > def _make_inheritable(self, handle): > """Return a duplicate of handle, which is inheritable""" > if handle==None: handle=-1 > return DuplicateHandle(GetCurrentProcess(), handle, > GetCurrentProcess(), 0, 1, > DUPLICATE_SAME_ACCESS) You should submit it to the tracker, not post here and hope someone would notice... http://sourceforge.net/tracker/?group_id=5470 Anyway, I don't see in which case would handle be None. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From martin at v.loewis.de Fri Jan 12 03:00:24 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 12 Jan 2007 09:00:24 +0100 Subject: Python 2.5 install on Gentoo Linux: failed dmb and _tkinter In-Reply-To: References: Message-ID: <45a74018$0$10291$9b622d9e@news.freenet.de> Sorin Schwimmer schrieb: >> Did you add /usr/local/lib to /etc/ld.so.conf? > > It's there It is it also listed with "ldconfig -p"? Regards, Martin From jstroud at mbi.ucla.edu Tue Jan 30 18:48:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 30 Jan 2007 15:48:37 -0800 Subject: how to "free" an object/var ? In-Reply-To: References: Message-ID: Stef Mientki wrote: > If I create a large array of data or class, > how do I destroy it (when not needed anymore) ? > > Assign it to an empty list ? > > thanks, > Stef Mientki It will be gc'd when you leave the scope or you can call del() to explicitly get rid of the object if its existence bothers you. James From gonzlobo at gmail.com Fri Jan 19 17:53:47 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Fri, 19 Jan 2007 15:53:47 -0700 Subject: How to comment code? In-Reply-To: <45b13876$0$323$e4fe514c@news.xs4all.nl> References: <45b13876$0$323$e4fe514c@news.xs4all.nl> Message-ID: If it's hard to write, it should be hard to read! :) On 1/19/07, Martin P. Hellwig wrote: > Hi all, (snip) > However since I'm learning more of python I've struggled with > commenting, how should I've comment my code (snip) From steven.bethard at gmail.com Sun Jan 7 23:24:23 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 07 Jan 2007 21:24:23 -0700 Subject: how to find the longst element list of lists In-Reply-To: <45a1b4da$1@nntp0.pdx.net> References: <45a1b4da$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Dan Sommers wrote: >> ... >> longest_list, longest_length = list_of_lists[ 0 ], len( >> longest_list ) >> for a_list in list_of_lists[ 1 : ]: >> a_length = len( a_list ) >> if a_length > longest_length: >> longest_list, longest_length = a_list, a_length >> will run faster than sorting the list just to pick off one element (O(n) >> vs. O(n log n) for all of you Big-Oh notation fans out there; you know >> who you are!). > > Or, more succinctly, after: > list_of_lists = [["q", "e", "d"], > ["a", "b"], > ["a", "b", "c", "d"]] > You can find the longest with: > maxlength, maxlist = max((len(lst), lst) for lst in list_of_lists) > or (for those pre-2.5 people): > maxlength, maxlist = max([(len(lst), lst) for lst in list_of_lists]) Generator expressions worked in 2.4 too. If you're using 2.5, you should take advantage of the key= argument to max and skip the generator expression entirely:: >>> list_of_lists = [["q", "e", "d"], ... ["a", "b"], ... ["a", "b", "c", "d"]] >>> maxlist = max(list_of_lists, key=len) >>> maxlist, len(maxlist) (['a', 'b', 'c', 'd'], 4) STeVe From wolfgang.grafen at marconi.com Tue Jan 16 07:17:25 2007 From: wolfgang.grafen at marconi.com (Wolfgang Grafen) Date: Tue, 16 Jan 2007 13:17:25 +0100 Subject: How to convert float to sortable integer in Python In-Reply-To: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> References: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> Message-ID: shellon wrote: > Hi all: > I want to convert the float number to sortable integer, like the > function float2rawInt() in java, but I don't know the internal > expression of float, appreciate your help! > You should know you can sort mixed float/integer values in Python >>> l=[3,2.3,1.45,2,5] >>> l.sort() >>> l [1.45, 2, 2.2999999999999998, 3, 5] to convert a float to int use the built-in int function: >>> int(2.34) 2 Hope this helps regards Wolfgang From garyjefferson123 at yahoo.com Thu Jan 25 00:32:25 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 24 Jan 2007 21:32:25 -0800 Subject: logging module and doctest Message-ID: <1169703145.393435.166020@m58g2000cwm.googlegroups.com> I've written a logging.filter and would like to use doctest on it (using a StreamHandler for stdout), but this doesn't seem possible. Output from the logger seems to disappear (running the doctest strings through the interpreter as-is yields expected results). I assume this is because doctest does something with logging. Is there any way to make these work together? Gary From sebastien.thur at laposte.net Tue Jan 9 03:06:15 2007 From: sebastien.thur at laposte.net (seb) Date: 9 Jan 2007 00:06:15 -0800 Subject: line duplication using logging to file Message-ID: <1168329975.491514.282000@11g2000cwr.googlegroups.com> Hi, I am writing to a file some basic information using the logging module. It is working but in the log file some line are printed several time. I had put some print debugging messages in the logging function (so they appear on the consile) and they are called once only. Obviously there is some understantding of the logging module that I am missing. My simple logging program (see below) is called by several processes. In this way I can collect the information from various sources (and not use the network enabled logging module) I am using python 2.4 on WinXP SP2. Do you have any idea ? Thanks in advance. Seb. ***************************************** The very simple "logging program ": ***************************************** import logging, logging.handlers import time def write_log(level, message): # Utilisation de l'API pour le Handler global print "time.asctime()",time.asctime(),"received level=",level,"message =",message nom_logger="main_log_file" logger=logging.getLogger(nom_logger) logger.setLevel(logging.DEBUG) prefix = "pix_main_log_file" #fh=logging.handlers.RotatingFileHandler(prefix + "_log.txt", 'a', 1000000,10) fh=logging.FileHandler("main_log.txt") fh.setLevel(logging.DEBUG) #formater = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") formater = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") fh.setFormatter(formater) logger.addHandler(fh) #logger.info("***************************** debut") #message = main(url,conf_file,logger) #message="hello seb" if str(level).lower() == "info" : print "logger info" logger.info(str(message)) elif str(level).lower() =="error": print "logger error" logger.error(str(message)) elif str(level).lower()=="warning" : print "logger warning" logger.warning(str(message)) elif str(level).lower() =="critical": print "logger critical" logger.critical(str(message)) elif str(level).lower() == "exception": print "logger exception" logger.exception(str(message)) else : logger.info("niveau inconnu "+str(message)) print "_________",message #print dir(logger) return ************************************************* Example of the log file with duplicated line. ************************************************** 2007-01-08 18:26:19,578 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___init_rs232initrs232_openCOM1 2007-01-08 18:26:19,578 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run____thread lance 2007-01-08 18:26:19,578 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run____thread lance 2007-01-08 18:26:32,015 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:32,015 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:32,015 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:42,483 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:42,483 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:42,483 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:42,483 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:53,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:53,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:53,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:53,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:26:53,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:03,092 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:03,092 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:03,092 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:03,092 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:03,092 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:03,092 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:13,671 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:13,671 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:13,671 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:13,671 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:13,671 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:13,671 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:13,671 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,796 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-08 18:27:14,890 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:51:26,562 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___init_rs232initrs232_openCOM1 2007-01-09 08:51:26,733 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run____thread lance 2007-01-09 08:51:26,733 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run____thread lance 2007-01-09 08:51:39,453 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:39,453 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:39,453 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:48,280 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:48,280 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:48,280 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:48,280 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:58,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:58,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:58,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:58,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:51:58,750 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:09,812 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:09,812 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:09,812 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:09,812 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:09,812 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:09,812 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:19,078 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:19,078 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:19,078 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:19,078 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:19,078 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:19,078 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:19,078 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\Client_tests.py___test1TEST 1 = OK 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,078 - WARNING - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___run___fin dans le run car continue = 0 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret 2007-01-09 08:52:22,125 - INFO - C:\Documents and Settings\test\Bureau\xmlrpc\version simple\thread_RS232.py___stopthread demande d'arret ************************** Program calling the log : *************************** import appel_log ..... message = "something" nom_function_actuelle= str(sys._getframe().f_code.co_filename) +"___"+str(sys._getframe().f_code.co_name) appel_log.write_log("info",nom_function_actuelle+message) ................ From Andreas.Ames at comergo.com Thu Jan 11 03:40:09 2007 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Thu, 11 Jan 2007 09:40:09 +0100 Subject: dynamic library loading, missing symbols Message-ID: <552B6B925278EF478EA8887D7F9E5AC301C8C5FD@tndefr-ws00024.tenovis.corp.lan> > -----Original Message----- > From: python-list-bounces+andreas.ames=comergo.com at python.org > [mailto:python-list-bounces+andreas.ames=comergo.com at python.or > g] On Behalf Of dfj225 at gmail.com > Sent: Wednesday, January 10, 2007 8:52 PM > Subject: Re: dynamic library loading, missing symbols > > I suppose this means that any subsequent libraries dlopened will not > see any of the symbols in my module? Have you already checked the output of LD_DEBUG=all or sth. like that? cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 711 13586 7789 | ames AT avaya DOT com From david at boddie.org.uk Wed Jan 31 13:51:56 2007 From: david at boddie.org.uk (David Boddie) Date: 31 Jan 2007 10:51:56 -0800 Subject: DCOP memory leak? In-Reply-To: <1170265582.892012.69290@v45g2000cwv.googlegroups.com> References: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> <1170265582.892012.69290@v45g2000cwv.googlegroups.com> Message-ID: <1170269516.158040.38450@s48g2000cws.googlegroups.com> On Jan 31, 6:46 pm, "TimD... at gmail.com" wrote: > The code I posted is not my actual program and was only to demonstrate > my problem. The complete program I'm writing uses QT and so the loop > is replaced by a Timer event. > I tried out the suggestion. I had already tried the del dcop > instruction, so I knew that wasn't it. I also placed the DCOP variable > outside my loop but that didn't help either. You might get a precise answer to your question if you send a message to the PyQt/PyKDE mailing list: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde The original authors and contributors of various Python DCOP modules read that list, so there's a chance they can either solve your problem or offer some advice on how to work around it. > What I did notice that my program only grew in memory use when the > 'ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() ' code was > executed (or any other function using the AmarokDcopRes variable like > 'ok, volume = AmarokDcopRes.player.getVolume()' ) Do you find the same problem with other DCOP interfaces? David From sigzero at gmail.com Wed Jan 17 13:54:54 2007 From: sigzero at gmail.com (Robert Hicks) Date: 17 Jan 2007 10:54:54 -0800 Subject: *POLL* How many sheeple believe in the 911 fairy tale and willingto accept an Orwellian doublespeak and enslavement world ? In-Reply-To: References: Message-ID: <1169060094.242970.268770@51g2000cwl.googlegroups.com> > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning cathedrals. > > -Quarry worker's creed Sure, but did you actually post your phone number on USENET? Robert From laurent.pointal at limsi.fr Wed Jan 10 04:20:55 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 10 Jan 2007 10:20:55 +0100 Subject: Establishing if an Object is Defined In-Reply-To: <1168420616.285450.306460@k58g2000hse.googlegroups.com> References: <1168420616.285450.306460@k58g2000hse.googlegroups.com> Message-ID: bg_ie at yahoo.com a ?crit : > Hi, > > The following code works - > > one = 1 > if one == 1: > ok = 1 > print ok > > but this does not, without exception - > > one = 2 > if one == 1: > ok = 1 > print ok > > How do I establish before printing ok if it actually exists so as to > avoid this exception? ok = 0 ...do the job... Very simple, failure-proof, no special case. From anthonydevine69 at hotmail.com Fri Jan 12 12:40:15 2007 From: anthonydevine69 at hotmail.com (tonydevlin) Date: Fri, 12 Jan 2007 09:40:15 -0800 (PST) Subject: ArchGenXML please help In-Reply-To: <45a7bc70$0$299$426a34cc@news.free.fr> References: <8301441.post@talk.nabble.com> <45a7bc70$0$299$426a34cc@news.free.fr> Message-ID: <8302734.post@talk.nabble.com> Bruno Desthuilliers wrote: > > tonydevlin a ?crit : >> I am creating a workflow in plone using argouml and archgenxml. I have >> been >> following the steps on the site:- >> http://plone.org/documentation/tutorial/anonymously-adding-custom-content-types-with-argouml-and-archgenxml/creating-a-class-and-workflow-with-argouml >> >> However I am confused at step 9 in creating the class section, where it >> says: >> "Now, save this file as "ProcessImprovement.zargo". Pull up a command >> prompt and navigate to that directory. Make sure that you've added the >> ArchGenXML directory to your env path, and type the following: >> C:\Sandbox\Plone\Tutorial>ArchGenXML.py ProcessImprovement.zargo" >> >> I have saved the file in the location >> C:\Documents and Settings\Tony\Desktop\Test\ProcessImprovement.zargo >> However I dont know what to type in the python command prompt!!! > > Which *python* command prompt ? The author is talking about a shell, > here (you know, this strange stuff that looks like good ole time DOS...). > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > I yes sorry I was obviously not thinking properly, however there is still > a problem, when I run this in dos after I have changed to the correct > directory the ArchGenXML file that I downloaded does not work. I renamed > it from its original name because that did not work, it just came up with > can not find program for it to run off. It still does the same. > > -- View this message in context: http://www.nabble.com/ArchGenXML-please-help-tf2966867.html#a8302734 Sent from the Python - python-list mailing list archive at Nabble.com. From gonzlobo at gmail.com Thu Jan 18 10:42:54 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Thu, 18 Jan 2007 08:42:54 -0700 Subject: variable scope Message-ID: Greetings, I've been using Python to successfully parse files. When the entire program was smaller, the variable firstMsg worked fine, but now doesn't because it's used in function PID_MinMax. I know it's a result of variables and their scope. I declare the variable 'firstMsg = 0' in the main loop, pass it to the function 'PID_MinMax(firstMsg, PID)'. When the function increments the variable, it doesn't pass it back to the main program. What am I doing wrong? ---- major snippage) --- firstMsg = 0 skipHeader = 13 pPIDs = ['0321'] # hundreds more pLen = len(pPIDs) pMsgNum = pLen * [0] pMax = pLen * [0] pMin = pLen * [10] pLast = pLen * [0] def PID_MinMax(firstMsg, PID): idx = pPIDs.index(PID) pMsgNum[idx] += 1 # Need to have 2 samples to determine Delta if firstMsg != 0: tDelta = tCurrent - pLast[idx] if tDelta > pMax[idx]: pMax[idx] = tDelta if tDelta < pMin[idx]: pMin[idx] = tDelta elif firstMsg == 0: firstMsg = 1 pLast[idx] = tCurrent print pMin, pMax return firstMsg ############## main ############## bf_file = file('bf_data/sByteflightLog_wISS.txt', 'r') for line in bf_file: # skip header if skipHeader != 0: skipHeader -= 1 # skip footer elif line == '\n': break else: raw_msg = line.split() tCurrent = int(raw_msg[0], 16) * 0.0001 PID = raw_msg[2] if PID in pPIDs: PID_MinMax(firstMsg, PID) From gagsl-py at yahoo.com.ar Mon Jan 8 21:03:45 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 23:03:45 -0300 Subject: Adding functions to classes after definition In-Reply-To: <45A2E61F.2080100@andrew.cmu.edu> References: <45A2E61F.2080100@andrew.cmu.edu> Message-ID: <7.0.1.0.0.20070108224821.03ba5830@yahoo.com.ar> At Monday 8/1/2007 21:47, Gerard Brunick wrote: >Consider: A) > >>> class C(object): >... pass >... > >>> def f(*args): >... print args >... > >>> C.f = f > >>> C.f > > >>> c=C() > >>> c.f() >(<__main__.C object at 0x04A51170>,) > >And B) > > >>> del c > >>> C.f = types.MethodType(f, None, C) > >>> C.f > > >>> c = C() > >>> c.f() >(<__main__.C object at 0x04A51290>,) > >I don't understand A). It is my vague understanding, that methods are >really properties that handle binding on attribute access, so B) should >be the "right" way to add a method to a class after definition. This is implemented using descriptors. A function object has a __get__ method: py> f.__get__ py> C.__dict__['f'] is f True py> C.f is f False py> C.f.im_func is f True So, when you assign C.f=f, nothing special happens; but when the function is retrieved from the class, the __get__ method is invoked, returning an "unbound method". > Why does >A show up as a method? Shouldn't it still just be a function? Certainly >when you define a class, there is some magic in the __new__ method that >turns functions in the initial dictionary into methods, but does this still >happen for all setattr after that? There's nothing special in __new__ (relating to this, at least). Nor even when setting the attribute; the magic happens when you *get* the method as an attribute of the class object. Functions don't even have a __set__: py> f.__set__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'function' object has no attribute '__set__' >Is is possible to set a class attribute >equal to a regular (types.FunctionType) function? Yes, that's what actually happens. It's not easy to *retrieve* it later without getting a MethodType. >Any references that discuss these issues would be greatly appreciated. Descriptors are documented somewhere... I think they came in Python 2.2 along with new-style classes. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From http Sun Jan 7 22:30:05 2007 From: http (Paul Rubin) Date: 07 Jan 2007 19:30:05 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: <7xlkke19he.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > If you want to write bug-free code, pessimism is the name of the game. > > I wonder whether Paul uses snow chains all year round, even in the blazing > summer? After all, "if you want to drive safely, pessimism is the name of > the game". No. I'm willing to accept a 10**-5 chance of hitting a freak snowstorm in summer, since I drive in summer at most a few hundred times a year, so it will take me 100's of years before I'm likely to encounter such a storm. There are millions of drivers, so if they all take a similar chance, then a few times a year we'll see in the paper that someone got caught in a storm, which is ok. Usually there's no real consequence beyond some inconvenience of waiting for a tow truck. Tow truck or ambulance operators, on the other hand, should keep chains available all year around, since they have to service the needs of millions of users, have to be ready for freak summer storms. As a software developer wanting to deploy code on a wide scale, I'm more like a tow truck operator than an individual car driver. Alternatively, as a coder I "drive" a lot more often. If some Python misfeature introduces a bug with probability 10**-5 per line of code, then a 100 KLoc program is likely to have such a bug somewhere. It doesn't take 100's of years. From anthra.norell at vtxmail.ch Mon Jan 15 15:07:07 2007 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 15 Jan 2007 21:07:07 +0100 Subject: Type casting a base class to a derived one? In-Reply-To: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> References: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> Message-ID: <45ABDEEB.5020509@vtxmail.ch> Chris Mellon wrote: > On 11 Jan 2007 15:01:48 +0100, Neil Cerutti wrote: > >> On 2007-01-11, Frederic Rentsch wrote: >> >>> If I derive a class from another one because I need a few extra >>> features, is there a way to promote the base class to the >>> derived one without having to make copies of all attributes? >>> >>> class Derived (Base): >>> def __init__ (self, base_object): >>> # ( copy all attributes ) >>> ... >>> >>> This looks expensive. Moreover __init__ () may not be available >>> if it needs to to something else. >>> >>> Thanks for suggestions >>> >> How does it make sense to cast a base to a derived in your >> application? >> >> > > I can't figure out any circumstance when you'd need to do this in > Python. Upcasting like this is something you do in statically typed > languages. I suspect that the OP doesn't really believe dynamic > casting works and doesn't want to pass a derived class for some > reason. > What for? If an instance needs to collect a substantial amount of data and needs to perform a substantial amount of processing in order to analyze that data, and if the appropriate type of the instance depends on the analysis, I thought that the instance might at that point just kind of slip into the appropriate identity. After studying the various helpful suggestions, some of which, like this one, question the wisdom of such an approach, I think I see the light: I'd have a class that does the collecting and the analyzing, or even two classes: one collecting the other analyzing and then, depending on the outcome of the analysis, make the appropriate processor and hand it the data it needs. Right? Thank you all very much for your input. Frederic (OP) From http Sun Jan 7 07:09:13 2007 From: http (Paul Rubin) Date: 07 Jan 2007 04:09:13 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> Message-ID: <7xmz4v11jq.fsf@ruckus.brouhaha.com> "Felipe Almeida Lessa" writes: > What is the chance of having to inherit from two classes from > different modules but with exactly the same name *and* the same > instance variable name? > > Of course you're being very pessimistic or extremely unlucky. If you want to write bug-free code, pessimism is the name of the game. From frank at niessink.com Mon Jan 29 14:14:21 2007 From: frank at niessink.com (Frank Niessink) Date: Mon, 29 Jan 2007 20:14:21 +0100 Subject: wxPython StatusBar Help In-Reply-To: <45bdfdc3$0$6722$426a74cc@news.free.fr> References: <45bdfdc3$0$6722$426a74cc@news.free.fr> Message-ID: <67dd1f930701291114y1a8bcb75t56579e76a7295205@mail.gmail.com> 2007/1/29, herve : > > > Does anybody know how to change the foreground colors in a wx.StatusBar wx.StatusBar is a subclass of wx.Window so SetForegroundColour should work... Cheers, Frank PS: In general, wxPython related questions are best asked on the wxPython-users mailinglist (see http://www.wxpython.org/maillist.php). -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Mon Jan 8 17:30:13 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 09 Jan 2007 09:30:13 +1100 Subject: how to find the longst element list of lists References: Message-ID: On Mon, 08 Jan 2007 13:55:40 +0100, Peter Otten wrote: >> The precise results depend on the version of Python you're running, the >> amount of memory you have, other processes running, and the details of >> what's in the list you are trying to sort. But as my test shows, sort has >> some overhead that makes it a trivial amount slower for sufficiently small >> lists, but for everything else you're highly unlikely to beat it. > > Try again with tN.timeit(1) and a second list that is random.shuffle()d and > copied to L before each measurement. list.sort() treats already sorted > lists specially. Or, simply shuffle the list itself. Why copy it? In my tests, sorting still wins, and by roughly the same factor. One optimization that might shift the balance would be to remove the list copying in the non-sort code (list_of_lists[1:]). That's going to be very time consuming for big lists. -- Steven. From collinstocks at gmail.com Thu Jan 11 21:41:55 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Thu, 11 Jan 2007 21:41:55 -0500 Subject: os.popen() not executing command on windows xp In-Reply-To: <7.0.1.0.0.20070111210043.01ce28c8@yahoo.com.ar> References: <1168508553.151827.261420@k58g2000hse.googlegroups.com> <1168509560.119819.78470@o58g2000hsb.googlegroups.com> <1168535370.211599.265250@p59g2000hsd.googlegroups.com> <7.0.1.0.0.20070111210043.01ce28c8@yahoo.com.ar> Message-ID: <4c0048df0701111841r1552ef46oad4e291b8d6969ae@mail.gmail.com> I have no clue what is wrong. If all else fails, use os.system() instead of os.popen(). Pipes tend not to always work in windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Mon Jan 22 16:37:59 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 22 Jan 2007 22:37:59 +0100 Subject: mmap caching In-Reply-To: <45B51C1B.2000705@designaproduct.biz> References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <45B3DD4D.3010009@v.loewis.de> <1169422167.683707.264180@a75g2000cwd.googlegroups.com> <45B3FDA7.9030702@v.loewis.de> <45B51C1B.2000705@designaproduct.biz> Message-ID: <45B52EB7.5030608@v.loewis.de> Laszlo Nagy schrieb: > >> In fact, memory that is read in because of mmap should *never* cause >> a MemoryError. > This is certainly not true. You can run out of virtual address space by > reading data from a memory mapped file. That is true, but not what I said. I said you cannot run out of memory *while reading it*. You can only run out of virtual address space when you invoke mmap.mmap itself (and when the application later tries to allocate more virtual address space through VirtualAlloc). >> Python calls MapViewOfFile when mmap.mmap is invoked, >> at which point the operating commits to providing that much address >> space to the application, along with backing storage on disk >> (typically, from the file being mapped, unless it is an anonymous >> map). Later access to the mapped range cannot fail (except for >> hardware errors), and if it would, you wouldn't see a MemoryError. >> > Hmm, maybe I'm wrong. Are you sure that Windows allocates the size of > the whole file in terms of memory address space? Yes, I am. See MapViewOfFile, at http://msdn2.microsoft.com/en-us/library/aa366761.aspx "Mapping a file makes the specified portion of a file visible in the address space of the calling process." Notice allocating address space doesn't consume much memory (it consumes a little memory for the page tables). > I also wrote a program > before (in Delphi). That program was playing a memory mapped wave file. > From the task manager, I have seen that "used memory" was growing as the > program was playing the wave file. For me, this indicates that Windows > extends the mapped address space in chunks. You are misinterpreting the data. I'm not sure what precisely "used memory" is, most likely it is the working set of the process, i.e. the amount the number of physical pages that are allocated for the process. That is typically much smaller than the address space, since many pages will be paged out (or not yet read in at all). You need to display the virtual address space in the task manager to determine how much address space the application is using. Regards, Martin From skip at pobox.com Wed Jan 31 16:49:13 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 31 Jan 2007 15:49:13 -0600 Subject: SyntaxError: 'return' outside function In-Reply-To: <1170278702.599741.212420@l53g2000cwa.googlegroups.com> References: <1170278702.599741.212420@l53g2000cwa.googlegroups.com> Message-ID: <17857.3801.331748.605998@montanaro.dyndns.org> Melih> Has anyone seen this error before and been able to solve it? I Melih> can't seem to find anything that leads to a solution. Your code is incorrectly indented. Try: def legiturl(self, url): # this breaks down the url into 6 components to make sure it's "legit" t = urlparse.urlparse(url) if t[0] != 'http': return "" # remove URL fragments, but not URL if len(t[5]) > 0: url = urlparse.urlunparse((t[0],t[1],t[2],"","","")) t = urlparse.urlparse(url) # stupid parser sometimes leaves frag in path x = find(t[2], '#') if x >= 0: return "" instead. Note also the lack of a return at the end of the function. Skip From steve at REMOVE.THIS.cybersource.com.au Sat Jan 6 02:59:31 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 06 Jan 2007 18:59:31 +1100 Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> Message-ID: On Fri, 05 Jan 2007 07:19:37 -0800, king kikapu wrote: > > >> > Are they embarassed by their code? > > hehehe...no, just worried about stealing their ideas... I don't understand... how can they steal an idea? If somebody copies your idea, you've still got it, it's not gone. -- Steven. From tinaweb at bestemselv.com Wed Jan 17 00:48:52 2007 From: tinaweb at bestemselv.com (Tina I) Date: Wed, 17 Jan 2007 06:48:52 +0100 Subject: PyQt: QListviewItemIterator In-Reply-To: <54a5f$45ad62a8$54d1d767$17614@news.chello.no> References: <54a5f$45ad62a8$54d1d767$17614@news.chello.no> Message-ID: David Boddie wrote: > > When it.current() returns None. You can rewrite what you already > have like this: > > it = QListViewItemIterator(self.authListView) > while it.current(): > item = it.current() > if item.text(0).contains(filterString) or \ > item.text(1).contains(filterString) or \ > item.text(2).contains(filterString): > > item.setVisible(1) > else: > item.setVisible(0) > it += 1 > > If you don't like calling item.current() twice for some reason, > you could write this: > > it = QListViewItemIterator(self.authListView) > item = it.current() > while item: > if item.text(0).contains(filterString) or \ > item.text(1).contains(filterString) or \ > item.text(2).contains(filterString): > > item.setVisible(1) > else: > item.setVisible(0) > it += 1 > item = it.current() > > David Ah, of course! Thanks!! Tina From sjmachin at lexicon.net Mon Jan 1 20:20:10 2007 From: sjmachin at lexicon.net (John Machin) Date: 1 Jan 2007 17:20:10 -0800 Subject: Writing more efficient code References: Message-ID: <1167700810.404307.148620@k21g2000cwa.googlegroups.com> gonzlobo wrote: > Greetings, and happyNewYear to all. > > I picked up Python a few weeks ago, and have been able to parse large > files and process data pretty easily, but I believe my code isn't too > efficient. I'm hoping dictionaries will help out, but I'm not sure the > best way to implement them. > > I've been using a bunch of nested if/elif/else statements to select > slices (0317 & 03de) from a file, then parse the data (aa, hh, bb, > d2-d9) into parameters (a = airspeed, h = heading) & flags. > > #sample file contents > 0000007d 03 0317 aa aa aa aa aa hh hh hh bb bb > 0000007e 06 03de d2 d3 d4 d5 d6 d7 d8 d9 10 11 Do you have the original file from which this hex dump was made? It may be a lot easier to write the code to pick that apart using the struct module's unpack function than fiddling with the hex dump. It would probably run faster as well. > > # some pseudo code > if PID == '03de': > flapsCmd = int(d3, 16) > if flapsCmd == 0xc0: > > elif flapsCmd == 0x03: > > if PID == '0317': > airspeed == 'combine aa for airspeed & multiply by 0.1' *five* bytes for airspeed? Are they ascii characters e.g. "01234" meaning 123.4? > heading == 'combine hh for heading' > mach == 'combine bb for mach & multiply by 0.01' > > Might dictionaries help in this case... say Label0317(parameterName, > slice (d3), scaleFactor(0.1))... I'd like to use them if they'll > replace the dozens of nested conditionals. I have roughly 75 > different parameters to decode from a file containing ~2.5 million > lines of data. > > I know my pseudo code lacks details, but hopefully I'm getting my > point across... It would help if you gave some more precise info on what format the individual fields can take. Cheers, John From tidegenerator at tom.com Tue Jan 30 03:50:29 2007 From: tidegenerator at tom.com (tidegenerator at tom.com) Date: 30 Jan 2007 00:50:29 -0800 Subject: How can I know both the Key c and Ctrl on the keyboard are pressed? Message-ID: <1170147029.261981.322740@a75g2000cwd.googlegroups.com> Hi; How can I know the Key c and Ctrl on the keyboard are pressed? Or how to let the program press the key Ctrl+c automatically? I just want to use python to develop a script program. gear From samuel.y.l.cheung at gmail.com Mon Jan 22 18:32:58 2007 From: samuel.y.l.cheung at gmail.com (samuel.y.l.cheung at gmail.com) Date: 22 Jan 2007 15:32:58 -0800 Subject: How to use time.clock() function in python In-Reply-To: References: <1169503516.425217.218790@q2g2000cwa.googlegroups.com> Message-ID: <1169508778.101027.320760@11g2000cwr.googlegroups.com> Thanks. I have a fuction called 'func1'. def func1: # logic of the function When my script just call 'func1()' it works. func1() But when put it under timerit.Timer, like this: t = timeit.Timer("func1()","") t.repeat(1, 10) # want to time how long it takes to run 'func1' 10 times, I get an error like this: File "/usr/lib/python2.4/timeit.py", line 188, in repeat t = self.timeit(number) File "/usr/lib/python2.4/timeit.py", line 161, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner NameError: global name 'func1' is not defined I don't understand why i can't find 'func1', when I call the function 'func1' directly, it works. but why when I call it within 'timeit', it can't find it? Thank you. Gabriel Genellina wrote: > At Monday 22/1/2007 19:05, yinglcs at gmail.com wrote: > > >I am following this python example trying to time how long does an > >operation takes, like this: > > > >My question is why the content of the file (dataFile) is just '0.0'? > >I have tried "print >>dataFile, timeTaken" or "print >>dataFile,str( > >timeTaken)", but gives me 0.0. > >Please tell me what am I missing? > > > > > > t1 = time.clock() > > os.system(cmd) > > > > outputFile = str(i) + ".png" > > > > t2 = time.clock() > > > > timeTaken = t2 - t1 > > allTimeTaken += timeTaken > > print >>dataFile, timeTaken > > time.clock() may not give you enough precision; see this recent post > http://mail.python.org/pipermail/python-list/2007-January/422676.html > Use the timeit module instead. > > > -- > Gabriel Genellina > Softlab SRL > > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas From wasadmin at optonline.net Tue Jan 30 20:49:43 2007 From: wasadmin at optonline.net (Tequila) Date: 30 Jan 2007 17:49:43 -0800 Subject: PythonCard In-Reply-To: References: <1170193549.583822.156450@k78g2000cwa.googlegroups.com> Message-ID: <1170208183.438605.151800@j27g2000cwj.googlegroups.com> On Jan 30, 6:26 pm, s... at pobox.com wrote: > Tequila> I'm having some trouble starting PythonCard on my PC. I've > Tequila> downloaded and ran python-2.5.msi to install Python on my > Tequila> machine. And PythonCard-0.8.2.win32.exe to install PythonCard. > ... > Tequila> import wx > Tequila> ImportError: No module named wx > > Tequila> Does anyone know what the problem might be? > > Sorta looks like you need to install wxPython. In fact, the Windows > instructions for PythonCard mention downloading wxPython before downloading > PythonCard itself: > > http://pythoncard.sourceforge.net/windows_installation.html > > If you're confident wxPython *is* installed, check to make sure it's > installed somewhere that Python will find it. > > Skip Yeah, ummm... ok so, I overlooked the Windows install instructions (thanks for the tip Gabriel :-) Once I installed wxPython all is good. Thanks for everything all!! Teq From robert.kern at gmail.com Thu Jan 4 22:46:12 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Jan 2007 21:46:12 -0600 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> Message-ID: jeremito wrote: > I am writing a class that is intended to be subclassed. What is the > proper way to indicate that a sub class must override a method? raise NotImplementedError -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Bob.Sidebotham at gmail.com Fri Jan 12 10:10:06 2007 From: Bob.Sidebotham at gmail.com (Bob.Sidebotham at gmail.com) Date: 12 Jan 2007 07:10:06 -0800 Subject: context managers and generators References: <1168611420.448058.163860@11g2000cwr.googlegroups.com> Message-ID: <1168614604.273032.173650@51g2000cwl.googlegroups.com> Jean-Paul Calderone wrote: > On 12 Jan 2007 06:17:01 -0800, bob.sidebotham at gmail.com wrote: > >I'm happily using context managers and co-routines, and would like to > >use both at the same time, e.g. > > Python has generators, not co-routines. They may be called generators, but I'm using them as co-routines. > Wrap the generator in a function which co-operates with your context > managers to clean-up or re-instate whatever they are interacting with > whenever execution leaves or re-enters the generator. I don't think wrapping the generator will do it. I think I would have to wrap the actual yield call. Maybe that wouldn't be so bad. There's not even any guarantee, by the way, that the yield even returns: an exception outside the generator will not trigger the exception in the context manager. In general, there is no hook (that I can see) that helps with this. I'm still thinking there is a better way to do it, and would appreciate any ideas. Bob From van.lindberg at gmail.com Thu Jan 11 17:24:34 2007 From: van.lindberg at gmail.com (VanL) Date: Thu, 11 Jan 2007 16:24:34 -0600 Subject: Intellectual Property Talk at PyCon Message-ID: I will be presenting a talk at PyCon, "The Absolute Minimum an Open Source Developer Needs to Know About Intellectual Property." I want to tailor this talk so that it is interesting to as many attendees as possible. I am familiar with a lot of the internal divisions in the Free Software/Open Source community. My intent is not to advocate for or against any specific position, but rather to promote a common understanding and address specific situations that developers may encounter. In other words, a problem/solution approach, instead of an argumentative approach. With that in mind, I had in mind the following subjects: - A brief primer on intellectual property (what are patents, trademarks, copyrights, and trade secrets?) - What to do when you have an idea you want to develop, but you are working for somebody else - What it means to incorporate GPL'd modules into your own code - Ways to protect ideas that you have put into a proprietary software product - Ways to avoid, work around, or mitigate the effect of software patents - Licensing, using, and distributing software (comparing and contrasting the GPL, BSD, and Python licenses) I am interested in hearing about 1) other topics of interest, and 2) the relative level of interest in each topic. To keep within the time limits for my talk, I intend to address the most popular topics in roughly the order of their popularity. Thanks, Van Lindberg From aahz at pythoncraft.com Thu Jan 25 10:26:13 2007 From: aahz at pythoncraft.com (Aahz) Date: 25 Jan 2007 07:26:13 -0800 Subject: My Tkinter Threading nightmare References: <1169693266.209082.323310@a75g2000cwd.googlegroups.com> <7xac07wzh2.fsf@ruckus.brouhaha.com> <1169726320.703566.272120@k78g2000cwa.googlegroups.com> <7xejpjuvwe.fsf@ruckus.brouhaha.com> Message-ID: In article <7xejpjuvwe.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > > self.progressWindow.protocol('WM_DELETE_WINDOW', self.callback) > >becomes > > gui.cmd_queue.put(self.progressWindow.protocol, > ('WM_DELETE_WINDOW', self.callback)) > >where gui is the Window object containing your gui. > >I think there are some recipes like this in ASPN, that give more >detail about how to do this stuff. You can find a simple example at http://pythoncraft.com/ in the threads tutorial. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From arkanes at gmail.com Mon Jan 8 21:17:30 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 8 Jan 2007 20:17:30 -0600 Subject: Fwd: Execute binary code In-Reply-To: <7.0.1.0.0.20070108194009.03993008@yahoo.com.ar> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168289145.319706.199950@11g2000cwr.googlegroups.com> <4866bea60701081251we2bf7f3vb55a285ee20e91f6@mail.gmail.com> <1168290090.137259.324360@i15g2000cwa.googlegroups.com> <7.0.1.0.0.20070108194009.03993008@yahoo.com.ar> Message-ID: <4866bea60701081817l7a7ccaa2nabdaff12e4d2c4a4@mail.gmail.com> On 1/8/07, Gabriel Genellina wrote: > At Monday 8/1/2007 18:01, citronelu at yahoo.com wrote: > > >Chris Mellon wrote: > > > Writing to a temp file will be at least 3 times as easy and twice as > > > reliable as any other method you come up with. > > > >I'm not disputing that, but I want to keep a piece of code (a parser > >for Oracle binary dumps, that I didn't wrote) out of foreign hands, as > >much as possible. Using a TEMP directory is not "stealth" enough. > > This is what I would do (untested of course!) (Mostly using the > Win32 API so you'll have to use pywin32 or ctypes). > > Call CreateFile with dwShareMode=0, FILE_ATTRIBUTE_TEMPORARY, > FILE_FLAG_NO_BUFFERING, FILE_FLAG_DELETE_ON_CLOSE. > That means that no other process could open the file, if it fits in > available memory probably it won't even be written to disk, and it > will be deleted as soon as it has no more open handles. File name > does not have to end in .exe. > Copy the desired contents into a buffer obtained from VirtualAlloc; > then call WriteFile; release the buffer (rounding size up to next 4KB multiple) > Then CreateProcess with CREATE_SUSPENDED, and CloseHandle on the > file, and CloseHandle on the two handles returned on > PROCESS_INFORMATION. At this stage, the only open handle to the > temporary file is held by the section object inside the process. > Then ResumeThread(hTread) -process begins running- and > WaitForSingleObject(hProcess) -wait until finishes-. > As soon as it finishes execution, the last handle to the file is > closed and it is deleted. > > Another approach would be to go below the Windows API and use the > native API function NtCreateProcess -officially undocumented- which > receives a section handle (which does not have to be disk based). But > this interfase is undocumented and known to change between Windows versions... > > Or search for a rootkit... > > > -- > Gabriel Genellina > Softlab SRL > Thats a lot of work to execute a binary image that can be trivially recovered from the python source with 2 minutes of work (up to 15 if you have to install Python and google for how to write to a file first). From michael at mustun.ch Wed Jan 3 10:18:04 2007 From: michael at mustun.ch (mm) Date: Wed, 03 Jan 2007 16:18:04 +0100 Subject: array of class / code optimization In-Reply-To: References: Message-ID: Yes, it was the (), equivalent to thiks like new() create new object from class xy. > s1.append(Word) s1.append(Word()) But I was looking for a "struct" equivalent like in c/c++. And/or "union". I can't find it. Maybe you know a source (URL) "Python for c/c++ programmers" or things like that. Yes, I konw whats an object is... From ziade.tarek at gmail.com Sat Jan 6 12:25:18 2007 From: ziade.tarek at gmail.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Sat, 6 Jan 2007 18:25:18 +0100 Subject: python, zlib, and fedora 64bits In-Reply-To: <94bdd2610701060924s1a00ccc9r222e90e892665a05@mail.gmail.com> References: <94bdd2610701060147i6725e52bgdcc3d81377366ecd@mail.gmail.com> <200701060402.25665.jonc@icicled.net> <94bdd2610701060222u3448213eyd9a66e167ed6eb92@mail.gmail.com> <94bdd2610701060924s1a00ccc9r222e90e892665a05@mail.gmail.com> Message-ID: <94bdd2610701060925r34ea5a3bmb8d30ed8b160a485@mail.gmail.com> On 1/6/07, Tarek Ziad? wrote: > > I am answering to myself, if it can help someone else. > > zlib has to be recompiled with CFLAGS set to -fPIC. > > So before launching ./configure do a: > > export CFLAGS="-fPIC" > > Python then will build properly zlib.so > > > Tarek -- Tarek Ziad? | Association AfPy | www.afpy.org Blog FR | http://programmation-python.org Blog EN | http://tarekziade.wordpress.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From dilbert01 at gmail.com Thu Jan 18 07:29:41 2007 From: dilbert01 at gmail.com (alessandro) Date: 18 Jan 2007 04:29:41 -0800 Subject: closing a "forever" Server Socket Message-ID: <1169123381.930403.24170@38g2000cwa.googlegroups.com> Hi all, This is my framework for create TCP server listening forever on a port and supporting threads: import SocketServer port = 2222 ip = "192.168.0.4" server_address = (ip, port) class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass class Handler(SocketServer.BaseRequestHandler): def handle(self): # my handler print "Listening for events at " + ip + ":" + str(port) monitor_server = ThreadingTCPServer(server_address, Handler) try: monitor_server.serve_forever() except KeyboardInterrupt: monitor_server.socket.close() print "Bye." This server will not run as a daemon and for quitting you have to send the SIGINT signal with Ctrl-C. It will rise the KeyboardInterrupt exception, during its handling I simply close the socket and print a message. I want to ask if someone knows a better way for closing a "forever server" or if there is a lack in my design. Thank you! Alessandro From webraviteja at gmail.com Tue Jan 9 01:18:36 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Jan 2007 22:18:36 -0800 Subject: private variables In-Reply-To: References: Message-ID: <1168323516.333488.322310@i15g2000cwa.googlegroups.com> belinda thom wrote: > Hello, > > In what version of python were private variables added? > > Thanks, > > --b Short answer - 1.5 (or - so long ago that it doesn't matter anymore) Long answer - There are no true private variables in Python. Just private variables names by convention. See Python docs for a detailed explanation. Ravi Teja. From rweth at cisco.com Sat Jan 6 15:44:06 2007 From: rweth at cisco.com (rweth) Date: Sat, 06 Jan 2007 12:44:06 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 In-Reply-To: <459f1703$0$24039$9b622d9e@news.freenet.de> References: <459f1703$0$24039$9b622d9e@news.freenet.de> Message-ID: <1168116247.370914@sj-nntpcache-1.cisco.com> Martin v. L?wis wrote: > Carroll, Barry schrieb: >> What I want to know is: >> >> * has anyone else encountered a problem like this, * how was the >> problem corrected, * can the fix be retro-fitted to 2.5 and 2.4? > > From your description, I suspect an error in your code. Your description > indicates that you don't expect to have more than five files open > simultaneously. Yet, the error message "Too many open files" occurs when > you open many more files (in the order of hundreds of files). > > It is very unlikely that there is a bug in Python where it would fail to > close a file when .close() is explicitly invoked on it (as your > description suggests that you do), so if you get that error message, it > can only mean that you fail to close some files. > > Notice that you may have other files open, as well, and that those also > count towards the limit. > > As a debugging utility, you can use Sysinternal's process explorer. > Make the program halt (not exit) when the exception occurs (e.g. by > having it sleep(1) in a loop), then view all open handles in the > process explorer (check the menu if it doesn't display them initially). > > Regards, > Martin I agree with Martin .. this code to close is solid. Make certain you are really closing the files when you think you should. I am pretty sure you are not. Look at the code that closes the files closely. Put a print statement in the block that is supposed to close the files (may bee even a raw_input("closing file" + afile) statement). My guess is that you won't see the print statements trigger when you though they should .. they may be out of "the loop" you thought that they were in. From pydecker at gmail.com Tue Jan 2 12:21:49 2007 From: pydecker at gmail.com (Peter Decker) Date: Tue, 2 Jan 2007 12:21:49 -0500 Subject: DOS, UNIX and tabs In-Reply-To: References: <1167243140.687557.93320@f1g2000cwa.googlegroups.com> Message-ID: On 1/1/07, Tom Plunket wrote: > Maybe I'm also weird, but I use a variable-pitch font when programming > in Python. So a "tab equals some number of spaces" really isn't useful > to me. My setup is, "tab equals this much space". A year ago I would have thought you were weird, but after reading a post by Ed Leafe, one of the creators of Dabo about using proportional fonts for readability, I thought I'd try it out, thinking that it was pretty wacky. Turns out that after a very brief adjustment period, I liked it! I've been using proportional fonts ever since, and have found only one drawback: code that is indented with spaces looks butt-ugly. I'm glad I switched to tabs for my code. -- # p.d. From gagsl-py at yahoo.com.ar Fri Jan 5 04:05:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 06:05:58 -0300 Subject: checking one's type In-Reply-To: References: Message-ID: <7.0.1.0.0.20070105060049.05c1e270@yahoo.com.ar> At Friday 5/1/2007 05:40, belinda thom wrote: >I've been using the following hack to determine if a type is >acceptable and I suspect there is a better way to do it: This has been discussed today under the thread "Set type?", and a few days ago as "type classobj not defined". -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From phd at phd.pp.ru Mon Jan 22 13:20:36 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 22 Jan 2007 21:20:36 +0300 Subject: SQLObject 0.7.3b1 Message-ID: <20070122182036.GC8012@phd.pp.ru> Hello! I'm pleased to announce the 0.7.3b1 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.3b1 News and changes: http://sqlobject.org/docs/News.html What's New ========== Bug Fixes --------- * Allow multiple MSSQL connections. * Psycopg1 requires port to be a string; psycopg2 requires port to be an int. * Fixed a bug in MSSQLConnection caused by column names being unicode. * Fixed a bug in FirebirdConnection caused by column names having trailing spaces. * Fixed a missed import in firebirdconnection.py. * Remove a leading slash in FirebirdConnection. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From bignose+hates-spam at benfinney.id.au Wed Jan 24 19:52:22 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 25 Jan 2007 11:52:22 +1100 Subject: Question about docutils References: <45b7fca1$0$49206$14726298@news.sunsite.dk> Message-ID: <87hcug0vy1.fsf@benfinney.id.au> Damjan writes: > I'm using docutils 0.4. The specific mailing lists for docutils: Also available via GMane, which is how I read them. -- \ "Here is a test to see if your mission on earth is finished. If | `\ you are alive, it isn't." -- Francis Bacon | _o__) | Ben Finney From dudds at netspace.net.au Sat Jan 27 01:56:54 2007 From: dudds at netspace.net.au (dudds) Date: 26 Jan 2007 22:56:54 -0800 Subject: wx Python event question Message-ID: <1169881014.463339.257190@v45g2000cwv.googlegroups.com> Hi I really haven't used wxPython before and I was just wondering if there was some sort of timer event that can be used. For example if I have a database that I want to query at regular intervals and display the results in a window is that possibly to do under a wx Python program? So far I have come across certain event handlers, but they all seem to wait for something to happen, like moving the mouse, clicking on a button etc. I just want to display the results of a query every so often automatically without having to press a button to do so. I'm not looking for a complete solution as I'm doing this so I can teach myself Python, but a bit of a hint or a nudge in the right direction would be great. From nogradi at gmail.com Fri Jan 26 18:59:06 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 27 Jan 2007 00:59:06 +0100 Subject: [ANN] markup.py 1.6 (bugfix: 1.6.1) Message-ID: <5f56302b0701261559n7d12abe3pdb0951133d0c2b7b@mail.gmail.com> > The new 1.6 release of markup.py is available for download: > > http://sourceforge.net/project/showfiles.php?group_id=161108 > > What is it? > > Markup.py is an intuitive, lightweight, easy-to-use, customizable and > pythonic HTML/XML generator. > > Where is the documentation? > > http://markup.sourceforge.net/ > > Why is it called markup.py and not markup? > > This way it's easier to search for it online and also shows that it's > a single module. Also note that the former Markup project of Edgewall > changed its name to Genshi in the meantime. > > Please send comment/feedback/bugs/etc to nogradi at gmail.com Ooooops, a bug was introduced in the latest release, in case you downloaded version 1.6 please get version 1.6.1 which fixes it. Sorry, I probably should do more testing before releasing stuff :) Thanks very much to everyone who gave feedback! From s.mientki at id.umcn.nl Wed Jan 31 06:41:25 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 31 Jan 2007 12:41:25 +0100 Subject: another newbie question: why should you use "*args" ? Message-ID: why should I use *args, as in my ignorance, making use of a list (or tupple) works just as well, and is more flexible in it's calling. So the simple conclusion might be: never use "*args", or am I overlooking something ? # method 1 def execute (self, *args): for i in range ( len(args) ): ... do something # method 2 def chunk_plot(self, list): for i in range ( len(list) ): .... do something # calling method 1: execute (S[0], S[4] ) # calling method 2: execute ( ( S[0], S[4] ) ) # or *the extra flexibility) mylist = ( S[0], S[4] ) execute ( mylist ) thanks, Stef Mientki From hg at nospam.org Mon Jan 15 03:09:53 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 09:09:53 +0100 Subject: check if there is data in stdin without blocking Message-ID: <4PMqh.47441$X97.9536@newsfe18.lga> Hi, Is there a way ? ... select ? hg From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 15:00:04 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 21:00:04 +0100 Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> <50fdf9F1fki7dU3@mid.individual.net> Message-ID: <50fm64F1fotpdU2@mid.individual.net> Nick Maclaren wrote: > Not at all. "Precision" has been used to indicate the number of > digits after the decimal point for at least 60 years, Not only, remember: Computer memories can't think in powers of ten. > probably 100; in 40 years of IT and using dozens of programming > languages, I have never seen "display" used for that purpose. Yes, but since the representation in computers is based on powers of two, a certain precision in the dual system, i. e. a fixed amount of dual places, doesn't correspond with a fixed amount of decimal places. Thus the rounding while displaying -- just to make it look prettier. The very minimal additional error is silently accepted. Regards, Bj?rn -- BOFH excuse #199: the curls in your keyboard cord are losing electricity. From michael at mustun.ch Wed Jan 3 10:50:27 2007 From: michael at mustun.ch (mm) Date: Wed, 03 Jan 2007 16:50:27 +0100 Subject: code optimization (calc PI) In-Reply-To: <5020j6F1du59cU1@mid.uni-berlin.de> References: <5020j6F1du59cU1@mid.uni-berlin.de> Message-ID: Hmm... it's a question. It was not that easy to translate this #@*?%! C-Program into readable code and then to Python. But it works. There are only two while-loops (a while within an other while). I konw, that for example while-loops in Perl are very slow. Maybe this is also known in Pyhton. Then, I can translate the while-loops in to for-loops, for example. More general, maybe there is a speed optimazation docu out there. (Anyway, this code for C-calc is complex. And I realy don't understand it right now... 8-) But anyway, there is not that much calculation, it has more something to do with the too while-loops. Here is some code: (In general, it has basically nothing to do with PI-calc.) c=2800 ## a counter while c*2: ## do some calc. did not change c here. ... b=c ## number of elements while (b-1): ## so some calc. ... b=b-1 ## just for while-loop condition. c = c-14; ## this is code vor the 1st while-loop, BUT bust run after the 2nd-while-loop. pi = pi + str("%04d" % int(e + d/a)) ## this should be fast?! I dont know. There are a output string, a list, and integers. No complex data structures; and no complex calculations. Diez B. Roggisch wrote: > mm wrote: > > >>(Yes, I konw whats an object is...) >>BTW. I did a translation of a pi callculation programm in C to Python. >>(Do it by your own... ;-) > > > Is that a question on how to optimize code you won't show us? If yes, I'm > sorry to tell you that crystal balls are short these days. Too much > new-year-outlooks. > > Diez From bearophileHUGS at lycos.com Mon Jan 1 16:33:49 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Jan 2007 13:33:49 -0800 Subject: Writing more efficient code In-Reply-To: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> References: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1167687229.430930.197720@v33g2000cwv.googlegroups.com> Jon Harrop: > OCaml's pattern matcher is very sophisticated and very fast. You'll probably > shrink your code by several fold whilst also having it run a few orders of > magnitude faster and having it statically checked, so it will be more > reliable. You seem to forget some months of time to learn OCaml. And my Python programs seem reliable enough despite being unstatically checked :-) > You might want to look at any language with pattern matching: OCaml, SML, > Haskell, F#, Mathematica etc. Mathematica pattern matching is good, but Mathematica costs a lot of money (and you need some time to learn it, it's not an easy system). Bye, bearophile From aahz at pythoncraft.com Wed Jan 31 22:12:59 2007 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2007 19:12:59 -0800 Subject: Any python scripts to do parallel downloading? References: Message-ID: In article , Jean-Paul Calderone wrote: > >You misunderstand. I wasn't expressing a lack of confidence in Python >threads, but in the facility with which they can be used by programmers. Based on my admittedly limited experience, I say the same about Twisted. Although I was able to bring up a Twisted 1.1 web server in a hurry under extreme pressure (15 minutes before a PyCon presentation), I have never been able to even get Twisted 2.0 installed. Software is hard. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From steve at REMOVEME.cybersource.com.au Mon Jan 22 19:14:30 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 23 Jan 2007 11:14:30 +1100 Subject: arrow keys don't work References: <1169506381.452422.179070@11g2000cwr.googlegroups.com> Message-ID: On Mon, 22 Jan 2007 14:53:01 -0800, tac-tics wrote: > I've noticed that in Python 2.5, the interactive prompt does not > support intelligent use of arrow keys like 2.4 did (up/down for > previous/next statement, left/right for moving the cursor). It works perfectly for me. > What > exactly is the reason for this and is there an easier fix than > downgradinig to 2.4? Thanks. Have you changed your terminal (either the program itself or its config) so that it is no longer sending the correct codes? When you hit the arrow key, what happens? Do you just get nothing at all, or do you get control characters appearing? e.g. ^Z or similar. -- Steven D'Aprano From horpner at yahoo.com Tue Jan 16 07:51:21 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Jan 2007 13:51:21 +0100 Subject: whats wrong with my reg expression ? References: <7.0.1.0.0.20070115195902.05c75aa0@yahoo.com.ar> Message-ID: On 2007-01-15, Gert Cuykens wrote: > thx > > PS i also cant figure out what is wrong here ? > > rex=re.compile('^"(?P[^"]*)"$',re.M) > for v in l: > v=rex.match(v).group('value') > v=v.replace('""','"') > return(l) > > v=rex.match(v).group('value') > AttributeError: 'NoneType' object has no attribute 'group' When the regex doesn't match, match returns None. -- Neil Cerutti Strangely, in slow motion replay, the ball seemed to hang in the air for even longer. --David Acfield From gagsl-py at yahoo.com.ar Tue Jan 16 12:03:01 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 14:03:01 -0300 Subject: arguments of a function/metaclass References: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> <1168964835.087773.221950@s34g2000cwa.googlegroups.com> Message-ID: "goodwolf" escribi? en el mensaje news:1168964835.087773.221950 at s34g2000cwa.googlegroups.com... > A simply solution: > > def __init__(self, a=1, b=2, c=3, ......): > for key, val in locals().items(): > if key != 'self': > setattr(self.__class__, key, val) > > in addition: > > def set(self, **kwarg): > for key in kwargs: > if hasattr(self.__class__, key): > setattr(self.__class__, key, kwargs[key]) > else: > raise .... Why setattr(self.__class__,...) instead of setattr(self, ...)? You're modifying the class attributes, and that's not usually intended. -- Gabriel Genellina From http Mon Jan 1 00:23:03 2007 From: http (Paul Rubin) Date: 31 Dec 2006 21:23:03 -0800 Subject: I want to see all the variables References: <45952426.1080800@websafe.com> <8yelh.90$Q4.82@newsfe02.lga> <459722fc$0$30313$9b4e6d93@newsspool1.arcor-online.net> <2v0hp2tbk8uq2pbqi6874b4tidbck2tpga@4ax.com> Message-ID: <7xbqljnww8.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > At the same time, you should ponder very > > carefully the reasons why the original author deemed it important to > > make those attributes private in the first place. > > In my experience, it is mostly because they come from > bondage-and-domination languages where it is expected that > everything is private except for a small, carefully chosen public > API, rather than from languages like Python that encourages openness > and a philosophy of "we're all adults here". Funny thing, some of those B&D languages were designed by people who had plenty of experience with Lisp and were tired of being bitten by its Python-like looseness. > I wonder how many double-underscore "private" attributes are used in the > Python standard library? That should give you an idea of "best practice" > use of private attributes in Python. If socket.py is an example of best practice use of private attributes, I shudder to imagine what kind of cruft must lurk in legacy applications. From me17 at privacy.net Tue Jan 9 10:25:43 2007 From: me17 at privacy.net (zoara) Date: Tue, 9 Jan 2007 15:25:43 +0000 Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: On 9 Jan 2007 06:58:15 -0800, octabox at gmail.com wrote: > Hello all, > > I represent Octabox, an Internet Start-up developing a wide-scale > platform for Internet services. We are very interested to know your > thoughts on Internet productivity and how it might be improved, and to > that end we have set up a short survey at our website - > http://www.octabox.com/productivity_poll.php > We would very much appreciate if you would take a couple of minutes to > fill it up and influence our direction and empahsis. Well, that was too tempting to pass up. Amusing answers related to dirty bastard time-wasting spammers duly entered and submitted. -z- -- Our team is conducting a benchmarking effort to gather an outside-in view on development performance metrics and best practice approaches to issues of process and organization from companies involved in a variety of software development (and systems integration). From jstroud at mbi.ucla.edu Thu Jan 18 19:57:56 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 18 Jan 2007 16:57:56 -0800 Subject: Using lambda with a Pmw.ComboBox In-Reply-To: <1169167034.200565.227900@a75g2000cwd.googlegroups.com> References: <1169167034.200565.227900@a75g2000cwd.googlegroups.com> Message-ID: Willie wrote: > Hi, > > I have an array of 2 ComboBoxes. I would like to use lambda to report > on which widget is being accessed. When I use arrays of other widgets I > just use lambda to return which item I am using as an argument. This > does not seem to work with ComboBox, the only thing returned is the > value changed. > > Can someone refer me to some code which shows this in action? I have > searched the web for a solution, without any luck. > > Thanks, > > Willie > Can you show us your code? Your question is ambiguous to me. Comboboxes do not hold widgets but display text. From bearophileHUGS at lycos.com Fri Jan 19 05:59:14 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 Jan 2007 02:59:14 -0800 Subject: Match 2 words in a line of file In-Reply-To: <1169175299.490994.244700@51g2000cwl.googlegroups.com> References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> <1169172954.107365.133950@51g2000cwl.googlegroups.com> <1169175299.490994.244700@51g2000cwl.googlegroups.com> Message-ID: <1169204354.494510.277840@v45g2000cwv.googlegroups.com> Rickard Lindberg, yesterday I was sleepy and my solution was wrong. > 2) If you have a line something like this: "foobar hello" then "'foo' > in line" will return true, even though foo is not a word (it is part of > a word). Right. Now I think the best solution is to use __contains__ (in) to quickly find the lines that surely contains both substrings, then on such possibly rare cases you can use a correctly done RE. If the words are uncommon enough, such solution may be fast and reliable. Using raw tests followed by slow and reliable ones on the rare positive results of the first test is a solution commonly used in Computer Science, that often is both fast and reliable. (It breaks when the first test is passed too much often, or when it has some false negatives). Probably there are even faster solutions, scanning the whole text at once instead of inside its lines, but the code becomes too much hairy and probably it's not worth it. Bye, bearophile From arkanes at gmail.com Mon Jan 8 12:27:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 8 Jan 2007 11:27:54 -0600 Subject: Suitability for long-running text processing? In-Reply-To: <84fb38e30701080919r41d52fb6nc5ee31f12e901ef3@mail.gmail.com> References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> <4866bea60701080849h16d1dacew7a0abe950726c006@mail.gmail.com> <84fb38e30701080919r41d52fb6nc5ee31f12e901ef3@mail.gmail.com> Message-ID: <4866bea60701080927r4dedd392o38d45660864a8717@mail.gmail.com> On 1/8/07, tsuraan wrote: > > > > My first thought was that interned strings were causing the growth, > > but that doesn't seem to be the case. > > Interned strings, as of 2.3, are no longer immortal, right? The intern doc > says you have to keep a reference around to the string now, anyhow. I > really wish I could find that thing I read a year and a half ago about > python never collecting small strings, but I just can't find it anymore. > Maybe it's time for me to go source diving... > > I remember something about it coming up in some of the discussions of free lists and better behavior in this regard in 2.5, but I don't remember the details. Interned strings aren't supposed to be immortal, these strings shouldn't be automatically interned anyway (and my brief testing seemed to bear that out) and calling _Py_ReleaseInternedStrings didn't recover any memory, so I'm pretty sure interning is not the culprit. From jstroud at mbi.ucla.edu Mon Jan 22 18:38:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 22 Jan 2007 15:38:01 -0800 Subject: SQLObject 0.8.0b2 In-Reply-To: References: Message-ID: Oleg Broytmann wrote: > Hello! > > I'm pleased to announce the 0.8.0b2 release of SQLObject. > > > What is SQLObject > ================= > > SQLObject is an object-relational mapper. Your database tables are described > as classes, and rows are instances of those classes. SQLObject is meant to be > easy to use and quick to get started with. > > SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and > Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also > known as SAPDB). > > > Where is SQLObject > ================== > > Site: > http://sqlobject.org > > Development: > http://sqlobject.org/devel/ > > Mailing list: > https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss > > Archives: > http://news.gmane.org/gmane.comp.python.sqlobject > > Download: > http://cheeseshop.python.org/pypi/SQLObject/0.8.0b2 > > News and changes: > http://sqlobject.org/devel/News.html > > > What's New > ========== > > News since 0.8.0b1 > ------------------ > > * Another round of bugfixes for MySQL errors 2006 and 2013 (SERVER_GONE, > SERVER_LOST). > > * Fixed a bug in MSSQLConnection caused by column names being unicode. > > * Fixed a bug in FirebirdConnection caused by column names having trailing > spaces. > > * Remove a leading slash in FirebirdConnection. > > For a more complete list, please see the news: > http://sqlobject.org/devel/News.html > > Oleg. This project has an amazingly impressive pace of development: 10:20 AM : "SQLObject 0.7.3b1" 10:22 AM : "SQLObject 0.8.0b2" But I'm wondering, why is it taking so long for SQLObject 0.8.7b3? James From http Wed Jan 24 22:35:05 2007 From: http (Paul Rubin) Date: 24 Jan 2007 19:35:05 -0800 Subject: My Tkinter Threading nightmare References: <1169693266.209082.323310@a75g2000cwd.googlegroups.com> <7x1wljajgg.fsf@ruckus.brouhaha.com> Message-ID: <7xac07wzh2.fsf@ruckus.brouhaha.com> Paul Rubin writes: > def idle(self): > # read and execute any commands waiting on the queue > while True: > try: > func, args, kw = self.cmd_queue.get(block=False) > except QueueEmpty: > return > func (*args, **kw) Whoops, I forgot, you have to set up the after event again at the end of this: def idle(self): # read and execute any commands waiting on the queue while True: try: func, args, kw = self.cmd_queue.get(block=False) except QueueEmpty: return func (*args, **kw) self.after(20, self.idle) From bdesth.quelquechose at free.quelquepart.fr Fri Jan 12 18:22:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Jan 2007 00:22:08 +0100 Subject: globals accros modules In-Reply-To: <38388$45a6b867$d443bb3a$10089@news.speedlinq.nl> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> <45a66cea$0$289$426a34cc@news.free.fr> <3137a$45a6851a$d443bb3a$24085@news.speedlinq.nl> <45a69cca$0$321$426a74cc@news.free.fr> <38388$45a6b867$d443bb3a$10089@news.speedlinq.nl> Message-ID: <45a811ba$0$291$426a34cc@news.free.fr> Stef Mientki a ?crit : > Bruno Desthuilliers wrote: > >> Stef Mientki a ?crit : >> >>> Bruno Desthuilliers wrote: >>> >>>> stef a ?crit : >> >> (snip) >> >>>>> but tell them that they are going to loose all their globals ??? >>>> >>>> It's a feature. Globals are definitively a BadThing(tm). >>> >>> yes, I know, but my audience will accept that only in the long term. >> >> Unless you clearly explain the benefits... Any code relying on the >> existence of a global is: >> 1/ dependent on the existence of this global >> 2/ harder to understand > > And you think physicians will believe that ? Aren't physicians supposed to be somewhat cartesians guys ? FWIW, functional languages are mostly used by peoples with a strong mathematical background... > And suppose they believe it, are the willing to stop their research to > rethink and rewrite their code ;-) Not my problem. But anyway, if they really hope to get reliable results, they'd better have bug-free programs, and using globals not only potentially introduces subtle bugs, but also makes code hardly unit-testable... >> >> FWIW, I'm currently fixing a simple Delphi program that's using quite >> a few globals, > > Then it was certainly not written by a Delphi-guy ;-) Yes it was. But that does not imply it was written by a competent Delphi-guy !-) (snip) >> >> # another.py >> import myglobs >> print myglobs.meaning_of_life >> >>> >>> >>> import Ugly_MatLab_Globals >>> >>> def some_function(): >>> import Ugly_MatLab_Globals >> >> >> You don't have to reimport it here... > > Then I miss something: Probably > TEN = 10 > TWELVE = 12 > def some_function(): > global TEN > TEN = 9 rebinds the 'global' (well... module) name 'TEN'. > TWELVE = 11 creates a *local* name 'TWELVE' and bind it to integer 11. > print TEN, TWELVE > > some_function() #will print 9,11 > print TEN, TWELVE #will print 9,12 > > Or am I mistaken ? You are. bruno at bibi playground $ cat myglobals.py a = None b = None bruno at bibi playground $ cat useglobals.py import myglobals def test(): myglobals.a = "meaning_of_life" myglobals.b = 42 print "myglobals.a : ", myglobals.a print "myglobals.b : ", myglobals.b test() print "myglobals.a : ", myglobals.a print "myglobals.b : ", myglobals.b bruno at bibi playground $ python useglobals.py myglobals.a : None myglobals.b : None myglobals.a : meaning_of_life myglobals.b : 42 From usenet200701 at tobyinkster.co.uk Sun Jan 28 09:54:00 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Sun, 28 Jan 2007 14:54:00 +0000 Subject: Ip address References: Message-ID: <81qu84-b0l.ln1@ophelia.g5n.co.uk> Scripter47 wrote: > How do i get my ip address? Which IP address. One computer might have many IP addresses. (Indeed a typical network-connected computer will tend to have at least one for each connected network device, plus the special address 127.0.0.1 for the loopback network.) How is Python supposed to know which IP address you want? If you don't care which address, the code supplied by Adam should work. If you do care, then you'll probably need to write OS-specific code for each platform you choose to support, probably parsing the output of ipconfig (Windows) or ifconfig (Linux/UNIX/Mac) somehow. Adam also says: | If you are wanting to to communicate over the internet you will have | to get the IP of you rounter. Not strictly true, but if your network uses NAT, and you want some host outside your network to be able to *connect to you*, then yes, you need the IP address of your router. If you're not using NAT, then you shouldn't need to worry about your router, as IP addresses alone provide full end-to-end routing. (Indeed that's the whole point of IP.) -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From mail at microcorp.co.za Wed Jan 3 01:27:20 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 3 Jan 2007 08:27:20 +0200 Subject: Writing more efficient code References: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net><1167687229.430930.197720@v33g2000cwv.googlegroups.com><459989ec$0$8759$ed2619ec@ptn-nntp-reader02.plus.net><1167699678.310643.140480@n51g2000cwc.googlegroups.com> <459b03e5$0$8725$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <015201c72f00$8d0d19e0$03000080@hendrik> "Jon Harrop" wrote: > I think that is an excellent idea. Who will pay me? ;-) The same fellow who is paying you to post to this newsgroup... - Hendrik From ziade.tarek at gmail.com Sat Jan 6 12:24:46 2007 From: ziade.tarek at gmail.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Sat, 6 Jan 2007 18:24:46 +0100 Subject: python, zlib, and fedora 64bits In-Reply-To: <94bdd2610701060222u3448213eyd9a66e167ed6eb92@mail.gmail.com> References: <94bdd2610701060147i6725e52bgdcc3d81377366ecd@mail.gmail.com> <200701060402.25665.jonc@icicled.net> <94bdd2610701060222u3448213eyd9a66e167ed6eb92@mail.gmail.com> Message-ID: <94bdd2610701060924s1a00ccc9r222e90e892665a05@mail.gmail.com> I am answering to myself, if it can help someone else. zlib has to be recompiled with CFLAGS set to -fPIC. So before launching ./configure do a: export CFLAGS="-fPIC" Python then will build properly zlib.so Tarek -------------- next part -------------- An HTML attachment was scrubbed... URL: From google98.email at blogger.com Sun Jan 7 22:59:55 2007 From: google98.email at blogger.com (Mr.Wiggly) Date: Mon, 08 Jan 2007 03:59:55 GMT Subject: *^*^*^*^8=====> Sexy Bikini Video Downloads <=====8*^*^*^*^*^* Message-ID: <%kjoh.572086$5R2.443620@pd7urf3no> An HTML attachment was scrubbed... URL: From jzgoda at o2.usun.pl Sat Jan 20 14:47:31 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 20 Jan 2007 20:47:31 +0100 Subject: Win GUI application: avoiding DOS console In-Reply-To: References: Message-ID: Siggi napisa?(a): > how do I avoid the DOS console show-up when starting a WinXP GUI application > with mouseclick on the respective Python file? > > I had this with my previous Python installation; it is very simple, > something with a "-i" somewhere in the open command of the MS Windows data > types "PY" and "PYW". But after a new Python installation, this was lost, > and I cannot find the instruction what to do. Run it using pythonw.exe instead of python.exe (check in file types properties window). -- Jarek Zgoda http://jpa.berlios.de/ From durumdara at gmail.com Tue Jan 2 04:04:43 2007 From: durumdara at gmail.com (durumdara) Date: Tue, 02 Jan 2007 10:04:43 +0100 Subject: [Off] WXP Fingerprint + Python... Message-ID: <459A202B.2080202@gmail.com> Hi! I have an application (Python + wx) somewhere. The users use they fingerprint to log[in/out]. But we have a problem that in this time the fingerprint logon is do REAL windows logon, so every user need a windows user too, and many times it need to close/open application, and Windows. We need better solution. We tried MS Fingerprint Reader, but that is working in same method: it store the fingerprints for every Windows user... I need something better. Do anyone knows about a Fingerprint Software and device that can recognize many-many fingerprints, and it can associate the actual fingerprint with a VIRTUAL(! not windows user! a virtual!) user that stored in a DB? This DB can store other infos, or an ID that we can use in another app... Or a software hook needed (DLL hook) that can add possibility to catch the login/outs, and I can do anything else as I need. Do anyone knows about same solution or product? Thanks for help: dd From bigblueswope at gmail.com Wed Jan 24 07:12:47 2007 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 24 Jan 2007 07:12:47 -0500 Subject: smtplib starttls gmail example - comments? In-Reply-To: <9afea2ac0701240256kae247b3s666be6529362c84e@mail.gmail.com> References: <9afea2ac0701240256kae247b3s666be6529362c84e@mail.gmail.com> Message-ID: On 1/24/07, Tim Williams wrote: > > On 24/01/07, py wrote: > > I would love for anybody to comment on this code with regard to > redundancy/efficiency/wordiness or whatever else. > > for instance, do i understand correctly that i cant have a try: else: > without an intervening except:? > > -dave > > > > stdout.write("calling smtp server...") > > try: > > server = SMTP(msgsmtp) > > except: > > stdout.write("FAIL.") #using .write to avoid the implied > \n with print > > else: > > server.set_debuglevel(msgdebug) > > stdout.write("starting tls...") > > server.ehlo(msgfrom) > > try: server.starttls() > > except: stdout.write("FAIL.") > > else: > > server.ehlo(msgfrom) #neessary duplication (?) > > stdout.write("logging in...") > > try: server.login(msgfrom, msgpass) > > except: stdout.write("FAIL.") > > else: > > stdout.write("sending...") > > try: server.sendmail(msgfrom, msgto, msgtxt + > "\n.\n") > > except: stdout.write("FAIL.") > > else: > > try: > > server.quit() > > except sslerror: # a known and largely > ignored issue with early EOF in ssl protocol > > stdout.write("success.") > > else: > > stdout.write("success.") > > -- > > > *** Not tested but should have the same functionality and error > handling as your script *** > > this_host = 'myhostname.mydom1.com' > print "calling smtp server...", # the trailing comma removes '\n' > try: > server = smtplib.SMTP(msgsmtp,local_hostname=this_host) > server.set_debuglevel(msgdebug) > print "starting tls...", > server.starttls() > server.ehlo(this_host) # RFC requirement for 2nd EHLO after > requesting TLS > print "logging in...", > server.login(msgfrom, msgpass) > print "sending...", > failed = server.sendmail(msgfrom, msgto, msgtxt + "\n.\n") > try: > server.quit() > except: pass > print "success." > except: > print "FAIL.", > > if failed: > print "failed:", failed # some recipients, but not all of them, > failed > -- > http://mail.python.org/mailman/listinfo/python-list > Both examples have included the cardinal sin in smtp... They both send the message text followed by new line dot new line. The smtp protocol specifically mentions CRLF dot CRLF. Please please please use \r\n.\r\n in your code... -- We are all slave to our own paradigm. -- Joshua Williams -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomas at fancy.org Mon Jan 8 20:09:57 2007 From: tomas at fancy.org (Tom Plunket) Date: Mon, 08 Jan 2007 17:09:57 -0800 Subject: Non-blocking pipes during subprocess handling Message-ID: <22q5q25jn7dfti18rv1tshj7os5a0gm27r@4ax.com> I'm using subprocess to launch, well, sub-processes, but now I'm stumbling due to blocking I/O. Is there a way for me to know that there's data on a pipe, and possibly how much data is there so I can get it? Currently I'm doing this: process = subprocess.Popen( args, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def ProcessOutput(instream, outstream): text = instream.readline() if len(text) > 0: print >>outstream, text, return True else: return False while process.poll() is None: ProcessOutput(process.stdout, sys.stdout) ProcessOutput(process.stderr, sys.stderr) # clean up everything to EOF once the process ends. somethingPrinted = True while somethingPrinted: somethingPrinted = ProcessOutput( process.stdout, sys.stdout) somethingPrinted |= ProcessOutput( process.stderr, sys.stderr) Unfortunately, stream.readline will block 'til it gets a line, and typically there won't be anything on the stderr stream. The reason for the redirections in the first place is that I'm launching this script as a subprocess from a GUI app that catches stdout and stderr and directs the output to the appropriate windows, but in some cases I don't actually want the output at all (I've removed that logic though since it needlessly complicates my example; suffice to say everything below the process = subprocess.Popen... line is enclosed in a try and then in an if block. The documentation on file.read() indicate that there's an option for "non-blocking" mode, but I'm stumped as to how to even look for how to enable and use that. thanks, -tom! -- From kylotan at gmail.com Tue Jan 9 07:14:34 2007 From: kylotan at gmail.com (Ben Sizer) Date: 9 Jan 2007 04:14:34 -0800 Subject: PyCFunction_New requires a pointer to a static PyMethodDef? Message-ID: <1168344874.063070.324770@38g2000cwa.googlegroups.com> In following the example given at , I find that if I instead try to create PyMethodDef instances on the stack and create methods that way, rather than providing pointers to a static array of them, executing the method later raises an exception from PyCFunction_Call. Is it required that the PyMethodDef persists throughout the execution of the Python program? If so, why isn't the information just copied instead? I was hoping to just create a temporary PyMethodDef on the stack purely for the duration of creating the method. (Google doesn't find any instance of "PyCFunction_Call" on docs.python.org. This might explain the Cookbook's comment that "one hardly ever sees Python class objects built in C extensions"!) -- Ben Sizer From steve at holdenweb.com Wed Jan 24 08:42:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Jan 2007 13:42:07 +0000 Subject: sys.path issue in cygwin In-Reply-To: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> References: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> Message-ID: Wang Shuhao wrote: > > > I successfully built and installed Python 2.2.3 in cygwin. But there is > something wrong in the sys.path. I use following statments for a test. > > >>> import sys > >>> print sys.path > ['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', > 'C/lib/python2.2/lib-tk' > , '\\Python24/lib/python2.2/lib-dynload'] > >>> > > To keep the question simple, I've set PATH= in cygwin.bat to avoid > python initialze sys.path from Windows' PATH environment. > > Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is > installed in /usr/local/lib/python2.2.3. The result of the issue is that > when you run a program python can't find the module. So what I really > want to know is where these path came from and how to fix it. > > > Why "obviously"? 2.2.3 and 2.2.2 aren't meant to coexist, so one will install over the other. So the directories you are seeing are what would be used with standard prefix settings. If you mean "obviously because I used a setting to configure the prefixes for loading from a specific directory" then perhaps you are suffering from having set your Windows PATH. If you *don't* set your Windows PATH do you see it using the "2.2.3" variants? Did you run "make install"? Just a couple of random thoughts ... are you even sure that running the "python" command does run your new 2.2.3 binary? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From gagsl-py at yahoo.com.ar Sun Jan 28 20:46:39 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Jan 2007 22:46:39 -0300 Subject: Problems with ElementTree and ProcessingInstruction In-Reply-To: <1169994480.424321.51600@m58g2000cwm.googlegroups.com> References: <1169994480.424321.51600@m58g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20070128224329.0470fa78@yahoo.com.ar> At Sunday 28/1/2007 11:28, Kent Tenney wrote: >I want to generate the following file; > > > >stuff > >How should I be doing this? open("filename","w").write('\n' '\n' 'stuff\n') :) >As far as I can tell, ElementTree() requires everything >to be inside the root element (leo_file) Just keep the first two lines on my example... -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From S.Mientki-nospam at mailbox.kun.nl Sat Jan 6 05:29:58 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 06 Jan 2007 11:29:58 +0100 Subject: howto overload with a NOP (empty statement) Message-ID: How should I overload / disable a method ? In the example below I have defined the class "Power_Supply", derived from baseclass "device". The baseclass has a method "execute", which will be implemented in most derived classes, but not in all. Now apparently it's not allowed to overload a method with an empty statement. I could write a nonsense dummy statement, like "A= 3", but isn't there another way ? thanks, Stef Mientki class device: def execute (self): print 'execute not yet implemented for', self.Name class Power_Supply (device): def execute (self): ; From nszabolcs at gmail.com Wed Jan 31 14:25:28 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 31 Jan 2007 11:25:28 -0800 Subject: Python **kwargs ? In-Reply-To: <1170263432.199403.175290@k78g2000cwa.googlegroups.com> References: <1170263432.199403.175290@k78g2000cwa.googlegroups.com> Message-ID: <1170271526.715082.125370@s48g2000cws.googlegroups.com> johnny wrote: > What is **kwargs mean in python? When you put double **, does it mean > passing by reference? here's a little example: >>> def f(a, *args, **kw): ... print 'a:',a ... print 'args:',args ... print 'kw:',kw ... >>> f(1,2,3,x=4) a: 1 args: (2, 3) kw: {'x': 4} >>> f(a=1,b=2,c=3) a: 1 args: () kw: {'c': 3, 'b': 2} From paul at boddie.org.uk Mon Jan 1 16:53:55 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 1 Jan 2007 13:53:55 -0800 Subject: PEP 3107 Function Annotations for review and comment References: <1167492896.292605.15040@48g2000cwx.googlegroups.com> <1167580455.349588.234610@v33g2000cwv.googlegroups.com> Message-ID: <1167688435.399538.318990@48g2000cwx.googlegroups.com> Tony Lownds wrote: > > It's possible packages like pylint will learn to interpret function annotations to provide > better static analysis. Right? It's true that for the area to be explored, which I know you've been doing, one first has to introduce an annotation scheme that can then be used by things like pylint. I'd like to see assertions about the usefulness of such annotations verified by modified versions of tools like pylint before changes to the language are made, mostly because such assertions seem to be more conjecture than prediction. In other words, the changes should be advocated, implemented and tested in a closed system before being introduced as wider language changes, especially given that Python has already seen a number of speculative changes which were made in anticipation of certain needs that subsequently appeared to be less significant than first thought. Another thing I find worrying about function annotations is the ambivalence around their purpose: the feature is supposedly great for static typing, but when confronted over the consequences of having developers spray type declarations everywhere, we're told that they aren't really meant for such things and that type declarations are only an example of what annotations could do. Here, the sales department and the engineering department really have to get together and get their story straight. Paul From srikrishnamohan at gmail.com Fri Jan 12 09:40:46 2007 From: srikrishnamohan at gmail.com (km) Date: Fri, 12 Jan 2007 20:10:46 +0530 Subject: setup.py ./configure arguments Message-ID: Hi, how do i pass '--enable-shared' etc arguments to Python2.5 setup.py ? do i need to edit some file ? regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From igouy at yahoo.com Sat Jan 20 17:19:12 2007 From: igouy at yahoo.com (Isaac Gouy) Date: 20 Jan 2007 14:19:12 -0800 Subject: Py 2.5 on Language Shootout In-Reply-To: References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> <45B23400.2010906@gmx.de> <1169321686.025356.120340@s34g2000cwa.googlegroups.com> Message-ID: <1169331552.918850.282920@a75g2000cwd.googlegroups.com> Ramon Diaz-Uriarte wrote: > On 20 Jan 2007 11:34:46 -0800, Isaac Gouy wrote: > > > > Ramon Diaz-Uriarte wrote: > > > On 1/20/07, Carl Friedrich Bolz wrote: > > > > pgarrone at acay.com.au wrote: > > > > >>> Looking over the benchmarks, one gains the impression that Python is a > > > > >>> slow language. > > > > >> What does that even mean - a slow language? > > > > >> > > > > > > > > > > The alioth benchmarks provide a set of numbers by which > > > > > languages may be compared. > > > > > > > > Wrong. The benchmarks provide a set of numbers by which > > > > _implementations_ of languages can be compared. After all, it is > > > > possible that someone implements a magic-pixie-dust-interpreter that > > > > executes Python programs several orders of magnitude fastes than > > > > CPython. Or you could say that C is slow because if you use CINT, a C > > > > interpreter ( http://root.cern.ch/root/Cint.html ) to execute it, it is > > > > slow. > > > > > > > > > Yeah, but this is hair-splitting. Except for Jython, IronPython, and > > > Stackless, I think when we say "Python is slow/fast" we think CPython > > > (otherwise, we qualify the implementation). For that matter it is > > > often said "the GIL ..."; oh, but wait, Stackless ... > > > > When we say "Python is slow/fast" what does "slow/fast" mean? > > > > Oh, well, I have no idea. I guess you'd have to define what "speed" > and, if that is a single number, then we can just rank languages. We'd > probably never agree on how to obtain a single number. But I think > most of us, when looking at the shootout, can see that there are some > languages that, for most of the programs, are consistently faster than > the rest, and others that are consistently slower. But really, I think > the shootout page has large, detailed and statements about the > perils and pitfalls of measuring these things. (And I do not go to the > shootout to hear the oracle tell me which language I should use in my > next project). That's wise ;-) Yes the shootout page has statements about the perils and pitfalls of measuring these things - it's encouraging that at least one person has noticed :-) > > > > > > > > > > > With other languages (e.g., Common Lisp) the separation between the > > > language and the implementation is key because, to begin with, there > > > is something external from, and independent of, any particular > > > implementation. That is not the case with Python. > > > > > > And the example of CINT is hair-splitting to the nth power.To begin > > > with, I do not think CINT implements the full standard C. But even if > > > it were, when people think of C they rarely think of CINT. > > > > And that's why the existence of CINT is such a stark reminder of the > > separation between the language and the implementation. When people > > think of C what do they think of - gcc? tiny-c? intel c? microsoft c? > > some mythical C implementation? > > > > > > Really, this ain't my war. Sure, there are two things: the language > and the implementation. But, for practical purposes, when most people > today say Python they mean CPython, whereas if the say Scheme, they > certainly need to say _which_ Scheme (I think only PLT is in the > official shootout page; there are others in the beta tests). If people > want to mean Jython or Stackless, they just say that. As for C, I > think people will need to qualify what exactly they mean. > > I think all these issues do not really lead to confusion for most of > us; certainly not if you go to the shootout page. But as I said, this > ain't my war. I was simply pointing out that correcting one poster for > talking about languages when referring to python was hair splitting. > > And I think we are all running in circles, because I guess we all > agree. This is turning into what in Spain (a country of catholic > tradition) we call a discussion about "the sex of the angels" (el sexo > de los angeles), i.e., whether angels are male or female or something > else. Since sexing angels is not my area of expertise, I'll just shut > up (I actually don't really know why I even said anything about this > issue; please, forgive my chatiness). In England the corresponding expression is "Counting Angels on a Pinhead" http://dannyayers.com/2001/misc/angels.htm > > Best, > > R. > > > > > > > > I think readers understood the previous poster. > > > > > > Best, > > > > > > R. > > > > > > > > Cheers, > > > > > > > > Carl Friedrich Bolz > > > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > > > -- > > > Ramon Diaz-Uriarte > > > Statistical Computing Team > > > Structural Biology and Biocomputing Programme > > > Spanish National Cancer Centre (CNIO) > > > http://ligarto.org/rdiaz > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Ramon Diaz-Uriarte > Statistical Computing Team > Structural Biology and Biocomputing Programme > Spanish National Cancer Centre (CNIO) > http://ligarto.org/rdiaz From half.italian at gmail.com Tue Jan 2 15:16:58 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 2 Jan 2007 12:16:58 -0800 Subject: Remote askopenfilename() Message-ID: <1167769018.742658.286380@s34g2000cwa.googlegroups.com> Hi all. I'm trying to get Tkinter.askopenfilename() to list a directory tree on a remote computer. I've got some ideas, but nothing is slapping me in the face. Can someone point me in the right direction? ~Sean From bob at passcal.nmt.edu Fri Jan 26 13:18:42 2007 From: bob at passcal.nmt.edu (Bob Greschke) Date: Fri, 26 Jan 2007 11:18:42 -0700 Subject: time series data and NumPy References: <1169830757.220964.196540@m58g2000cwm.googlegroups.com> <51us3uF1mdcpsU1@mid.uni-berlin.de> <1169834042.396351.12660@h3g2000cwc.googlegroups.com> Message-ID: <2007012611184275249-bob@passcalnmtedu> On 2007-01-26 10:54:02 -0700, "BBands" said: > On Jan 26, 9:29 am, "Diez B. Roggisch" wrote: > >> What you could do would be to convert the date-column into a timestamp, >> which is a int/long, and use that. Would that help? > > Actually that might help, as all I need the date for is to index > values. > > Thanks, I'll give it a spin. > > jab You're using the Python-MySQL module mysqldb, right? You can select the data from the database and have MySQL do the conversion with an SQL command. select to_days(), from ; Bob From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 06:36:29 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 19 Jan 2007 22:36:29 +1100 Subject: Iterator length References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> <1169167258.553202.190130@m58g2000cwm.googlegroups.com> <1169168139.350836.79790@s34g2000cwa.googlegroups.com> Message-ID: On Thu, 18 Jan 2007 16:55:39 -0800, bearophileHUGS wrote: > What's your point? Maybe you mean that it consumes the given iterator? > I am aware of that, it's written in the function docstring too. But > sometimes you don't need the elements of a given iterator, you just > need to know how many elements it has. A very simple example: > > s = "aaabbbbbaabbbbbb" > from itertools import groupby > print [(h,leniter(g)) for h,g in groupby(s)] s isn't an iterator. It's a sequence, a string, and an iterable, but not an iterator. I hope you know what sequences and strings are :-) An iterable is anything that can be iterated over -- it includes sequences and iterators. An iterator, on the other hand, is something with the iterator protocol, that is, it has a next() method and raises StopIteration when it's done. >>> s = "aaabbbbbaabbbbbb" >>> s.next() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute 'next' An iterator should return itself if you pass it to iter(): >>> iter(s) is s False >>> it = iter(s); iter(it) is it True You've said that you understand len of an iterator will consume the iterator, and that you don't think that matters. It might not matter in a tiny percentage of cases, but it will certainly matter all the rest of the time! And let's not forget, in general you CAN'T calculate the length of an iterator, not even in theory: def randnums(): while random.random != 0.123456789: yield "Not finished yet" yield "Finished" What should the length of randnums() return? One last thing which people forget... iterators can have a length, the same as any other object, if they have a __len__ method: >>> s = "aaabbbbbaabbbbbb" >>> it = iter(s) >>> len(it) 16 So, if you want the length of an arbitrary iterator, just call len() and deal with the exception. -- Steven. From skip at pobox.com Tue Jan 23 22:37:25 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Jan 2007 21:37:25 -0600 Subject: easy_install pylons failure - www.myghty.org unavailable Message-ID: <17846.54389.27457.383902@montanaro.dyndns.org> I'm trying to easy_install pylons. Alas: $ easy_install pylons Searching for pylons Best match: Pylons 0.9.4.1 Processing Pylons-0.9.4.1-py2.5.egg Pylons 0.9.4.1 is already the active version in easy-install.pth Using /usr/local/mojam/lib/python2.5/site-packages/Pylons-0.9.4.1-py2.5.egg Processing dependencies for pylons Searching for Myghty>=1.1 Reading http://cheeseshop.python.org/pypi/Myghty/ Reading http://cheeseshop.python.org/pypi/Myghty/1.1 Reading http://www.myghty.org error: Download error: (111, 'Connection refused') Is it not able to get past this point because there is only one source for Myghty or does it always need to go to a package's home page? I was able to work around this by manually downloading the Myghty-1.1.tar.gz file and installing it. Skip From fredrik at pythonware.com Thu Jan 4 01:40:47 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Jan 2007 07:40:47 +0100 Subject: new office formats, REs and Python In-Reply-To: References: Message-ID: tubby wrote: > How are Python users dealing with some of the new OASIS Open Document > formats (Open Office) or MS Open XML formats. These formats store data > in a file which is actual a zip archive that contains numerous files and > folders. For example, a file saved from Open Office 2.0 named 'test.odt' > can be unzipped into many parts... content.xml, meta.xml, settings.xml, > etc, etc. > > How can I read these files do re searching and matching on them, etc? > content.xml may have a string I'm searching for, but how would I attach > that back to the original 'test.odt' file? http://ooopy.sourceforge.net/ http://www.google.com/search?q=python+open+office etc From gert.cuykens at gmail.com Tue Jan 16 14:25:26 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Tue, 16 Jan 2007 20:25:26 +0100 Subject: for v in l: In-Reply-To: References: Message-ID: ok thx this was just what i was looking for http://docs.python.org/tut/node7.html#SECTION007600000000000000000 From nogradi at gmail.com Wed Jan 31 10:59:24 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 31 Jan 2007 16:59:24 +0100 Subject: "Correct" db adapter In-Reply-To: <45c0b8cd$0$5072$ba4acef3@news.orange.fr> References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> Message-ID: <5f56302b0701310759i4e643c43u27f5aaf0fb21e0dc@mail.gmail.com> > Maybe you should take a look at sqlalchemy > > > Hi to all, > > > > i have started a month ago to seriously studying Python. I am now > > looking at the databases stuff > > and i want the opinion of more experienced Python programmers (than > > me) at the following : > > > > I see that there are a lot of databases adapters on the net, some > > following the DB-API 2.0 and some others do not. I want to use a db- > > module that do not tie me down to a specific database and that fully > > supports DB-API 2.0 > > Now i am using Sql Server but who knows about tomorrow. > > > > I started using pyodbc and looking how i can e.x. call stored > > procedure with arguments and all that stuff. > > This is using ODBC syntac and i found enough info on the net. > > > > Is the approach i took the "correct" one or is there a better db- > > module so i can use ? > > > > Thanks in advance > SQLObject might be of interest to you: http://sqlobject.org/ it is a DB-API 2.0 compliant ORM. From zaz600 at gmail.com Mon Jan 29 09:53:40 2007 From: zaz600 at gmail.com (NoName) Date: 29 Jan 2007 06:53:40 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <7xveiqapwi.fsf@ruckus.brouhaha.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170064302.264009.12650@p10g2000cwp.googlegroups.com> <7xveiqapwi.fsf@ruckus.brouhaha.com> Message-ID: <1170082420.420688.109910@l53g2000cwa.googlegroups.com> Hmmm.. In the Perl example password generates after user hit ENTER not continously like in Python you wrote... :) i want see various ways to generate passwords even if they some indirect like using BASE64 thanks all p.s. sorry for my eng ;) From gnewsg at gmail.com Wed Jan 17 07:09:33 2007 From: gnewsg at gmail.com (billie) Date: 17 Jan 2007 04:09:33 -0800 Subject: Projects anyone? In-Reply-To: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> References: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> Message-ID: <1169035773.692421.84610@38g2000cwa.googlegroups.com> placid wrote: > Hi all, > > I'm looking for anyone who is working on a project at the moment that > needs help (volunteer). The last project i worked on personally was > screen-scraping MySpace profiles (read more at the following link) > > http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles > > > but that didn't go all to well, so im kinda bored and need something to > do, with Python. So any suggestions anyone? > > Cheers Please, contact me at: billiejoex __ at __ gmail.com I could need help for 3 projects. From ptmcg at austin.rr._bogus_.com Sun Jan 7 17:43:32 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 7 Jan 2007 16:43:32 -0600 Subject: Additional pyparsing examples in latest release (1.4.5) Message-ID: <45a17793$0$5197$4c368faf@roadrunner.com> It seems I left out some examples from my announcement of pyparsing 1.4.5. Here is a more complete list of the new examples: parsePythonValue.py - parses strings representing lists, dicts, and tuples, with nesting support; safe alternative to using eval sql2dot.py - SQL diagram generator, parsed from schema table definitions (adapted from a post at http://energyblog.blogspot.com/2006/04/blog-post_20.html) jsonParser.py - parses JSON object serializations into hierarchical ParseResults, accessible using list, dict, or object attribute methods htmlStripper.py - strips HTML tags from HTML pages, leaving only body text -- Paul From irmen.NOSPAM at xs4all.nl Sun Jan 28 13:17:56 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 28 Jan 2007 19:17:56 +0100 Subject: socket.inet_ntop, and pton question In-Reply-To: <12rpns1tkp0e34@corp.supernews.com> References: <12rpns1tkp0e34@corp.supernews.com> Message-ID: <45bce8f7$0$334$e4fe514c@news.xs4all.nl> Andrew wrote: > Hi > > Are these functions (inet_ntop(), inet_pton()) from the socket library > supported on Windows. > > If not is there an equivalent for them using Windows > > Ive seen mention of people creating their own in order to use them > > Appreciate the help > > ty Why didn't you just try: [E:\Projects]python Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> socket.inet_aton("127.0.0.1") '\x7f\x00\x00\x01' >>> socket.inet_ntoa(_) '127.0.0.1' >>> This is on windows xp. --Irmen From stefan.behnel-n05pAM at web.de Sat Jan 6 07:16:43 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 06 Jan 2007 13:16:43 +0100 Subject: Using sax libxml2 html parser In-Reply-To: <1167995370.789361.43410@v33g2000cwv.googlegroups.com> References: <1167995370.789361.43410@v33g2000cwv.googlegroups.com> Message-ID: <459f932c$0$30318$9b4e6d93@newsspool1.arcor-online.net> cesar.ortiz at gmail.com wrote: > I have created an example using libxml2 based in the code that appears > in http://xmlsoft.org/python.html. > My example processes an enough amount of html files to see that the > memory consumption rises till the process ends (I check it with the > 'top' command). Try the lxml binding for libxml2. It relieves you from having to do your own memory management and makes using that library plain easy. http://codespeak.net/lxml/ Stefan From Sardaukary at gmail.com Tue Jan 9 17:19:34 2007 From: Sardaukary at gmail.com (Sard) Date: 9 Jan 2007 14:19:34 -0800 Subject: What does the -O flag do? Message-ID: <1168381174.638428.168500@k58g2000hse.googlegroups.com> http://rgruet.free.fr/PQR25/PQR2.5.html says "Optimize generated bytecode (also PYTHONOPTIMIZE=x). Asserts are suppressed." Is removing asserts all it does, where can I find more details? I'm guessing it's not very useful as I hardly ever see it mentioned. From mhellwig at xs4all.nl Sat Jan 27 11:33:44 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 27 Jan 2007 17:33:44 +0100 Subject: Dictionary inserts and threads Message-ID: <45bb7eac$0$321$e4fe514c@news.xs4all.nl> Hi all, I'm thinking to speed up a process, I like to use multiple threads to get data fractions from multiple servers and place those data fragments into a local dictionary for further processing, the dictionary will look like this: self.dic = {'thread_a':dict(), 'thread_b':dict()} The fragments will not overlap each other, since they will be subdictionaries within the dictionary, though it would be possible that multiple threads do something like this at the same time: self.dic['thread_a'] = data_from_a() and self.dic['thread_b'] = data_from_b() I assume that this is not a problem, but since assuming something gives a lot of room for screw-ups I rather ask beforehand if I should except all kinds of troubles when multiple threads update 'at the same time' a dictionary or that I should lock the dictionary, for each update? Thanks for your insights. -- mph From steve at REMOVE.THIS.cybersource.com.au Sat Jan 27 23:36:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 28 Jan 2007 15:36:43 +1100 Subject: assertions to validate function parameters References: <1169909883.944892.74390@k78g2000cwa.googlegroups.com> <1169954946.479629.312100@k78g2000cwa.googlegroups.com> Message-ID: On Sat, 27 Jan 2007 19:29:06 -0800, Carl Banks wrote: > On Jan 27, 6:51 pm, Steven D'Aprano > wrote: >> On Sat, 27 Jan 2007 06:58:04 -0800, Carl Banks wrote: >> >> I find that when I detect invalid parameters overtly, I spend less time >> >> debugging. >> >> > If it helps go ahead an use them. The world won't end if you use an >> > assertion in a less than ideal situation. And, after all, if someone >> > doesn't like it they can shut them off. >> >> Is there any way to have finer control of assertions than just passing -O >> to the Python interpreter? Suppose I want to switch them off for certain >> modules but not others, am I out of luck? > > Please relax. The suggestion that one could shut them off was tongue > in cheek. (a) I am relaxed; (b) One can shut down assertions, and it isn't a joke, it is a feature; (c) I meant my question seriously, I think it would be a good thing. -- Steven. From Eric_Dexter at msn.com Sun Jan 14 02:36:51 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 13 Jan 2007 23:36:51 -0800 Subject: Tkinter code (with pmw) executing to soon please help In-Reply-To: <45a9ad0a$1@nntp0.pdx.net> References: <1168746063.322340.10410@l53g2000cwa.googlegroups.com> <45a9ad0a$1@nntp0.pdx.net> Message-ID: <1168760210.636485.205020@a75g2000cwd.googlegroups.com> C:\dex_tracker\csdlist.py bay-at-night.csd Traceback (most recent call last): File "C:\dex_tracker\csdlist.py", line 58, in root.mainloop() File "C:\Python25\lib\lib-tk\Tkinter.py", line 1023, in mainloop self.tk.mainloop(n) File "../../..\Pmw\Pmw_1_2\lib\PmwBase.py", line 1751, in __call__ File "../../..\Pmw\Pmw_1_2\lib\PmwBase.py", line 1777, in _reporterror TypeError: unsupported operand type(s) for +: 'type' and 'str' Script terminated. It doesn't like the return handler part of it. Scott David Daniels wrote: > Gabriel Genellina wrote: > >... So `callback` should return a function, like this: > > > > def callback(text): > > def handler(event): > > print text > > > > Even better than that: > def callback(text): > def handler(event): > print text > return handler > > Otherwise callback returns the spectacularly un-useful value None. > > --Scott David Daniels > scott.daniels at acm.org From bjourne at gmail.com Wed Jan 31 05:38:01 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 31 Jan 2007 11:38:01 +0100 Subject: data design In-Reply-To: References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> <45bfbcc3$0$30950$426a74cc@news.free.fr> <1170201274.580256.182740@v45g2000cwv.googlegroups.com> Message-ID: <740c3aec0701310238o4786273fuf3bce8c2f595c3e6@mail.gmail.com> On 1/31/07, James Stroud wrote: > [copy_files] > files_dir1 = this.file that.file > path_dir1 = /some/path > > files_dir2 = the_other.file yet_another.file > path_dir2 = /some/other/path > > In yaml, it might look thus. > > copy_files : > - files : [this.file, that.file] > path : /some/path > - files : [the_other.file, yet_another.file] > path : /some/other/path > > Both are readable (though I like equals signs in appearance over > colons), but yaml doesn't require a lot of string processing to group > the files with the paths. I don't even want to think the coding > gymnastics required to split all of the option names and then group > those with common suffixes. But is not that a perfect world example? Consider: [copy_files] files_dir1=this.file that.file path_dir1=/some/path files_dir2=the_other.file yet_another.file path_dir2=/some/other/path versus: copy_files: -files:[this.file,that.file] path:/some/path -files:[the_other.file,yet_another.file] path:/some/other/path Mandatory indentation is good in programming languages, but does it really belong in configuration files? With tabs verboten to boot. -- mvh Bj?rn From http Fri Jan 5 18:37:32 2007 From: http (Paul Rubin) Date: 05 Jan 2007 15:37:32 -0800 Subject: Encoding / decoding strings References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> <1168010144.000928.131920@42g2000cwt.googlegroups.com> <1168018757.397170.216870@11g2000cwr.googlegroups.com> Message-ID: <7xr6u92gg3.fsf@ruckus.brouhaha.com> "oliver at obeattie.com" writes: > Basically, what I am trying to do is display all comments by a > specified user on the website. As the only thing which has =always= > been used to identify users which never changes is their e-mail > addresses, this is the only thing which I can use. Obviously, I can't > display this e-mail address though. Assign a unique number to each user in the system, and use the number. Email addresses aren't necessarily stable since users should be able to change their email addresses. If you really want to use a hash, use the hmac module: import hmac hash = hmac.new('swordfish', 'person at domain.tld').hexdigest() where instead of swordfish you'd use some random constant string that you keep secret. The secrecy stops attackers from figuring out whether a given address has a specific hash per Mark Rintsch's comment. You'll still have to main a table mapping hashes back to addresses, since the hashes are not reversable. If you HAVE to have reversible encryption, you could use http://nightsong.com/phr/crypto/p3.py note that the string you get is binary and is longer than the input string even before you encode it to printing chars. Note also that it reveals the length of its input. To generate a random string, use os.urandom: import os, binascii secret_string = binascii.hexlify(os.urandom(16)) you'd then embed the secret string in your program or database. You then face the problem of keeping it secret, which is not trivial. Overall you're better off just assigning ID numbers to users like most BBS's do. From yinglcs at gmail.com Mon Jan 22 16:45:40 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 22 Jan 2007 13:45:40 -0800 Subject: How to convert a string into an integer Message-ID: <1169502340.434227.224820@11g2000cwr.googlegroups.com> Can you please tell me why the following code does not work in python? My guess is I need to convert 'count' from a string to an integer. How can I do that? And my understanding is python is a dynamic type language, should python convert it for me automatically? count = sys.argv[2] for i in range(count): #do some stuff Thank you. From tgrav at mac.com Thu Jan 11 10:04:21 2007 From: tgrav at mac.com (Tommy Grav) Date: Thu, 11 Jan 2007 10:04:21 -0500 Subject: Progress count in terminal (Mac OS X) In-Reply-To: References: <9079A3B8-47A8-495A-BFAE-09A603CFB819@mac.com> Message-ID: This certainly does work when running the interpreter interactively, but when inserted into a script it seems to buffer the print statement and not write it out to the terminal. How can I force the print statement to not buffer the output? Cheers Tommy On Jan 11, 2007, at 9:22 AM, Fredrik Lundh wrote: > Tommy Grav : > >> I have a program that does a lot of iterations and would like >> to follow its progress by having it print out the current iteration >> number as it progresses. How do I do this so that it appears >> like a counter that increases in the same place in the terminal >> window? I am using python2.5 on a Mac OSX and its terminal >> tcsh window. > > print a carriage return before, and no line feed after, each line: > > for i in range(100): > print "\r" + "count", i, > print # done > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From dimitri.pater at gmail.com Wed Jan 24 18:33:59 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Thu, 25 Jan 2007 00:33:59 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: <45b72b0d$0$5107$ba4acef3@news.orange.fr> References: <45b72b0d$0$5107$ba4acef3@news.orange.fr> Message-ID: On 1/24/07, Laurent Rahuel wrote: > > Hi, > > I known this can be impossible but what about an "HTML" GUI ? Yep, I think you should consider a HTML GUI. I have just finished a project using CherryPy running on localhost. The big advantage is that the app runs on Linux, Mac and Win using a browser without any problem. You can use css and js to polish the user interface and usability of your application. regards, Dimitri --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From octabox at gmail.com Tue Jan 9 09:58:50 2007 From: octabox at gmail.com (octabox at gmail.com) Date: 9 Jan 2007 06:58:50 -0800 Subject: Internet Survey Message-ID: <1168354730.421464.159680@51g2000cwl.googlegroups.com> Hello all, I represent Octabox, an Internet Start-up developing a wide-scale platform for Internet services. We are very interested to know your thoughts on Internet productivity and how it might be improved, and to that end we have set up a short survey at our website - http://www.octabox.com/productivity_poll.php We would very much appreciate if you would take a couple of minutes to fill it up and influence our direction and empahsis. Thanks in advance, Octabox Development Team From wolf_tracks at invalid.com Wed Jan 24 16:07:51 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 24 Jan 2007 21:07:51 GMT Subject: Python Windows Editors In-Reply-To: References: Message-ID: W. Watson wrote: > I downloaded python-2.5.msi and installed it. I believe its editor is > [corrected]IDLE. I understand there's a Win editor called pythonwin. I believe it's > in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this > exe file has just the editor or all of Python. Comments? If not how do I > get the PythonWin editor by itself? > > BTW, one of the features I did not like of IDE is the limited file Print > command. It puts everything in 16pt type, and gives no choice over what > pages should be printed. Maybe there's an option? I don't see any responses that address regarding pywin32-210.win32-py2.5.exe, so it looks like I'll have to undbundle it and see for myself. From tjreedy at udel.edu Mon Jan 22 22:32:35 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Jan 2007 22:32:35 -0500 Subject: arrow keys don't work References: <1169506381.452422.179070@11g2000cwr.googlegroups.com> <1169511711.594390.167630@11g2000cwr.googlegroups.com> Message-ID: "tac-tics" wrote in message news:1169511711.594390.167630 at 11g2000cwr.googlegroups.com... |> Have you changed your terminal (either the program itself or its config) | udlr yields ^[[A^[[B^[[C^[[D in the interactive python interpreter, but | like I said, works like it should outside the Python interpreter. If I remember correctly, '^[' represents the escape character and '^[[A', etc represent the standard ANSI terminal escape sequences for the up, etc, key. So you are missing the interpretive layer that should intercept and act on those sequences and Python is getting them raw (literally). tjr From gert.cuykens at gmail.com Tue Jan 23 16:11:42 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Tue, 23 Jan 2007 22:11:42 +0100 Subject: instancemethod In-Reply-To: References: <45b51298$0$8289$426a74cc@news.free.fr> Message-ID: import MySQLdb class Db(object): def __enter__(self): pass def __init__(self,server,user,password,database): self._db=MySQLdb.connect(server , user , password , database) self._db.autocommit(True) self.cursor=self._db.cursor() def execute(self,cmd): self.cursor.execute(cmd) self.rowcount=int(self.cursor.rowcount) def close(self): self.cursor.close() self._db.close() def __getattr__(self, name): attr = getattr(self._cursor, name,getattr(self._db, name, None)) if attr is None: raise AttributeError("object %s has no attribute %s" %(self.__class__.__name__, name)) return attr def __del__(self): try: self.close() finally: pass except: pass def __exit__(self): pass if __name__ == '__main__': gert = Db('localhost','root','*****','gert') gert.execute('select * from person') for row in gert.cursor: print row with Db('localhost','root','*****','gert') as gert: gert.excecute('select * from person') for row in gert.cursor: print row Desktop/svn/db/Py/db.py:45: Warning: 'with' will become a reserved keyword in Python 2.6 File "Desktop/svn/db/Py/db.py", line 45 with Db('localhost','root','*****','gert') as gert: ^ SyntaxError: invalid syntax I was thinking if it would be possible to create a object that uses it's own instance name as a atribute. For example instead of gert = Db('localhost','root','*****','gert') you would do this gert = Db('localhost','root','*****') and the name of the object itself 'gert' get's assigned to database somehow ? From bignose+hates-spam at benfinney.id.au Sat Jan 20 02:10:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 Jan 2007 18:10:04 +1100 Subject: Code reformater? References: Message-ID: <874pqm41ir.fsf@benfinney.id.au> Vincent Delporte writes: > When I copy/paste Python code from the web, every so often, the TABs > are wrong, which means that the code won't work and I have to > manually reformat the code. > > Is there a code reformater that can parse the code to make it right? Indentation is necessary for the syntax in Python. If that information is lost, it can't be reliably recreated. -- \ "People come up to me and say, 'Emo, do people really come up | `\ to you?'" -- Emo Philips | _o__) | Ben Finney From bignose+hates-spam at benfinney.id.au Wed Jan 31 19:24:09 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Feb 2007 11:24:09 +1100 Subject: How to sort using hash's key? References: Message-ID: <87zm7yu3me.fsf@benfinney.id.au> Steven Bethard writes: > JoJo wrote: > > I want to sort a dict via its key,but I have no idea on how to do > > it. > > >>> d = dict(a=2, b=1) > >>> for key in sorted(d): > ... print key, d[key] > ... > a 2 > b 1 That's not a solution to "sort the dict"; that's getting a particular representation of the dict. It's likely the original poster wants the equivalent to list.sort() instead of a one-time output of the contents. -- \ "I installed a skylight in my apartment. The people who live | `\ above me are furious!" -- Steven Wright | _o__) | Ben Finney From wpeloqui at gmail.com Thu Jan 18 19:37:14 2007 From: wpeloqui at gmail.com (Willie) Date: 18 Jan 2007 16:37:14 -0800 Subject: Using lambda with a Pmw.ComboBox Message-ID: <1169167034.200565.227900@a75g2000cwd.googlegroups.com> Hi, I have an array of 2 ComboBoxes. I would like to use lambda to report on which widget is being accessed. When I use arrays of other widgets I just use lambda to return which item I am using as an argument. This does not seem to work with ComboBox, the only thing returned is the value changed. Can someone refer me to some code which shows this in action? I have searched the web for a solution, without any luck. Thanks, Willie From danielkleinad at gmail.com Thu Jan 11 14:02:04 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Thu, 11 Jan 2007 19:02:04 GMT Subject: Learning Python book, new edition? References: <50n9daF1g30l4U1@mid.individual.net> Message-ID: On Thu, 11 Jan 2007 18:11:06 +0100, Bjoern Schliessmann wrote: >Demel, Jeff wrote: > >> Does anyone know if there's a plan in the works for a new edition >> of Learning Python? The current edition (2nd) is a few years old >> and looks like it only covers Python 2.3. > >IIRC, differences to 2.4 are in it, too. > The only thing I see missing from it, from a 'learning' point of view, is the new try/catch/finally construct. Dan From ptmcg at austin.rr._bogus_.com Tue Jan 9 07:05:33 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 9 Jan 2007 06:05:33 -0600 Subject: line duplication using logging to file References: <1168329975.491514.282000@11g2000cwr.googlegroups.com> Message-ID: <45a3850d$0$16962$4c368faf@roadrunner.com> "seb" wrote in message news:1168329975.491514.282000 at 11g2000cwr.googlegroups.com... > Hi, I am writing to a file some basic information using the logging > module. It is working but in the log file some line are printed > several time. I had put some print debugging messages in the logging > function (so they appear on the consile) and they are called once only. > Obviously there is some understantding of the logging module that I am > missing. > > My simple logging program (see below) is called by several processes. > In this way I can collect the information from various sources (and not > use the network enabled logging module) > > I am using python 2.4 on WinXP SP2. > > Do you have any idea ? Thanks in advance. > > Seb. > A quick tally of log messages by timestamp and comment gives this data: ('2007-01-08 18:26:19,578', '___init_rs232initrs232_openCOM1') : 1 ('2007-01-08 18:26:19,578', '___run____thread lance') : 2 ('2007-01-08 18:26:32,015', '___test1TEST 1 = OK') : 3 ('2007-01-08 18:26:42,483', '___test1TEST 1 = OK') : 4 ('2007-01-08 18:26:53,750', '___test1TEST 1 = OK') : 5 ('2007-01-08 18:27:03,092', '___test1TEST 1 = OK') : 6 ('2007-01-08 18:27:13,671', '___test1TEST 1 = OK') : 7 ('2007-01-08 18:27:14,796', '___run___fin dans le run car continue = 0') : 8 ('2007-01-08 18:27:14,890', "___stopthread demande d'arret") : 9 ('2007-01-09 08:51:26,562', '___init_rs232initrs232_openCOM1') : 1 ('2007-01-09 08:51:26,733', '___run____thread lance') : 2 ('2007-01-09 08:51:39,453', '___test1TEST 1 = OK') : 3 ('2007-01-09 08:51:48,280', '___test1TEST 1 = OK') : 4 ('2007-01-09 08:51:58,750', '___test1TEST 1 = OK') : 5 ('2007-01-09 08:52:09,812', '___test1TEST 1 = OK') : 6 ('2007-01-09 08:52:19,078', '___test1TEST 1 = OK') : 7 ('2007-01-09 08:52:22,078', '___run___fin dans le run car continue = 0') : 8 ('2007-01-09 08:52:22,125', "___stopthread demande d'arret") : 8 ('2007-01-09 08:52:22,125', "___stopthread demande d'arret ") : 1 Does this suggest anything to you? -- Paul (BTW, here is the pyparsing program I used to do this analysis) from pyparsing import Word,nums,Combine,alphas,oneOf,Literal,SkipTo,restOfLine # create pyparsing grammar definition for a log line date = Word(nums,exact=4)+'-'+Word(nums,exact=2)+'-'+Word(nums,exact=2) time = Word(nums,exact=2)+':'+Word(nums,exact=2)+':'+Word(nums,exact=2)+ \ ','+Word(nums,exact=3) timestamp = Combine(date + ' ' + time) severity = oneOf( ["INFO","WARNING"] ) # not complete, but enough for this data backslash = Literal("\\") fileref = Combine(Word(alphas,exact=1)+":" + backslash + SkipTo(".py") + ".py") logline = ( timestamp.setResultsName("timestamp") + "-" + severity.setResultsName("severity") + "-" + fileref.setResultsName("fileref") + restOfLine.setResultsName("comment") ) # create list of ParseResults, with addressable log line elements by results name logEntries = [ logline.parseString(line) for line in logdata ] # tally up log lines by timestamp and comment tallyByTimestamp = {} for entry in logEntries: tallyKey = (entry.timestamp, entry.comment) tallyByTimestamp[tallyKey] = tallyByTimestamp.get(tallyKey,0) + 1 for ts in sorted( tallyByTimestamp.items() ): print "%s : %d" % ts From Ognjen at mailshack.com Thu Jan 4 11:04:07 2007 From: Ognjen at mailshack.com (Ognjen Bezanov) Date: Thu, 04 Jan 2007 16:04:07 +0000 Subject: Using External Libraries with python? Message-ID: <459D2577.70503@mailshack.com> Hello, I have some external C libraries I would like to use with python. I have been searching on the internet and found many such modules/bindings for libraries (e.g. Py-Lame) but have not yet come across any information of how to actually go about creating such bindings, so I was wondering if anybody here could point me in the right direction? Thank you! From john.d.clark at mac.com Wed Jan 3 07:05:35 2007 From: john.d.clark at mac.com (John Clark) Date: Wed, 3 Jan 2007 07:05:35 -0500 Subject: NYC Python User Group Meeting Message-ID: <01f701c72f2f$7adb9dd0$b301a8c0@haengma> Greetings! The next New York City Python Users Group meeting is this Tuesday, Jan. 9th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. RSVP to clajo04 at mac.com to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython/ Hope to see you there! -John From jura.grozni at gmail.com Tue Jan 16 11:07:09 2007 From: jura.grozni at gmail.com (azrael) Date: 16 Jan 2007 08:07:09 -0800 Subject: help needed for pymorph Message-ID: <1168963625.800116.231490@a75g2000cwd.googlegroups.com> Hi guys I tried to install and run pymorph but I am having some problems. when I want to use mmshow() I get the message ImportError: DLL load failed: the specified module could not be found import morph import handson def main (): arr = mmreadgray("beef.jpg"); mmgshow(arr) does anyone have any idea how to fix it. thnx From exarkun at divmod.com Sat Jan 6 17:15:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 6 Jan 2007 17:15:20 -0500 Subject: search mail by date with imaplib In-Reply-To: <1168112957.946721@sj-nntpcache-1.cisco.com> Message-ID: <20070106221520.11447.869207529.divmod.quotient.8153@ohm> On Sat, 06 Jan 2007 11:49:17 -0800, rweth wrote: >csselo at gmail.com wrote: >> Hi >> I am looking for a code sample which searches mail by date with imaplib >> >> example: >> get email from 01.01.2007 to now >> >> how can I change imaplib search parameters? >> >So I had to do the same thing a few years back. I love python but >seriously every author spends less than 1/10 of 1% on doc ! > >Well So do I .. so take it with a grain of salt. Here is what I did, >MANY YEARS AGO .. I don't even have a IMAP account anymore > >t,data = M.uid("SEARCH",None,'(FROM blahblah)') >luid = string.split(data[0]) >for uid in luid: > t,d = M.uid("FETCH",uid,"(BODY[HEADER.FIELDS (DATE SUBJECT TO)])") > date = d[0][1] > >This will get you the dates .. and you can write your own >filter off that .. it's trivial. What isn't so great is >getting every piece of mail and then searching for the needle's in >the haystack. > >So I guess this is plan c (just in case you don't get a better answer). >I will watch this one for a "plan a | b" answer. > The SEARCH command supports quite a few kinds of criteria. Several which may be relevant here are BEFORE, SINCE, SENTBEFORE, and SENTSINCE. Using Twisted's IMAP4 code, you can format a query like this: >>> from twisted.mail.imap4 import Query >>> Query(after='01-Jan-2007') '(AFTER "01-Jan-2007")' >>> Since documentation was brought up, I'll point out Query's docs too, since that might help shed some further light on what's possible. http://twistedmatrix.com/documents/current/api/twisted.mail.imap4.html#twisted.mail.imap4.Query Jean-Paul From __peter__ at web.de Mon Jan 29 03:06:49 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 29 Jan 2007 09:06:49 +0100 Subject: import from future References: <1169969100.946843.111770@p10g2000cwp.googlegroups.com> <1170049392.204148.54430@a34g2000cwb.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In <1170049392.204148.54430 at a34g2000cwb.googlegroups.com>, Dan Bishop > wrote: > >> Now that nested_scopes and generators are no longer optional, the only >> thing left is "from __future__ import division", which makes the "/" >> operator on integers give the same result as for floats. > > From 2.5 on we have `with_statement`:: ...and absolute_import. Peter From Eric_Dexter at msn.com Sun Jan 21 18:08:33 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 21 Jan 2007 15:08:33 -0800 Subject: Reading Fortran Data In-Reply-To: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> Message-ID: <1169420913.789301.227430@11g2000cwr.googlegroups.com> I don't know if this is helpfull or not but (or for that matter current). http://cens.ioc.ee/projects/f2py2e/ offers some suggestions and it looks like you can use it with c code also. Tyler wrote: > Hello All: > > After trying to find an open source alternative to Matlab (or IDL), I > am currently getting acquainted with Python and, in particular SciPy, > NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's > NumPy manual, I have a quick question (hopefully) regarding how to read > in Fortran written data. > > The data files are not binary, but ASCII text files with no formatting > and mixed data types (strings, integers, floats). For example, I have > the following write statements in my Fortran code: > > I write the files as such: > WRITE(90,'(A30)') fgeo_name > WRITE(90,'(A30)') fmed_name > WRITE(90,*) nfault,npoint > WRITE(90,*) (xpt(n), n=1,npoint) > WRITE(90,*) (ypt(n), n=1,npoint) > > and, > > WRITE(10,'(A30)') fname > DO i=1,nfault > WRITE(10,*) dbn(i),dtn(i),xfwnt(i),yfwnt(i),xfent(i),yfent(i),& > & slpvlS(i),slpvlD(i),slpvlT(i),segdp1(i) > END DO > > > I then respectively read them into Fortran as: > READ(70,'(A30)') fgeo_name > READ(70,'(A30)') fmed_name > READ(70,*) nfault,npoint > READ(70,*) (x(n), n=1,npoint) > READ(70,*) (y(n), n=1,npoint) > > and, > > READ(20,'(A30)') fname > DO i=1,nfault > READ(20,*) dbn(i),dtn(i),xfwnt(i),yfwnt(i),xfent(i),yfent(i),& > & slpvlS(i),slpvlD(i),slpvlT(i),segdp1(i) > END DO > > I also read them into IDL for visualization using the "READF" command. > I was wondering how I might go about reading this into Python using > NumPy. If this is not trivial, let me know and I'll just wait until the > NumPy manual arrives. > > Cheers, > > t. From michael at mustun.ch Wed Jan 3 10:17:45 2007 From: michael at mustun.ch (mm) Date: Wed, 03 Jan 2007 16:17:45 +0100 Subject: code optimization (calc PI) Message-ID: (Yes, I konw whats an object is...) BTW. I did a translation of a pi callculation programm in C to Python. (Do it by your own... ;-) -------- Calc PI for 800 digs(?). (german: Stellen) ------ int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5; for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a, f[b]=d%--g,d/=g--,--b;d*=b);} $ ./a.exe 31415926535897932384626433832795028841971693993751058209749445923078164062862089 98628034825342117067982148086513282306647093844609550582231725359408128481117450 28410270193852110555964462294895493038196442881097566593344612847564823378678316 52712019091456485669234603486104543266482133936072602491412737245870066063155881 74881520920962829254091715364367892590360011330530548820466521384146951941511609 43305727036575959195309218611738193261179310511854807446237996274956735188575272 48912279381830119491298336733624406566430860213949463952247371907021798609437027 70539217176293176752384674818467669405132000568127145263560827785771342757789609 17363717872146844090122495343014654958537105079227968925892354201995611212902196 08640344181598136297747713099605187072113499999983729780499510597317328160963185 -------- But Python is much slower here then C here. I used a while-loop within a while-loop. Not that much calculation here. From Thomas.Ploch at gmx.net Sun Jan 7 12:09:33 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 18:09:33 +0100 Subject: Why less emphasis on private data? In-Reply-To: <1168188427.144219.206490@s80g2000cwa.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> Message-ID: <45A1294D.7050103@gmx.net> sturlamolden schrieb: > time.swift at gmail.com wrote: >> Coming from a C++ / C# background, the lack of emphasis on private data >> seems weird to me. I've often found wrapping private data useful to >> prevent bugs and enforce error checking.. >> >> It appears to me (perhaps wrongly) that Python prefers to leave class >> data public. What is the logic behind that choice? > > The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that > if an object's 'internal' variables or states cannot be kept private, > programmers get an irresistible temptation to mess with them in > malicious ways. But if you are that stupid, should you be programming > in any language? The most widely used language is still C, and there is > no concept of private data in C either, nor is it needed. There is a kind of this concept in C with 'static' declarations. > As mentioned in other replies, it is not rocket science to access a > class private data. In C++ you can cast to void*, in Java and C# you > can use reflection. C++ is said to be an "unsafe" language because > programmers can, using a few tricks, mess with the vtables. But how > many really do that? Exactly, if they were available, a lot more would do that. I think this is the point. Programmers who can do that normally are sensible towards that people who have designed this or that knew what they were doing. But there are enough people that don't have a clue and _will_ fiddle around and then flame all kind of mailing lists with requests for help cause they did it wrong. From arkanes at gmail.com Tue Jan 30 11:25:57 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 30 Jan 2007 10:25:57 -0600 Subject: message handling in Python / wxPython In-Reply-To: <5fe216230701300113i4422bae8g97021e07361bfc2b@mail.gmail.com> References: <5fe216230701300113i4422bae8g97021e07361bfc2b@mail.gmail.com> Message-ID: <4866bea60701300825h6ae3d0aejcdb7228bd3f362a3@mail.gmail.com> On 1/30/07, murali iyengar wrote: > hi, > i have basic knowledge of python and wxPython... now i need to know about > message handling in python/wxPython? > > could anybody pls help me by giving some info on how to handle (in Python), > 'the user defined messages' posted from VC++, i dont know how to handle > messaes in python. > > Thanks and Regards, > Murali M.S > -- You need to override the WndProc at the C level in order to catch these. As it happens, there is a page on the wxPyWiki about this exact topic: http://wiki.wxpython.org/index.cgi/HookingTheWndProc From paul.sijben at xs4all.nl Wed Jan 10 06:42:01 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 12:42:01 +0100 Subject: maximum number of threads In-Reply-To: References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> <7.0.1.0.0.20070110064655.0508d0a0@yahoo.com.ar> Message-ID: <45A4D109.809@xs4all.nl> Felipe Almeida Lessa wrote: > Maybe Stackless could help the OP? > http://www.stackless.com/ > thanks I will look into it! From python at hope.cz Fri Jan 12 05:06:41 2007 From: python at hope.cz (Lad) Date: 12 Jan 2007 02:06:41 -0800 Subject: How to run external program? In-Reply-To: References: <1168594577.397453.320380@a75g2000cwd.googlegroups.com> Message-ID: <1168596401.191648.79440@38g2000cwa.googlegroups.com> Gary Herron wrote: > Lad wrote: > > How can I run external program from Python? > > I use Python with XP > > Thank you for help > > LB > > > > > The subprocess module is what you want for this. > > It's got ways of running external executables as separate subprocesses, > and interacting with the subprocess and both its input and output. > Gary , Thank you for your reply. I use os.popen3 but it does not work properly for me all the time. Here is a part of my Python program I use an external program ( here mpeg.exe) for converting sourcefile into targetfile ###########... ... ... mpeg = "mpeg.exe -i %s codec mp3 -s 320x240 %s" % (sourcefile, targetfile) stdin, stdout, stderr = os.popen3(mpeg) mpegresult = stdout.read() mpegerrors = stderr.read() stdin.close(); stdout.close(); stderr.close() print ffmpegerrors print ffmpegresult ######### It works if the sourcefile is small but if it is large( 30MB) it does NOT work.It hangs or the file is not converted in full. Any advice how I should change the program? Thank you. L. From gheissenberger at gmail.com Thu Jan 11 16:27:39 2007 From: gheissenberger at gmail.com (gheissenberger at gmail.com) Date: 11 Jan 2007 13:27:39 -0800 Subject: Python nuube needs Unicode help Message-ID: <1168550858.233814.292900@p59g2000hsd.googlegroups.com> HELP! Guy who was here before me wrote a script to parse files in Python. Includes line: print u where u is a line from a file we are parsing. However, we have started recieving data from Brazil. If I open file to parse in VI, looks like: References: Message-ID: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> On 24 Jan 2007 18:21:38 GMT, Nick Maclaren wrote: > > In article , > "Chris Mellon" writes: > |> > |> > |> > |> Does anyone have any conclusive evidence that python threads/locks are > |> > |> safe or unsafe? > |> > > |> > Unsafe. They are built on top of unsafe primitives (POSIX, Microsoft > |> > etc.) Python will shield you from some problems, but not all. > |> > > |> > There is precious little that you can do, because the root cause is > |> > that the standards and specifications are hopelessly flawed. > |> > |> This is sufficiently inaccurate that I would call it FUD. Using > |> threads from Python, as from any other language, requires knowledge of > |> the tradeoffs and limitations of threading, but claiming that their > |> usage is *inherently* unsafe isn't true. It is almost certain that > |> your code and locking are flawed, not that the threads underneath you > |> are buggy. > > I suggest that you find out rather more about the ill-definition of > POSIX threading memory model, to name one of the better documented > aspects. A Web search should provide you with more information on > the ghastly mess than any sane person wants to know. > > And that is only one of many aspects :-( > I'm aware of the issues with the POSIX threading model. I still stand by my statement - bringing up the problems with the provability of correctness in the POSIX model amounts to FUD in a discussion of actual problems with actual code. Logic and programming errors in user code are far more likely to be the cause of random errors in a threaded program than theoretical (I've never come across a case in practice) issues with the POSIX standard. Emphasizing this means that people will tend to ignore bugs as being "the fault of POSIX" rather than either auditing their code more carefully, or avoiding threads entirely (the second being what I suspect your goal is). As a last case, I should point out that while the POSIX memory model can't be proven safe, concrete implementations do not necessarily suffer from this problem. From sjdevnull at yahoo.com Tue Jan 9 05:55:07 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 9 Jan 2007 02:55:07 -0800 Subject: General Question About Python In-Reply-To: <1168254451.098796.144790@42g2000cwt.googlegroups.com> References: <1168254451.098796.144790@42g2000cwt.googlegroups.com> Message-ID: <1168340107.053008.67530@s34g2000cwa.googlegroups.com> Enteng wrote: > To those who program in python, what programs do you do? Some Unix TCP servers, some data-driven command line apps, and some web stuff. > Also what community projects are you involved in(OSS probably)? None that are Python-based, aside from the occasional patch to support new Python features in Vim or keep it working with newer versions. > Will mastering the language land me a job? Maybe. My last 3 jobs have been for people with experience in C and Python, or with substantial programming experience and a willingness to learn C and Python. From __peter__ at web.de Sun Jan 14 09:33:58 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 14 Jan 2007 15:33:58 +0100 Subject: Tkinter code (with pmw) executing to soon please help References: <1168746063.322340.10410@l53g2000cwa.googlegroups.com> <45a9ad0a$1@nntp0.pdx.net> <1168760210.636485.205020@a75g2000cwd.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > Scott David Daniels wrote: >> Gabriel Genellina wrote: >> >... So `callback` should return a function, like this: >> > >> > def callback(text): >> > def handler(event): >> > print text >> > >> >> Even better than that: >> def callback(text): >> def handler(event): >> print text >> return handler >> >> Otherwise callback returns the spectacularly un-useful value None. > C:\dex_tracker\csdlist.py bay-at-night.csd > Traceback (most recent call last): > File "C:\dex_tracker\csdlist.py", line 58, in > root.mainloop() > File "C:\Python25\lib\lib-tk\Tkinter.py", line 1023, in mainloop > self.tk.mainloop(n) > File "../../..\Pmw\Pmw_1_2\lib\PmwBase.py", line 1751, in __call__ > File "../../..\Pmw\Pmw_1_2\lib\PmwBase.py", line 1777, in _reporterror > TypeError: unsupported operand type(s) for +: 'type' and 'str' > Script terminated. > > It doesn't like the return handler part of it. Probably because a Tkinter.Button command callback doesn't accept any arguments. Try def callback(text): def handler(): print text return handler Note that 'make_callback' would be a better name than 'callback' because the function 'callback' actually creates the callback (called 'handler'). Peter From steven.bethard at gmail.com Thu Jan 4 13:13:23 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 04 Jan 2007 11:13:23 -0700 Subject: When argparse will be in the python standard installation In-Reply-To: <459CBAC8.9060007@v.loewis.de> References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> <459C008D.5040404@v.loewis.de> <459CBAC8.9060007@v.loewis.de> Message-ID: <64mdnTE_-5Ff3gDYnZ2dnUVZ_q6vnZ2d@comcast.com> Martin v. L?wis wrote: > Steven Bethard schrieb: >> If someone has an idea how to include argparse features into optparse, >> I'm certainly all for it. But I tried and failed to do this myself, so I >> don't know how to go about it. > > It's not necessary that the implementation is retained, only that the > interface is preserved. So if you can come up with an implementation > that supports all optparse applications, and adds the additional > features, your implementation could replace the current optparse. > If you need to make incompatible changes, it would be best if you > could produce a list of such changes, so that optparse users can > review them to find out whether they are affected. FWIW, here's a short list of issues that could be easily addressed: * alias ArgumentParser to OptionParser * alias add_argument to add_option * alias Values to Namespace * alias OptionError and OptionValueError to ArgumentError * alias add_help= keyword argument of ArgumentParser to add_help_option= * alias namespace= keyword argument of parse_args to options= * add the has_option, get_option and remove_option methods * add the set_conflict_handler method * add the destroy method * add the set_usage method * add the string names for types (e.g. "string", "str", "int", etc.) as aliases to the type objects (argparse already has a type registry for exactly these kinds of things) Some slightly harder issues: * ArgumentParser.parse_args returns a single namespace object, not an (options, args) tuple, since argparse handles positional arguments. This could probably be addressed by adding an __iter__ method to the Namespace object which would return (self, []) * argparse uses standard string formatting specifiers, e.g. %(default)s and %(prog)s instead of optparse's %default and %prog. It could probably be hacked to support both though. * argparse doesn't support {enable,disable}_interspersed_args() because their primary use case was for handling sub-parsers, which argparse handles through the add_subparsers method. It could probably be hacked to work though I guess. And the issues that I don't see any good way to address: * argparse makes the default value for a "store_true" action False, and the default value for a "store_false" action True. This is what users expect, but different from optparse where the default is always None. * the ArgumentParser constructor doesn't accept the option_list=, option_class= or formatter= keyword arguments. Since argparse uses Action subclasses instead of a single Option class, the former two don't make much sense. And formatter= has been replaced with formatter_class= where the API of the formatter was dramatically changed. (That said, the formatter API is undocumented in both optparse and argparse.) * the choices argument is now checked *after* arguments have been type-converted. This is intentional, so that you can specify, say xrange(100) instead of ["0", "1", "2", "3", ... "99"]. There is also no "choices" type anymore since any action can also specify their choices. * argparse doesn't support ``callback`` actions because the same effects are better handled by defining a simple type-checking function and passing it as the type= keyword argument, or by subclassing argparse.Action and passing this as the action= keyword argument. I could probably add callback actions by creating an appropriate Action subclass and registering it. However, any code relying on parser.{largs,rargs,values} would break because the parsing algorithm is completely different in argparse. * The `Extending optparse`_ section in the docs is pretty much completely inapplicable. One of the major goals of argparse was to get rid of the need to hack class attributes like TYPES, STORE_ACTIONS, etc. Instead, these things are handled by defining simple string-to-object functions that are passed to type= or by defining appropriate subclasses of argparse.Action which are passed to action=. Trying to support these sorts of things would be nearly impossible. I guess I don't know how to proceed from here. I'm reluctant to start adding the code necessary to support even the easily solved issues when the issues that I don't know how to solve seem like they could be deal breakers. STeVe .. _Extending optparse: http://docs.python.org/lib/optparse-extending-optparse.html From dummy at dummy.nl Fri Jan 19 12:22:11 2007 From: dummy at dummy.nl (Cecil Westerhof) Date: Fri, 19 Jan 2007 18:22:11 +0100 Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> <5q01r2p4hnnrm1b8fh5dul6qmoc1lsf4re@4ax.com> Message-ID: <45b0fe43$0$333$e4fe514c@news.xs4all.nl> Tim Roberts wrote: > Cecil Westerhof wrote: >> >>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse >>I can not time the time used to import time, but os and sys do not take >>more as a millisecond. My script itself takes 3 or 4 milliseconds. But >>importing cgi takes 95 milliseconds. (This is on my test system a PII 300 >>MHz. Is there a way to make this more fast? The import off cgi makes the >>script at least 20 times as slow. Something like mod-python is not a >>possibility. I could use it on my test machine, but not at the osting >>provider. > > Realistically, do you plan to support more than a few dozen requests per > minute? If not, then it doesn't matter at all. The script launch > overhead is an insignificant part of the user's browser experience. Not at the moment. The application is in alpha, so it is mostly a few testers. At the moment it is going life I want to have another provider. So I have a little time to search for another provider and select 'the best' framework. ;-} From ask at me Wed Jan 10 23:11:28 2007 From: ask at me (alf) Date: Wed, 10 Jan 2007 22:11:28 -0600 Subject: globals accros modules Message-ID: Hi, executing main.py reulsts in following: [andy at localhost andy]$ python main.py Traceback (most recent call last): File "main.py", line 4, in ? amodule.f() File "/raid/home/andy/amodule.py", line 3, in f print a NameError: global name 'a' is not defined How can I have global globals without cyclical import? A. -------------------- amodule.py: def f(): global a print a -------------------- main.py: import amodule a=1 amodule.f() From gagsl-py at yahoo.com.ar Fri Jan 26 23:03:50 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Jan 2007 01:03:50 -0300 Subject: instancemethod References: <45b51298$0$8289$426a74cc@news.free.fr><45ba2b72$0$3007$426a34cc@news.free.fr> Message-ID: "Steven D'Aprano" escribi? en el mensaje news:pan.2007.01.27.00.07.59.387012 at REMOVE.THIS.cybersource.com.au... > On Fri, 26 Jan 2007 17:25:37 +0100, Bruno Desthuilliers wrote: >>> def __del__(self): >>> try: >>> self.close() >>> finally: >>> pass >>> except: >>> pass >> >> The finally clause is useless here. > > In principle, closing a file could raise an exception. I've never seen it > happen, but it could. From the Linux man pages: [...] > I assume that the same will apply in Python. Note that he said that the *finally* clause were useless (and I'd say so, too), not the *except* clause. And yes, in Python it is checked - when the close method was called explicitely, an exception is raised; when called when the object is garbage collected, a message is printed on sys.stderr > It has to be said, however, that the error recovery shown ("pass") is > fairly pointless :-) Only supresses the message on sys.stderr - exceptions raised on __del__ are never propagated. -- Gabriel Genellina From edquichan at yahoo.com Thu Jan 18 15:38:08 2007 From: edquichan at yahoo.com (EdG) Date: 18 Jan 2007 12:38:08 -0800 Subject: Traversing the properties of a Class In-Reply-To: References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> Message-ID: <1169152688.921153.26150@m58g2000cwm.googlegroups.com> This works great. I have one more question. Now that I have the name of the property, how do I get it's value? I want to print '%s = %s' % (attr,theattributesvalue) Thanks. Neil Cerutti wrote: > On 2007-01-18, EdG wrote: > > For debugging purposes, I would like to traverse the class > > listing out all the properties. > > This is the first thing that came to mind. > > def show_properties(cls): > for attr in dir(cls): > if isinstance(getattr(cls, attr), property): > print attr > > -- > Neil Cerutti > > -- > Posted via a free Usenet account from http://www.teranews.com From pkyoung at gmail.com Wed Jan 24 02:24:12 2007 From: pkyoung at gmail.com (auditory) Date: Wed, 24 Jan 2007 16:24:12 +0900 Subject: numpy or _numpy or Numeric? Message-ID: I am a newbie here I am trying to read "space separated floating point data" from file I read about csv module by searching this group, but I couldn't read space separated values with csv. (which may be matter of course..) I also read about numpy.fromfile(file, sep=' ') which i can use. but on my machine(ubuntu linux) numpy is unknown module, which I didn't install by myself. While trying to install numpy accroding to its homepage. (http://numpy.scipy.org/numpydoc/numdoc.htm). i am quite confused. it's talking about the Numerical Python, and it says to test whether it is installed or not, try import Numeric instead of numpy. I got Nurmeric modules and as a matter of fact i got a file named '_numpy.so' in lib directory. I can import _numpy but _numpy does not have 'fromfile' method My question is: 1. Do i need to install numpy module? 2. Then Is it different from Numeric module? 3. Then where can i get it? 4. Or what is general way to read 'space separated values' from file? Thanks in advance. From ptmcg at austin.rr._bogus_.com Thu Jan 11 09:14:05 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 11 Jan 2007 08:14:05 -0600 Subject: Reloading the already imported module References: <1168519894.160024.70930@o58g2000hsb.googlegroups.com> Message-ID: <45a6462c$0$16655$4c368faf@roadrunner.com> wrote in message news:1168519894.160024.70930 at o58g2000hsb.googlegroups.com... > hi all, > i have following code > > > if > from SIPT.xml_param_mapping import MESSAGE_PARAMETER_MAPPING > else: > from SIPT.msg_param_mapping import MESSAGE_PARAMETER_MAPPING > > parameter_list = MESSAGE_PARAMETER_MAPPING ['ABC' ] > for parms in parameter_list: > parameter_list[parms][4] = 'EXPORT' > parameter_list[parms][5] = 'IMPORT' > > > After this the xml_param_mapping gets altered. this process is > repeated over couple of time. But every time i need to get a fresh > xml_param_mapping. So how to relaod the already imported module?? > Why not work with a copy of MESSAGE_PARAMETER_MAPPING['ABC'], and keep the original intact? Change: parameter_list = MESSAGE_PARAMETER_MAPPING ['ABC' ] to parameter_list = MESSAGE_PARAMETER_MAPPING ['ABC' ][:] Now no reimport is required. -- Paul From nocl123 at gmail.com Thu Jan 11 15:26:48 2007 From: nocl123 at gmail.com (nic) Date: 11 Jan 2007 12:26:48 -0800 Subject: os.popen() not executing command on windows xp In-Reply-To: <1168535370.211599.265250@p59g2000hsd.googlegroups.com> References: <1168508553.151827.261420@k58g2000hse.googlegroups.com> <1168509560.119819.78470@o58g2000hsb.googlegroups.com> <1168535370.211599.265250@p59g2000hsd.googlegroups.com> Message-ID: <1168547208.736198.295560@77g2000hsv.googlegroups.com> It appears os.popen() doesn't like full windows paths with spaces (e.g. "c:/program files") so I'm going to use the subprocess module. From aboudouvas at panafonet.gr Fri Jan 5 11:07:59 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 5 Jan 2007 08:07:59 -0800 Subject: program deployment In-Reply-To: <1168012877.398078.59120@s80g2000cwa.googlegroups.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> <1168012877.398078.59120@s80g2000cwa.googlegroups.com> Message-ID: <1168013279.634426.84110@s80g2000cwa.googlegroups.com> Ok, i got the point...Things are a little bit different on the other way of the fence (Microsoft way...) and so many of Python's elements are a little (at least) strange at first... But hey, thank you all! From beej at beej.us Tue Jan 30 02:26:33 2007 From: beej at beej.us (Beej) Date: 29 Jan 2007 23:26:33 -0800 Subject: Data structure and algorithms In-Reply-To: <1170107403.836795.211280@k78g2000cwa.googlegroups.com> References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> <1170095416.261460.157660@a34g2000cwb.googlegroups.com> <1170107403.836795.211280@k78g2000cwa.googlegroups.com> Message-ID: <1170141993.558572.88830@m58g2000cwm.googlegroups.com> On Jan 29, 1:50 pm, "azrael" wrote: > thanks guys. i see that there is no way then to go back to C to > satisfy my prof and get a grade Seconding what Dennis says below, it is totally possible to use Python for this. I didn't mean to discourage you from using Python--I just wanted to discourage you from trying to do it using the Python built-in list []. In fact, given the time constraints and your dislike of structs, you're likely going to rip your hair out trying to get it going in C. -Beej From daniele.varrazzo at gmail.com Thu Jan 18 06:38:37 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 18 Jan 2007 03:38:37 -0800 Subject: One more regular expressions question In-Reply-To: <1169113767.320500.71200@11g2000cwr.googlegroups.com> References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> Message-ID: <1169120317.437211.73660@m58g2000cwm.googlegroups.com> Victor Polukcht wrote: > I have a couple of strings like: > > Unassigned Number (1) 32 [...] > Interworking, unspecified (127) 5 > > I need to get: > Error code (value in brackets) - Value - Message. > > My actual problem is i can't get how to include space, comma, slash. Probably you have some escaping problem. The substitution: re.sub(r"^(.*)\s*\((\d+)\)\s+(\d+)", r'\2 - \3 - \1', row) does the required job (where "row" is one of your lines) To match a special character, such as "(", you need to escape it with a "\", because it has a special meaning in the regexp syntax. Because "\" is the escaping mechanism for Python strings too, you better use raw strings to specify the pattern. Other special character/groups matching patterns, such as "\s" to specify whitespaces, are documented, together with everything else you need, at http://docs.python.org/lib/re-syntax.html HTH Daniele From smusnmrNOSPAM at yahoo.com Fri Jan 5 09:24:49 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Fri, 5 Jan 2007 15:24:49 +0100 Subject: where is Microsoft Speech Object Library 5.1 option in PythonWin 2.5? Message-ID: Hi all, newbie question: I'd like to try speech synthesis with PythonWin 2.5. Problem ****** according to several instructions, such as found on http://surguy.net/articles/speechrecognition.xml and in a book on Python, I have to select Tools | COM MakePy Utility | Microsoft Speech Object Library 5.1, SDK 5.1, that is. However, in my Python 2.5/PythonWin 2.5 installation I find as only option "Microsoft Speech Object Library 5.0" to select. Unfortunately, 5.1 is the lowest SDK version I found on http://www.microsoft.com/downloads/details.aspx?FamilyId=5E86EC97-40A7-453F-B0EE-6583171B4530&displaylang=en#QuickInfoContainer Will this PythonWin's Tools | COM MakePy Utility for 5.0 work with SDK 5.1? Or will PythonWin's Tools | COM MakePy Utility be updated to SDK 5.1, once I have SDK 5.1 installed? Thanks, Siggi From postindex at gmail.com Sun Jan 14 01:16:28 2007 From: postindex at gmail.com (postindex at gmail.com) Date: 13 Jan 2007 22:16:28 -0800 Subject: Is it possible to get whole commandline include redirection.., etc In-Reply-To: References: <1168643505.949920.154470@a75g2000cwd.googlegroups.com> Message-ID: <1168755387.944792.133690@38g2000cwa.googlegroups.com> Thanks Steven. From ptmcg at austin.rr.com Tue Jan 23 19:03:44 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jan 2007 16:03:44 -0800 Subject: Simple Matrix class In-Reply-To: References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> Message-ID: <1169597024.006653.268440@v45g2000cwv.googlegroups.com> On Jan 23, 4:05 pm, Casey Hawthorne wrote: > Do you calcalate the matrix inversion, when you don't need to? > No, the inversion is only calculated on the first call to inverse(), and memoized so that subsequent calls return the cached value immediately. Since the Matrix class is mutable, the cache is invalidated if any of the matrix elements are updated. So after changing a matrix element, the inversion would be recalculated at the next call to inverse(). Hope that clears things up. You can also do your own experiments, including adding verbose logging to the memoizing decorators - an example is included in the source code. Also the footprint is quite small, just one Python source file, about 600-700 lines of code, and all Python, so 100% portable. -- Paul From huayang.xia at gmail.com Thu Jan 11 16:37:08 2007 From: huayang.xia at gmail.com (Huayang Xia) Date: 11 Jan 2007 13:37:08 -0800 Subject: How to modify object attribute by python C API Message-ID: <1168551428.114028.278940@77g2000hsv.googlegroups.com> I get a python object by running a class' constructor. Then I need to modify the instance's attribute just like obj.attr1.attr2 = 'a' if in python's term. PyObject* py_obj_attr1 = PyObject_GetAttrString(obj, "attr1"); PyObject_SetAttrString(py_obj_attr1, "attr2", PyString_FromString("a")); Py_DECREF(py_obj_attr1); The object py_obj_attr1 is said to be a "New reference". It's confusing, does it refer to the same object as "obj.attr1" in python's term? So that the above code equals: obj.attr1.attr2 = 'a' in python's term. I From martin at v.loewis.de Sun Jan 21 13:54:09 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Jan 2007 19:54:09 +0100 Subject: A solution to the MSVCRT vs MSVCR71 problem? In-Reply-To: References: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> <45B3267A.80605@v.loewis.de> Message-ID: <45B3B6D1.2010400@v.loewis.de> Gabriel Genellina schrieb: > That's a good thing - but is this just by accident, or is documented > somewhere? It's documented somewhere (although I can't find the documentation right now - it explains how you can link object files from a static library compiled with an older compiler version against a new version of the C library). > I remember that I tried something like that in the past, and failed. > (Perhaps earlier versions where not fully backwards compatible - or I > didn't try hard enough that time). It's been that way for ages, atleast since they started to support 32-bit code. So if you had problems, they might have had a different source. It's a different thing for the C++ libraries, though. Regards, Martin From ghirai at ghirai.com Thu Jan 18 11:20:28 2007 From: ghirai at ghirai.com (Ghirai) Date: Thu, 18 Jan 2007 18:20:28 +0200 Subject: Login Form Message-ID: <446678961.20070118182028@ghirai.com> Hello python-list, I need to make a login form, if possible without cookies. Can anyone point me in the right direction? Or are there any examples? Thanks. -- Best regards, Ghirai. From martin at v.loewis.de Tue Jan 9 17:45:51 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 09 Jan 2007 23:45:51 +0100 Subject: distutils and ctypes In-Reply-To: References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> <45A3FF17.2070509@v.loewis.de> Message-ID: <45a41b1f$0$19653$9b622d9e@news.freenet.de> Robert Kern schrieb: >> Not sure it's stupid, but I wonder why you want to use ctypes. What's >> wrong with extension modules? > > What's wrong with ctypes? They're both valid, useful approaches to connect to C > libraries. See the original posting. Distutils doesn't support building arbitrary shared libraries, but does support building extension modules. Furthermore, extension modules are more type-safe and more expressive than loading shared libraries through ctypes. IMO, you may consider using ctypes as a last resort - if you have the chance for a well-engineered solution, write a compiled wrapper. Regards, Martin From steve at REMOVE.THIS.cybersource.com.au Sat Jan 6 03:18:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 06 Jan 2007 19:18:46 +1100 Subject: Encoding / decoding strings References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> <1168010144.000928.131920@42g2000cwt.googlegroups.com> <1168018757.397170.216870@11g2000cwr.googlegroups.com> Message-ID: On Fri, 05 Jan 2007 09:39:17 -0800, oliver at obeattie.com wrote: > Basically, what I am trying to do is display all comments by a > specified user on the website. As the only thing which has =always= > been used to identify users which never changes is their e-mail > addresses, What are you talking about? I've changed my email address a dozen times on many mailing lists and websites. I'm still me. > this is the only thing which I can use. Obviously, I can't > display this e-mail address though. There is nothing obvious about that all all. Email addresses are usually public. But okay, your users aren't expecting their email address to be public. Why not do what many jails do with prisoners? Everybody gets a unique number. In your case, just walk through the database of users, giving each one a number. You can't reverse engineer the email address from the number without breaking into the database. Then your website can refer to them as "Prisoner 123456789" which should be good for a few laughs. Or simply take the username part of the address. So "fred at hotmail.com" would become "fred". Then "fred at gmail.com" would become "fred1", and so forth. Obviously you don't try to generate the username from the email address every single time, you do it once, and keep a list of used usernames so that when "fred at yahoo.com" joins you know "fred" and "fred1" are both used and he has to be "fred2". md5 checksums can now be broken, in both directions: it is relatively easy to generate collisions, and there are reverse md5 lookup tables. I imagine your use of md5 would be especially easy to attack, since the attacker knows that the string is an email address. -- Steven. From pavlovevidence at gmail.com Sun Jan 21 21:42:32 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 21 Jan 2007 18:42:32 -0800 Subject: Reading Fortran Data In-Reply-To: <1169429808.910298.10240@11g2000cwr.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> <1169424273.929396.133880@m58g2000cwm.googlegroups.com> <1169429808.910298.10240@11g2000cwr.googlegroups.com> Message-ID: <1169433752.130978.133210@a75g2000cwd.googlegroups.com> Beliavsky wrote: > Carl Banks wrote: > > > > > > WRITE(90,*) nfault,npoint > > > > Fortran writes this as two arbitrary integers separated by a space. > > I wrote a paragraph in my reply explaining why this is wrong. It's a safe assumption for a line of two integers. It might not exactly produce what a Fortran program would, but it would work in a read statement. > A Fortran > list-directed write can print results in an almost arbitrary format, > depending on the compiler. Many compilers will separate integers by > several spaces, not just one, and they could use commas instead of > spaces if they wanted. 1. Hardly any compiler will produce a line of two integers, or reals, that another compiler couldn't read back. 2. The number of spaces separating the numbers isn't important when reading back free-form data. 3. Fear that a Fortran compiler might use commas or wrap lines at ten columns or whatever, because it's not based on a standard, is misguided paranoia. > The number of items printed before a new line is > started is also compiler-dependent. For more control, one uses a > formatted write, for example > > write (90,"(2(1x,i0))") nfault,npoint I think it's just more work to guard against something isn't very relevant in practice. Carl Banks From jstroud at mbi.ucla.edu Tue Jan 23 17:11:19 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 23 Jan 2007 14:11:19 -0800 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: Message-ID: Daniel Jonsson wrote: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! > > Daniel You may also want to think about licensing issues. I think the license for QT is more restrictive than wx. Also, you might want to consider Tkinter. From gandalf at designaproduct.biz Fri Jan 5 14:19:33 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 20:19:33 +0100 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: <459EA4C5.6090808@designaproduct.biz> Stef Mientki wrote: > Not sure I wrote the subject line correct, > but the examples might explain if not clear > > > *** first attempt *** > class pin: > def __init__ (self): > self.Name = 'Unknown Pin' > > aap = pin() # create an instance > aap.Name = 'aap' # set it's name > print aap.Name # print it's name > > # but why should I set it's name ?? > print 'aap' # I can just as well print a constant string !! > # (ok there will be an extra check) > If you are trying to determine the name of your object, then you do not know what 'name' and 'object' means in Python. In this case, I recommend you this: http://effbot.org/zone/python-objects.htm In particular, pay attention to that objects can have zero or more names. This is how you can create three unnamed objects: L = [pin(),pin(),pin(),] This is how you can bind three names to the same object: p1 = p2 = p3 = pin() Maybe I did not understand you question. Laszlo From jmike at alum.mit.edu Fri Jan 12 09:51:29 2007 From: jmike at alum.mit.edu (jmike at alum.mit.edu) Date: 12 Jan 2007 06:51:29 -0800 Subject: Command line arguments on Vista In-Reply-To: <1168613362.406648.304720@11g2000cwr.googlegroups.com> References: <1168613362.406648.304720@11g2000cwr.googlegroups.com> Message-ID: <1168613488.896113.326290@l53g2000cwa.googlegroups.com> By the way, note that if I say (on Vista) python printargs.py booga -a wooga I get the desired output: > there are 4 args > arg: printargs.py > arg: booga > arg: -a > arg: wooga So the quesiton still stands, what's up with that? Thanks, --JMike From gagsl-py at yahoo.com.ar Tue Jan 30 12:39:28 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 14:39:28 -0300 Subject: Help me understand this References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> <1170146755.446429.90720@v45g2000cwv.googlegroups.com> Message-ID: En Tue, 30 Jan 2007 06:34:01 -0300, Beej escribi?: > But here's one I still don't get: > >>>> type(2) > >>>> type((2)) > >>>> (2).__add__(1) > 3 >>>> 2.__add__(1) > File "", line 1 > 2.__add__(1) > ^ > SyntaxError: invalid syntax It appears to be a bug, either in the grammar implementation, or in the grammar documentation. These are the relevant rules: attributeref ::= primary "." identifier primary ::= atom | attributeref | subscription | slicing | call atom ::= identifier | literal | enclosure literal ::= stringliteral | integer | longinteger | floatnumber | imagnumber An integer is a primary so 2.__add(1) should be valid. -- Gabriel Genellina From bearophileHUGS at lycos.com Wed Jan 31 07:52:31 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 31 Jan 2007 04:52:31 -0800 Subject: 'First class' Relationships Message-ID: <1170247951.132373.227800@v45g2000cwv.googlegroups.com> Currently reading an article, "First Class Relationships in an Object- oriented Language", by Gavin Bierman and Alisdair Wren: http://homepages.inf.ed.ac.uk/wadler/fool/program/final/4/4_Paper.pdf Found in the "Lambda the Ultimate" blog: http://lambda-the-ultimate.org/node/2013 Maybe it can be done in Python too, with a metaclass "Relationship". The relation can probably be added dynamically to an object/class. Some typecheek can be added too, if necessary. Bye, bearophile From jstroud at mbi.ucla.edu Mon Jan 22 01:10:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 21 Jan 2007 22:10:17 -0800 Subject: Is any python like linux shell? In-Reply-To: <1169398326.510530.180860@51g2000cwl.googlegroups.com> References: <1169398326.510530.180860@51g2000cwl.googlegroups.com> Message-ID: Frank Potter wrote: > I learned some python in windows. > And now I've turned to linux. > I read a book and it teaches how to write shell script with bash, > but I don't feel like the grammar of bash. > Since I know about python, > I want to get a linux shell which use python grammar. > I searched by google and I found pysh, which is not maintained any > more. > There's another script named pyshell, which is not likely what I'm > searching for. > So, will somebody please tell me if there are any python like shells > for linux? > Best is to do simple things (ls, mv, rm, cp) via bash or tcsh and to use python for things of any greater complexity (even slightly more complex). My strongest advice would be to let go of the idea of "shell scripting" altogether and begin to write programs built from libraries to solve your problems. The mere act of beginning to write a shell script (in, say, bash) will tie you to that "language", even when you realize your task was much more complex than you had originally imagined. It has happened to me time and time again. James From nospam at nospam.net Sun Jan 28 12:38:00 2007 From: nospam at nospam.net (Andrew) Date: Sun, 28 Jan 2007 09:38:00 -0800 Subject: socket.inet_ntop, and pton question Message-ID: <12rpns1tkp0e34@corp.supernews.com> Hi Are these functions (inet_ntop(), inet_pton()) from the socket library supported on Windows. If not is there an equivalent for them using Windows Ive seen mention of people creating their own in order to use them Appreciate the help ty From wbornor at gmail.com Thu Jan 18 14:25:59 2007 From: wbornor at gmail.com (dubs) Date: 18 Jan 2007 11:25:59 -0800 Subject: spidering script In-Reply-To: References: <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d@fdn.com> Message-ID: <1169148359.297521.239630@v45g2000cwv.googlegroups.com> Check out the quick start section in the documentation at Beautiful Soup http://www.crummy.com/software/BeautifulSoup/ Wes Jonathan Curran wrote: > On Thursday 18 January 2007 11:57, David Waizer wrote: > > Hello.. > > > > I'm looking for a script (perl, python, sh...)or program (such as wget) > > that will help me get a list of ALL the links on a website. > > > > For example ./magicscript.pl www.yahoo.com and outputs it to a file, it > > would be kind of like a spidering software.. > > > > Any suggestions would be appreciated. > > > > David > > David, this is a touchy topic but whatever :P Look into sgmllib, and you can > filter on the "A" tag. The book 'Dive Into Python' covers it quite nicely: > http://www.diveintopython.org/html_processing/index.html > > Jonathan From gagsl-py at yahoo.com.ar Tue Jan 30 18:23:07 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 20:23:07 -0300 Subject: PythonCard References: <1170193549.583822.156450@k78g2000cwa.googlegroups.com> Message-ID: En Tue, 30 Jan 2007 18:45:49 -0300, Tequila escribi?: > I'm having some trouble starting PythonCard on my PC. Usually it's a good idea at least to read the installation instructions :) http://pythoncard.sourceforge.net/windows_installation.html -- Gabriel Genellina From arkanes at gmail.com Wed Jan 17 10:54:41 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 17 Jan 2007 09:54:41 -0600 Subject: Newbie: Capture traceback message to string? In-Reply-To: <516tpnF1ic39jU1@mid.individual.net> References: <516tpnF1ic39jU1@mid.individual.net> Message-ID: <4866bea60701170754i50d6658fhf93af114fe0bee20@mail.gmail.com> On 17 Jan 2007 15:31:03 GMT, Thomas Guettler wrote: > Sean Schertell wrote: > > > Hello! > > > > I'm new to Python and this is my first post to the list. > > > > I'm trying to simply capture exception text to a few strings which > > can be passed to a PSP page to display a pretty error message. The > > problem is that I just can't seem to figure out how to get the basic > > components of the traceback message into strings. Here's what I want > > to do: > > > > > # http://www.thomas-guettler.de/vortraege/python/beispiele.py.txt > def foo(): > raise("Das ist eine Exception") > try: > foo() > except: > import traceback > import cStringIO > (exc_type, exc_value, tb) = sys.exc_info() > exc_file = cStringIO.StringIO() > traceback.print_exception(exc_type, exc_value, tb, file=exc_file) > exc_string=exc_file.getvalue() > print exc_string > This is a lot of extra work. traceback.format_exc is much simpler. From klaus at seistrup.dk Sat Jan 6 14:51:06 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 6 Jan 2007 19:51:06 +0000 (UTC) Subject: nntplib downloads content with extra linebreaks References: <1168110213.436860@sj-nntpcache-1.cisco.com> <1168112276.194982@sj-nntpcache-1.cisco.com> Message-ID: Rweth wrote: > for aline in buf: > bufHeal.append(aline.replace('\r\n', '\n')) What does one single aline look like? > s.body(id,afile) Does the 'afile' contain a filename or a filepointer? Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From richard.charts at gmail.com Wed Jan 3 11:18:47 2007 From: richard.charts at gmail.com (Richard Charts) Date: 3 Jan 2007 08:18:47 -0800 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: References: Message-ID: <1167841127.052786.175470@a3g2000cwd.googlegroups.com> mm wrote: > Is there a Perl to Python converter? > Or in general: a XY to Python converter? > > Is see, that Python is much better then Perl anyway. > But for beginners, they whant to konw how is this done with Python etc. > > Sure, there are some docus out there in the internet. But a converter? I don't know of any converter, but I have seen a number of tutorials that show how to do OO things in both perl and python for example. Avi Kak of Purdue U. has one such tutorial. When I took his class, he had a large package of notes that he said was the basis for his next book. It doesn't look like he ever got around to publishing that one. However, if you google his homepage, he does have at last one tutorial posted for Perl vs. Python. From steve at REMOVEME.cybersource.com.au Wed Jan 31 01:52:12 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 31 Jan 2007 17:52:12 +1100 Subject: how to "free" an object/var ? References: Message-ID: On Tue, 30 Jan 2007 15:48:37 -0800, James Stroud wrote: > Stef Mientki wrote: >> If I create a large array of data or class, >> how do I destroy it (when not needed anymore) ? >> >> Assign it to an empty list ? >> >> thanks, >> Stef Mientki > > It will be gc'd when you leave the scope or you can call del() to > explicitly get rid of the object if its existence bothers you. That is not quite correct. big_list = ["data"]*1000000 another_reference = big_list del big_list At this point, the list of one million "data" strings still exists. del big_list doesn't delete the list object, it removes the name "big_list". Then, only if the list has a reference count of zero, Python will dispose of the object and free the memory (if your OS allows that). If there are still references to it, like "another_reference" above, it will not be disposed of. As far as I know there is no way to force the deletion of an object even if it is in use. This is a Good Thing. -- Steven D'Aprano From wise at hyperformix.com Thu Jan 11 19:00:05 2007 From: wise at hyperformix.com (Tim) Date: 11 Jan 2007 16:00:05 -0800 Subject: py2exe: zipfile=None raised ImportError In-Reply-To: <1168543966.212663.141840@i56g2000hsf.googlegroups.com> References: <1168543966.212663.141840@i56g2000hsf.googlegroups.com> Message-ID: <1168560005.452340.249680@k58g2000hse.googlegroups.com> I see the py2exe mail list posts to this group... I think I have a handle on the problem: After I build the exe, I rename it. The renamed exe is the one that raises the error. The original exe works fine. -- Tim From martin at v.loewis.de Sun Jan 7 14:32:38 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 07 Jan 2007 20:32:38 +0100 Subject: Newbie XML SAX Parsing: How do I ignore an invalid token? In-Reply-To: <1168194830.741912.300290@51g2000cwl.googlegroups.com> References: <1168033818.692201.183790@11g2000cwr.googlegroups.com> <1168054226.290465.325910@s34g2000cwa.googlegroups.com> <459f5e14$0$17107$9b622d9e@news.freenet.de> <1168194830.741912.300290@51g2000cwl.googlegroups.com> Message-ID: <45A14AD6.1080002@v.loewis.de> scott at crybabymaternity.com schrieb: > Is there a Pythonic way to read the file and identify any illegal XML > characters so I can strip them out? this would keep my program more > flexible - if the vendor is going to allow one illegal character in > their document, there's no way of knowing if another one will pop up > later. Notice that you are talking about bytes here, not characters. It is inherently difficult to determine invalid bytes - you first have to determine the encoding, then (mentally) decode, and then find out whether there are any invalid characters. The invalid XML characters can be found in http://www.w3.org/TR/2006/REC-xml-20060816/#charsets So invalid characters are #x0 .. #x8, #xB, #xC, #xE .. #x1F, #xD800 .. #xDFFF, #xFFFE, #xFFFF. If you restrict attention to only the invalid characters below #x20 (i.e. control characters), and also restrict attention to encodings that are strict ASCII supersets (ASCII, ISO-8859-x, UTF-8), you can filter out the invalid characters on the byte level. Otherwise, you have to decode, filter out on the character level, and then encode again. Neither approach will deal with bytes that are invalid wrt. the encoding. To filter out these bytes, I recommend to use str.translate. Make an identity table for the substitution, and put the bytes you want deleted into the delete table. Regards, Martin From wasadmin at optonline.net Tue Jan 30 16:45:49 2007 From: wasadmin at optonline.net (Tequila) Date: 30 Jan 2007 13:45:49 -0800 Subject: PythonCard Message-ID: <1170193549.583822.156450@k78g2000cwa.googlegroups.com> I'm having some trouble starting PythonCard on my PC. I've downloaded and ran python-2.5.msi to install Python on my machine. And PythonCard-0.8.2.win32.exe to install PythonCard. When I try to run the program I get the following error: ====================================== C:\Python25\Lib\site-packages\PythonCard\tools \codeEditor>codeEditor.py Traceback (most recent call last): File "C:\Python25\Lib\site-packages\PythonCard\tools\codeEditor \codeEditor.py", line 13, in from PythonCard import about, configuration, dialog, log, menu, model, resource, util File "C:\Python25\lib\site-packages\PythonCard\about.py", line 8, in import wx ImportError: No module named wx ====================================== Does anyone know what the problem might be? Thanks, Tequila From viscanti at gmail.com Tue Jan 16 09:41:51 2007 From: viscanti at gmail.com (viscanti at gmail.com) Date: 16 Jan 2007 06:41:51 -0800 Subject: urrlib2 multithreading error Message-ID: <1168958510.834175.184730@a75g2000cwd.googlegroups.com> Hi, I'm using urllib2 to retrieve some data usign http in a multithreaded application. Here's a piece of code: req = urllib2.Request(url, txdata, txheaders) opener = urllib2.build_opener() opener.addheaders = [('User-agent', user_agent)] request = opener.open(req) data = request.read(1024) I'm trying to read only the first 1024 bytes to retrieve http headers (if is html then I will retrieve the entire page). When I use it on a single thread everything goes ok, when I create multiple threads the execution halts and the program terminates, just before the last line (when I execute the request.read(.) ). Obviously I tried to catch the exception but it doesn't work, the interpreter exits without any exception or message. How can I solve this? lv From paddy3118 at netscape.net Mon Jan 22 21:26:24 2007 From: paddy3118 at netscape.net (Paddy) Date: 22 Jan 2007 18:26:24 -0800 Subject: Best way to document Python code... In-Reply-To: <1169492869.101706.253620@38g2000cwa.googlegroups.com> References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: <1169519184.910635.197820@38g2000cwa.googlegroups.com> Scott Huey wrote: > I am working on a Python module and I would like to prepare some API > documentaiton. I managed to find epydoc after some searching online. > > Is there a standard way to document the API for Python modules? Is > epydoc the best way to go if there is no standard? Are there other ways > to document a Python API? > > Thanks, > > Scott Huey To add to the other replies: try adding a few doctests to your docstrings. They can help show typical use cases even if you don't use them for 'testing' - and you can automatically keep the use cases up-to-date. http://en.wikipedia.org/wiki/Doctest - Paddy. From Eric_Dexter at msn.com Sat Jan 13 22:41:06 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 13 Jan 2007 19:41:06 -0800 Subject: Tkinter code (with pmw) executing to soon please help Message-ID: <1168746063.322340.10410@l53g2000cwa.googlegroups.com> Instead of creating my buttons and waiting for me to press them to execute they are executing when I create them and won't do my callback when I press them.. thanks for any help in advance button[num] = Tkinter.Button(frame,text = returnstring, command=callback(returnstring))# this line executes on creation my output on startup is (should output when I choose an option) 1 String pad 10 Chorus 25 Reverb 30 Mixer The buttons do label correctly. title = 'csd instrument list' # Import Pmw from this directory tree. import sys sys.path[:0] = ['../../..'] import Tkinter import Pmw import csoundroutines class Demo: def __init__(self, parent): frame = Tkinter.Frame(parent) frame.pack(fill = 'both', expand = 1) button = {} instr = [[]] instr = csoundroutines.csdInstrumentList2(sys.argv[1]) num = 0 #instr_number buttonBox = Pmw.ButtonBox(parent) for i in range(0, len(instr.instrnum)): num += 1 returnstring = instr.instrnum[i] +' '+ str(instr.comments[i]) #printstring = zz + x[num] button[num] = Tkinter.Button(frame,text = returnstring, command=callback(returnstring))#kinter.Buttonstr(x[0]) + ' ' + x[1])# + comments) button[num].pack() #returnstring = zz button[num].grid(column=num, row = 0)#,command=callback(returnstring)) #button[num].pack() frame.grid_rowconfigure(3, weight=1) frame.grid_columnconfigure(3, weight=1) frame.pack() def callback(text): print text ###################################################################### # Create demo in root window for testing. if __name__ == '__main__': global filename filename = (sys.argv[1]) root = Tkinter.Tk() Pmw.initialise(root) root.title(title) exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy) exitButton.pack(side = 'bottom') widget = Demo(root) root.mainloop() http://www.dexrow.com From skip at pobox.com Thu Jan 18 09:20:53 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 18 Jan 2007 08:20:53 -0600 Subject: Would a Dutch speaker please check this wiki page please? In-Reply-To: <45af4735$0$322$e4fe514c@news.xs4all.nl> References: <45af4735$0$322$e4fe514c@news.xs4all.nl> Message-ID: <17839.33349.948499.442225@montanaro.dyndns.org> Martin> Could be Afrikaans too, but the page is gone now so I can't Martin> check. Actually, you can... ;-) Even though it's a nonexistent page, its history still exists. Poke the "Get Info" link and view the first revision of the file. Skip From mccredie at gmail.com Tue Jan 30 15:12:18 2007 From: mccredie at gmail.com (Matimus) Date: 30 Jan 2007 12:12:18 -0800 Subject: Find and replace in a file with regular expression In-Reply-To: <1170186744.322855.253550@j27g2000cwj.googlegroups.com> References: <1170186744.322855.253550@j27g2000cwj.googlegroups.com> Message-ID: <1170187938.235170.109870@s48g2000cws.googlegroups.com> The re module is used for regular expressions. Something like this should work (untested): import fileinput, string, sys, re fileQuery = "Text.txt" sourceText = '''SOURCE''' replaceText = '''REPLACE''' def replace(fileName, sourceText, replaceText): file = open(fileName, "r") text = file.read() #Reads the file and assigns the value to a variable file.close() #Closes the file (read session) file = open(fileName, "w") file.write(re.sub(sourceText, replaceText,text)) file.close() #Closes the file (write session) print "All went well, the modifications are done" replacemachine(fileQuery, sourceText, replaceText) From mike.klaas at gmail.com Wed Jan 24 19:07:34 2007 From: mike.klaas at gmail.com (Klaas) Date: 24 Jan 2007 16:07:34 -0800 Subject: The reliability of python threads In-Reply-To: References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> Message-ID: <1169683654.672020.136820@q2g2000cwa.googlegroups.com> On Jan 24, 10:43 am, "Carl J. Van Arsdall" wrote: > Yea, typically I would think that. The problem I am seeing is > incredibly intermittent. Like a simple pyro server that gives me a > problem maybe every three or four months. Just something funky will > happen to the state of the whole thing, some bad data, i'm having an > issue tracking it down and some more experienced programmers mentioned > that its most likely a race condition. THe thing is, I'm really not > doing anything too crazy, so i'm having difficult tracking it down. I > had heard in the past that there may be issues with threads, so I > thought to investigate this side of things. POSIX issues aside, Python's threading model should be less susceptible to memory-barrier problems that are possible in other languages (this is due to the GIL). Double-checked locking, frinstance, is safe in python even though it isn't in java. Are you ever relying solely on the GIL to access shared data? -Mike From robert.kern at gmail.com Sat Jan 27 22:26:09 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Jan 2007 21:26:09 -0600 Subject: distutils, sdist and tests In-Reply-To: References: Message-ID: Steven Bethard wrote: > Robert Kern wrote: >> Steven Bethard wrote: >>> How do I get distutils to include my testing module in just the "sdist" >>> distribution? >> Use a MANIFEST. >> >> http://docs.python.org/dist/source-dist.html Also, I just noted this tidbit: """If you don't supply an explicit list of files (or instructions on how to generate one), the sdist command puts a minimal default set into the source distribution: ... * anything that looks like a test script: test/test*.py (currently, the Distutils don't do anything with test scripts except include them in source distributions, but in the future there will be a standard for testing Python module distributions) ... """ So you can just stick test_argparse.py into a test/ directory. Having tested this, it appears to work (see below). >>> I want test_argparse.py to be available in the source distribution, but >>> I don't think it should be included in the binary distributions. > > Using a MANIFEST appears to do the same thing as putting "test_argparse" > into py_modules -- that is, it puts "test_argparse.py" into both "sdist" > and "bdist" distributions. In "bdist" distributions it gets installed to > the site-packages directory like any other module. Are you sure that you don't have changes left over in your setup.py when you tested that? Also check that you clear out your build/ directory every time. I think the bdist_* commands tend to just copy whatever is in the appropriate build/lib.*/ directory even though you've changed how those files should be generated. This is what I get with setup.py unmodified. The only thing I added was MANIFEST.in and an empty test_argparse.py file. [argparse]$ ls MANIFEST.in PKG-INFO README.txt argparse.py setup.py test_argparse.py [argparse]$ cat MANIFEST.in include PKG-INFO include *.txt include *.py [argparse]$ python setup.py bdist_dumb running bdist_dumb running build running build_py creating build creating build/lib copying argparse.py -> build/lib installing to build/bdist.macosx-10.3-fat/dumb running install running install_lib creating build/bdist.macosx-10.3-fat creating build/bdist.macosx-10.3-fat/dumb creating build/bdist.macosx-10.3-fat/dumb/Library creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5 creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages copying build/lib/argparse.py -> build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages byte-compiling build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.py to argparse.pyc running install_egg_info Writing build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse-0.5.0-py2.5.egg-info creating /Users/rkern/src/argparse/dist tar -cf /Users/rkern/src/argparse/dist/argparse-0.5.0.macosx-10.3-fat.tar . gzip -f9 /Users/rkern/src/argparse/dist/argparse-0.5.0.macosx-10.3-fat.tar removing 'build/bdist.macosx-10.3-fat/dumb' (and everything under it) [argparse]$ tar ztf dist/argparse-0.5.0.macosx-10.3-fat.tar.gz ./ ./Library/ ./Library/Frameworks/ ./Library/Frameworks/Python.framework/ ./Library/Frameworks/Python.framework/Versions/ ./Library/Frameworks/Python.framework/Versions/2.5/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse-0.5.0-py2.5.egg-info ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.py ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.pyc [argparse]$ python setup.py sdist running sdist reading manifest template 'MANIFEST.in' writing manifest file 'MANIFEST' creating argparse-0.5.0 making hard links in argparse-0.5.0... hard linking PKG-INFO -> argparse-0.5.0 hard linking README.txt -> argparse-0.5.0 hard linking argparse.py -> argparse-0.5.0 hard linking setup.py -> argparse-0.5.0 hard linking test_argparse.py -> argparse-0.5.0 tar -cf dist/argparse-0.5.0.tar argparse-0.5.0 gzip -f9 dist/argparse-0.5.0.tar removing 'argparse-0.5.0' (and everything under it) [argparse]$ tar ztf dist/argparse-0.5.0.tar.gz argparse-0.5.0/ argparse-0.5.0/argparse.py argparse-0.5.0/PKG-INFO argparse-0.5.0/README.txt argparse-0.5.0/setup.py argparse-0.5.0/test_argparse.py And this is what I get when I put test_argparse.py into a test/ directory: [argparse]$ ls PKG-INFO README.txt argparse.py setup.py test [argparse]$ python setup.py bdist_dumb running bdist_dumb running build running build_py creating build creating build/lib copying argparse.py -> build/lib installing to build/bdist.macosx-10.3-fat/dumb running install running install_lib creating build/bdist.macosx-10.3-fat creating build/bdist.macosx-10.3-fat/dumb creating build/bdist.macosx-10.3-fat/dumb/Library creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5 creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages copying build/lib/argparse.py -> build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages byte-compiling build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.py to argparse.pyc running install_egg_info Writing build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse-0.5.0-py2.5.egg-info creating /Users/rkern/src/argparse/dist tar -cf /Users/rkern/src/argparse/dist/argparse-0.5.0.macosx-10.3-fat.tar . gzip -f9 /Users/rkern/src/argparse/dist/argparse-0.5.0.macosx-10.3-fat.tar removing 'build/bdist.macosx-10.3-fat/dumb' (and everything under it) [argparse]$ tar ztf dist/argparse-0.5.0.macosx-10.3-fat.tar.gz ./ ./Library/ ./Library/Frameworks/ ./Library/Frameworks/Python.framework/ ./Library/Frameworks/Python.framework/Versions/ ./Library/Frameworks/Python.framework/Versions/2.5/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse-0.5.0-py2.5.egg-info ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.py ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.pyc [argparse]$ python setup.py sdist running sdist warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list) writing manifest file 'MANIFEST' creating argparse-0.5.0 creating argparse-0.5.0/test making hard links in argparse-0.5.0... hard linking README.txt -> argparse-0.5.0 hard linking argparse.py -> argparse-0.5.0 hard linking setup.py -> argparse-0.5.0 hard linking test/test_argparse.py -> argparse-0.5.0/test tar -cf dist/argparse-0.5.0.tar argparse-0.5.0 gzip -f9 dist/argparse-0.5.0.tar removing 'argparse-0.5.0' (and everything under it) [argparse]$ tar ztf dist/argparse-0.5.0.tar.gz argparse-0.5.0/ argparse-0.5.0/argparse.py argparse-0.5.0/PKG-INFO argparse-0.5.0/README.txt argparse-0.5.0/setup.py argparse-0.5.0/test/ argparse-0.5.0/test/test_argparse.py -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From karyn at calarts.edu Fri Jan 12 12:15:44 2007 From: karyn at calarts.edu (Karyn Williams) Date: Fri, 12 Jan 2007 09:15:44 -0800 Subject: What is a perl hash in python In-Reply-To: <8301441.post@talk.nabble.com> Message-ID: <3.0.1.32.20070112091544.0155fa80@muse.calarts.edu> I am new to Pyton. I am trying to modify and understand a script someone else wrote. I am trying to make sense of the following code snippet. I know line 7 would be best coded with regex. I first would like to understand what was coded originally. thelistOut looks like a hash to me (I'm more familiar with perl). Perhaps someone could translate from perl to python for me - not in code but just in concept. Here is the code. This script is reading the list thelistOut and then removing any items in RSMlist and taking the remainder and putting them in graphAddressOut with the formatting. This is a SAMPLE of what is in the lists referenced below in the loop: thelistOut = [(632, ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_9.log']), (145, ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_13.log']), (0, ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_5.log'])] RSMList = ['172.16.0.1_1', '172.16.0.1_2', '172.16.0.1_3', '172.16.0.1_4', '172.16.0.1_5'] #--------------------------Loop 1 ------------------------- w = 0 while w < 45: fileOut = string.split(thelistOut[w][1][0],".log") fileOutSplitedCommon = string.split(fileOut[0], "main/") fileOut2D = string.split(fileOutSplitedCommon[1], "/") fileOut = string.split(fileOut[0],"data-dist") if fileOut2D[1] in RSMList: w = w + 1 continue graphAddressOut = tag1 + logUrl + fileOut[1] + extention1 + tag2 + "SWITCH: " + string.swapcase(fileOut2D[0]) + "  & nbsp;PORT ID: " + fileOut2D[1] + "
" + imgTitleTag + imgTag1 + logUrl + fileOut[1] + extention2 + imgTag2 + tag3 + tag5 outputOut.append(graphAddressOut) strOut = strOut + graphAddressOut w = w + 1 #--------------------------Loop 1 ------------------------- -- Karyn Williams Network Services Manager California Institute of the Arts karyn at calarts.edu http://www.calarts.edu/network From elrondrules at gmail.com Fri Jan 26 21:51:58 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 26 Jan 2007 18:51:58 -0800 Subject: help with subscription to a process Message-ID: <1169866318.333371.238530@a34g2000cwb.googlegroups.com> Hi I am new to python and hence need some help i have a process A that posts events as XML docs. I need to create a listener to this process that subscribes to the process A and as and when a XML doc is posted parse it. I have creted an interface where if I specify the port number on which the listener is running the process A will automatically start posting events. The place I need help is to create a listener and a way of parsing the XML docs. If you can give me some starting points or docs/resources that will be great.. Thanks From perica.zivkovic at gmail.com Sat Jan 13 06:19:17 2007 From: perica.zivkovic at gmail.com (perica.zivkovic at gmail.com) Date: 13 Jan 2007 03:19:17 -0800 Subject: Portable Python - free portable development environment ! In-Reply-To: <9a6bb$45a8bd39$d443bb3a$8938@news.speedlinq.nl> References: <1168533423.224355.221390@k58g2000hse.googlegroups.com> <1168639781.763133.319580@s34g2000cwa.googlegroups.com> <1168684571.205607.277920@s34g2000cwa.googlegroups.com> <9a6bb$45a8bd39$d443bb3a$8938@news.speedlinq.nl> Message-ID: <1168687153.872917.81390@11g2000cwr.googlegroups.com> Stef, I never used Python4Delphi but I added it to the list-of-things-to-examine :) FOR ALL: I created google group for Portable Python http://groups-beta.google.com/group/portablepython and posted few items for discussion there :) Please if you have ideas/suggestions post it there! grtz Perica On Jan 13, 12:06 pm, Stef Mientki wrote: > > and something like Enthought edition will be there :) with even more > > packages and options :) at least that is my goal for the future :) But > > I must say I will also always be carefull with size of the distro :) > > thats also important right? :)Coming from MatLab, that's not the most important thing ;-) > > > more ideas?Embedded use of Python (e.g. Python4Delphi)... > ... I can imagine it needs special requirements ? > > cheers, > Stef From nanjundi at gmail.com Mon Jan 15 20:18:21 2007 From: nanjundi at gmail.com (Nanjundi) Date: 15 Jan 2007 17:18:21 -0800 Subject: Can't find module named 'svn' in python References: <1168907290.539976.117270@51g2000cwl.googlegroups.com> Message-ID: <1168910301.679069.166460@q2g2000cwa.googlegroups.com> My first thought: Check if you have /usr/local/lib/svn-python/ in your PYTHONPATH environment variable (echo $PYTHONPATH). If its missing, set it in the environment. export PYTHONPATH=$PYTHONPATH:/usr/local/lib/svn-python -N yinglcs at gmail.com wrote: > Hi, > > i have a simple test which tries to load 'svn' moddule. > > # python -c "from svn import client" > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named svn > > I have checked I have sub-directories 'libsvn', 'svn' under > /usr/local/lib/svn-python/ > > cd /usr/local/lib/svn-python/ > [root at localhost svn-python]# ls > libsvn svn > > But python still can't find it. Please tell me what am I missing. I > appreciate your help. From faulkner891 at gmail.com Thu Jan 25 21:22:51 2007 From: faulkner891 at gmail.com (faulkner) Date: 25 Jan 2007 18:22:51 -0800 Subject: Lython Message-ID: <1169778170.982274.46780@v45g2000cwv.googlegroups.com> I have Lython! I want to make sure that anybody else who wants it can access it, so, unless Mr. Egan objects, I'm hosting it here: http://home.comcast.net/~faulkner612/programming/python/lython.zip I had to patch it a bit because the number of arguments to compiler.ast.Function.__init__ changed between 2.3 and 2.4, when decorators were introduced. I haven't tested it on 2.5 because the last time I upgraded python, my gentoo died. I also took the liberty of adding some features such as primitive interactivity, a '-c code' option, a '-h' option, an rc file '~/.lythonrc.ly', and a '-o file' option which dumps bytecode to file. I've slated developing support for *args, **kwargs, default arguments, += and -= etc., reader macros ala common lisp, classes, try...except...finally, and raise. For the curious, here are some other implementations of lisp in python: http://ibiblio.org/obp/py4fun/lisp/lisp.html http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme/ http://www.xs4all.nl/~yduppen/site/psyche.html http://www.biostat.wisc.edu/~annis/creations/PyLisp/ These implementations are great, but Lython has macro capabilities, generates python byte code, and demonstrates the use of spark, a fantastic parsing package. From martin at v.loewis.de Fri Jan 5 04:30:11 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Jan 2007 10:30:11 +0100 Subject: checking one's type In-Reply-To: References: Message-ID: <459e1aa4$0$17143$9b622d9e@news.freenet.de> belinda thom schrieb: > I've been using the following hack to determine if a type is acceptable > and I suspect there is a better way to do it: > > e.g. > > if type(s) == type("") : > print "okay, i'm happy you're a string" > > If anyone knows a better way, I'm all ears. There are several way to improve it. In order from smaller to larger changes: - don't use type(""), instead, use str: if type(s) == str: [notice: this works only from Python 2.2 or so] - you can compare types by identity and don't need to compare for equality: if type(s) is str - you can do instance tests with isinstance: if isinstance(s, str): - try avoiding instance tests altogether. Instead, just let callers pass anything, and then let the operations fail if they can't handle the types. Regards, Martin From mail at microcorp.co.za Sun Jan 14 00:47:13 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 14 Jan 2007 07:47:13 +0200 Subject: General Question About Python References: <1168254451.098796.144790@42g2000cwt.googlegroups.com><1168586849.047301.301680@s34g2000cwa.googlegroups.com> <1168687033.258472.16090@v45g2000cwv.googlegroups.com> Message-ID: <006401c7379f$712ab320$03000080@hendrik> "Torabisu" wrote: > > Hendrik van Rooyen wrote: > > What do you want done? - I am only a thousand miles away... > > > > If I can just get my Python teleporter sorted out, distance will be no > problem... A little buggy at the moment though... Poor John, I told > him not to test it but oh well. OMG! - I have been feeding that unexpected heap of minced meat to the cat... - Hendrik From rschroev_nospam_ml at fastmail.fm Sat Jan 20 11:05:26 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 20 Jan 2007 16:05:26 GMT Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: References: Message-ID: Carroll, Barry schreef: > Secondly, can someone point me to the Standard Usenet Convention that > mandates against top-posting. This is not sarcasm; I would really like > to see it. You see, I recently returned to Usenet after a LONG absence. > When I was last a regular Usenet citizen the Internet was new, GUI > interfaces were experimental and the World Wide Web didn't exist yet. > Newsreader software was text-based. Top-posting was the common > practice, because it was the most convenient: you didn't have to page > through an arbitrarily large number of messages, most of which you'd > already read umpteen times, to get to the new stuff you were interested > in. I started to use the Internet and Usenet around 1992 or 1993, and at the time 'Netiquette' was a very common word. Amongst others it recommends inline replying (as opposed to both top-posting and bottom-posting), in spirit if not in exact wording. The Wikipedia article on Netiquette (http://en.wikipedia.org/wiki/Netiquette) mentions it with as many words: "Quoting should be interspersed, with a response that follows the relevant quoted material. The result should read like a conversation, with quotes indented to aid in skimming. A common mistake is to put all new text above the quoted material, without trimming any irrelevant text. This results in a message that is much harder to follow and is much less clear in context." All groups I read at the time used that convention. In my experience it was only in more recent times that people started to use top-posting, and then only in newsgroups, forums, etc. that didn't originate in the original Internet culture. > So I'd really like to know what the standard is now. I like to know > which rules I'm choosing to break. ;^) You could do worse than RFC 1855 (http://www.dtcc.edu/cs/rfc1855.html) and the above mentioned Wikipedia article. Both cover many other issues regarding online behavior. There's also http://wiki.ursine.ca/Top_Posting which just covers quoting practices. But note that inline replying isn't as wide-spread as I think it ought to be. Places that don't have roots in Internet or Unix culture are much more likely to accept and even encourage top-posting. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From gagsl-py at yahoo.com.ar Fri Jan 5 11:45:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 13:45:52 -0300 Subject: where is Microsoft Speech Object Library 5.1 option in PythonWin 2.5? In-Reply-To: References: Message-ID: <7.0.1.0.0.20070105134124.05cacec0@yahoo.com.ar> At Friday 5/1/2007 11:24, siggi wrote: >However, in my Python 2.5/PythonWin 2.5 installation I find as only option >"Microsoft Speech Object Library 5.0" to select. This list shows all the COM objects currently registered in Windows, does not depend on Pythonwin. >Unfortunately, 5.1 is the lowest SDK version I found on >http://www.microsoft.com/downloads/details.aspx?FamilyId=5E86EC97-40A7-453F-B0EE-6583171B4530&displaylang=en#QuickInfoContainer After you download and install version 5.1, it should appear on the list. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From arkanes at gmail.com Thu Jan 4 13:42:30 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Jan 2007 12:42:30 -0600 Subject: Using External Libraries with python? In-Reply-To: <459D2F8E.1080600@v.loewis.de> References: <459D2F8E.1080600@v.loewis.de> Message-ID: <4866bea60701041042t2c9ee250u5ba31b9b3c978d6b@mail.gmail.com> On 1/4/07, "Martin v. L?wis" wrote: > Ognjen Bezanov schrieb: > > I have some external C libraries I would like to use with python. > > > > I have been searching on the internet and found many such > > modules/bindings for libraries (e.g. Py-Lame) but have not yet > > come across any information of how to actually go about creating such > > bindings, so I was wondering if anybody here could point me in the right > > direction? > > There are several methods. One is to write a Python C module by hand, > using the Python C API: > > http://docs.python.org/ext/ext.html > http://docs.python.org/api/api.html > > Essentially, all you need is a DLL/shared-object with an init > function. > > Other solutions include tools that generate extension modules > automatically (such as SWIG or Pyrex), or using libraries on > top of the C API (such as Boost.Python). > > I personally always use the C API directly. > > Regards, > Martin Don't forget calling the using the external library directly from Python by using ctypes. From vmalloc at gmail.com Thu Jan 25 16:31:13 2007 From: vmalloc at gmail.com (Rotem) Date: 25 Jan 2007 13:31:13 -0800 Subject: Possible bug in Python 2.5? (Was Re: pdb in python2.5) In-Reply-To: References: <1169717486.230356.79730@l53g2000cwa.googlegroups.com> Message-ID: <1169760673.197226.206540@a75g2000cwd.googlegroups.com> Hi, I noticed that pydb.pm() also fails in python2.5 when invoked on that same example (seems like also trying to access a nonexistent attribute/variable). Is this known to you as well/was it fixed? On Jan 25, 9:15 pm, r... at panix.com (R. Bernstein) wrote: > I'd like to change my assessment of whether the problem encountered is > a pdb bug or not. It could be a bug in Python. (Right now it is only > known to be a bug in version 2.5.) > > For a given traceback t, the question is whether t.tb_frame.f_lineno > can ever be different from t.tb_lineno. > > Still, for now in pydb CVS, I've worked around this by checking. > > r... at panix.com (R. Bernstein) writes: > > "Rotem" writes: > > > > Hi, > > > > Maybe I'm repeating a previous post (please correct me if I am). > > > > I've tried the following code in python 2.5 (r25:51908, Oct 6 2006, > > > 15:22:41) > > > example: > > > > from __future__ import with_statement > > > import threading > > > > def f(): > > > l = threading.Lock() > > > with l: > > > print "hello" > > > raise Exception("error") > > > print "world" > > > > try: > > > f() > > > except: > > > import pdb > > > pdb.pm() > > > > This fails because pdb.pm() attempts to access sys.last_traceback which > > > is not assigned. > > > Recent releases of pydb (http://bashdb.sf.net/pydb) don't suffer this > > problem. (But see below.) > > > > Trying: > > > pdb.post_mortem(sys.exc_traceback) > > > > Yields the following: > > > > test.py(9)f() > > > -> print "world" > > > (Pdb) > > > > the 'w' command yields a similar output, which implies that the > > > exception was thrown from the wrong line. > > > the traceback module is better, yielding correct results (displays line > > > 8 instead of 9). > > > > Has anyone encountered this behavior? > > > Yes, this seems to be a bug in pdb. It is using the traceback's f_line > > instance variable rather than the tb_lineno instance variable. I guess > > these two values are usually the same. In fact, I haven't been able to > > come up with a Python 2.4 situtation where they are different. (If > > someone can, I'd appreciate it if you'd send me a small example so I > > can put it in the pydb regression tests.) Even in 2.5, it's kind of > > hard to get a case where they are different. If I remove the "with", > > the problem goes away. > > > It was also bug in pydb, but I've just committed in CVS the fix for > > this > > > > is pdb broken? > > > Best as I can tell pdb isn't all that well maintained. (Had it been, I > > probably wouldn't have devoted the time to pydb that I have been.) > > > > I get similar results for larger/more complex pieces of code. > > > > Thanks in advance, > > > > Rotem From bj_666 at gmx.net Wed Jan 17 04:04:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 17 Jan 2007 10:04:59 +0100 Subject: How to determine what exceptions a method might raise? References: <12qq98ijkn5mld8@corp.supernews.com> <1169022894.357383.45950@a75g2000cwd.googlegroups.com> Message-ID: In <1169022894.357383.45950 at a75g2000cwd.googlegroups.com>, George Sakkis wrote: > Ben Finney wrote: > >> But, in case it helps: Any code may raise any exception at any >> time. This is a feature, since it encourages program that are tested >> properly. > > That's a silly argument, really, unless perhaps you'd consider a box of > pills that look like M&Ms a 'feature' since it encourages parents to > hide them from their kids. A better answer would be along the lines of > "yes, that would be nice to have but in general it's not possible in a > dynamic language; that's the price you have to pay for leaving the > static typing world". I don't thing that's a dynamic vs. static thing because in statically typed languages it's not that easy to find out all possible exceptions unless the language forces you to declare them. Ciao, Marc 'BlackJack' Rintsch From pretoriano_2001 at hotmail.com Sun Jan 7 20:21:19 2007 From: pretoriano_2001 at hotmail.com (vizcayno) Date: 7 Jan 2007 17:21:19 -0800 Subject: Recommendations (or best practices) to define functions (or methods) Message-ID: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> Hello: Need your help in the "correct" definition of the next function. If necessary, I would like to know about a web site or documentation that tells me about best practices in defining functions, especially for those that consider the error exceptions management. I have the next alternatives but I think there are better: Alternative 1: ============= def ExecuteSQL(cmdSQL, cursor): try: cursor.execute(cmdSQL) except Exception, e: return e return 1 Seems a good solution but the function is not returning an uniform type, should the code that receives the function result decides the error display according of datatype? If I do this in C# I think I will have problems. Alternative 2: ============= def ExecuteSQL(cmdSQL, cursor): try: cursor.execute(cmdSQL) except Exception, e: return 0, e # or return (0,e.message) return 1, "ok" # or return (1, "ok") Sounds good, but seems forced. When doing return 1, "ok" I am doing redundancy and I have problems with the type (e is exception type and "ok" is string). Alternative 3: ============= def ExecuteSQL(cmdSQL, cursor): try: cursor.execute(cmdSQL) except Exception, e: print "ERROR:", e return 0 return 1 It solves the problem of alternative 1 and 2, but the print keyword would have problems if the function is called from an WEB or GUI application and, because there are plans to convert print into a function in py3k. Alternative 4: ============= def ExecuteSQL(cmdSQL, cursor): try: cursor.execute(cmdSQL) except Exception, e: print >> logerr, e.message return 0 return 1 Seems a good solution but I should always be persuaded to have an open global file (logerr) when invoking this function; otherwise code will generate another error. The function is not totally independent.I think I would be in the same situation when using the "logging" battery. Thanks for your attention. Regards, From liam_jones at yahoo.com Wed Jan 10 10:26:19 2007 From: liam_jones at yahoo.com (liam_jones at yahoo.com) Date: 10 Jan 2007 07:26:19 -0800 Subject: Using Excel With Python Message-ID: <1168442779.267439.222880@77g2000hsv.googlegroups.com> I'm very new to Python, well IronPython to precise, and have been having problems when using Excel. The problem I'm having is the closing of my Excel object. I'm able to successfully quit the Excel Application that I create, but when I open a Workbook in the Application I can't successfully Quit Excel (by this I mean I can quit it, but the Excel process isn't getting killed and I have to manually go this through Task Manager). I've given a sample of code below to hopefully make things clearer. I've then given all of the information I think might be useful (sorry if I've gone over the top!). import System import clr from System.Data import * from System.Web import * from System.Web.UI import * from clr import * clr.AddReference("Microsoft.Office.Interop.Word") clr.AddReference("Microsoft.Office.Interop.Excel") clr.AddReference("Microsoft.Office.Interop.PowerPoint") clr.AddReference("Office") from Microsoft.Office.Interop.Word import ApplicationClass as WordApplication from Microsoft.Office.Interop.Excel import ApplicationClass as ExcelApplication from Microsoft.Office.Interop.PowerPoint import ApplicationClass as PowerPointApplication from Microsoft.Office.Interop.Word import WdReplace from Microsoft.Office.Interop.Excel import XlCellType from Microsoft.Office.Interop.Excel import XlSearchDirection from System.Type import Missing from System import GC missing = Missing FileLocation = "C:\\test.xls" ExcelApp = ExcelApplication() workbook= None workbook = ExcelApp.Workbooks.Open(FileLocation, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing) workbook.Save() workbook.Close(SaveChanges=0) ExcelApp.Quit() workbook = None ExcelApp = None GC.Collect() GC.WaitForPendingFinalizers() I've simpilised the code by taking all of my Workbook processing from it and the problem is still occurring. As I said above if I don't create the workbook, then ExcelApp closes as expected (there are no stray processes). I've read many articles and postings over the last few days regarding this, but have had no luck with anything I've seen, examples of this are now given. I've tried adding the below code, but with no luck. ExcelApp.ActiveWorkbook.Save() ExcelApp.ActiveWorkbook.Close(SaveChanges=0) ExcelApp.Workbooks.Close() I've also tried the below (again with no luck). System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook) System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp) And, I've also tried the following (again with no luck!). del(workbook) del(excelApp) It may seem strange using the Garbage Collector (well I wouldn't have thought about using it here), but it was something that I read about using for code written in C#. I've tried the code in C# (what I normally write in) and all works fine, the only real difference is that I'm setting the objects to NULL in C# and None here in IronPython - Does this make a difference, is there something else I should be setting it to? The Workbook object HAS to be set to NULL in C#, it's then picked up by the Garbage Collector and the task disappears from the Task Manager. I did think of killing the actual EXCEL.EXE process at the end of my code, but there might be several versions of the containing application running on the same box, so I can't kill all of the Excel processes. As I said above, I'm sorry if I've gone over the top in my description. Any ideas or pointers would be greatly appreciated as I'm now going round in circles. Thanks in advance. Rgds Liam From nagle at animats.com Sat Jan 13 00:38:44 2007 From: nagle at animats.com (John Nagle) Date: Sat, 13 Jan 2007 05:38:44 GMT Subject: More M2Crypto issues. Not big ones, though. In-Reply-To: <3JGdnb2VxN7PsjXYnZ2dnUVZ_hydnZ2d@comcast.com> References: <3JGdnb2VxN7PsjXYnZ2dnUVZ_hydnZ2d@comcast.com> Message-ID: Heikki Toivonen wrote: > John Nagle wrote: > >> A list of small problems and bugs in the current M2Crypto: >>I need to look at SSL certificates in some detail, so this >>is all about the access functions for certificates. > > > Thanks, got the reports, will check them out. > > >> 3. /M2Crypto/SSL/Connection.py:147: >> DeprecationWarning: Old style callback, use cb_func(ok, store) >> instead return m2.ssl_connect(self.ssl) >> (Also reported, in Polish, here: >>http://www.mail-archive.com/pld-devel-pl at lists.pld-linux.org/msg12433.html) >> Entered into Bugzilla as #7718. > > > This is actually intended. Once I figure out how to implement all the > functionality in the new way I'd like to remove the old way. OK. >> 4. "close()" on an SSL socket that's just finished certificate >> negotiation hangs, at least on Windows. > > No known issues, but the ending of an SSL connection is a little grey > area to me so I wouldn't be surprised if there are some cases where we > shut down prematurely or too late. But I don't know why we'd hang. I'll check that again. > > >> 1. X509.X509_name.__getattr__: >> Field retrieval from X.509 name items with x509_name_by_nid >> retrieves only first instance of field, not all instances. > > Yes, I've been battling with this myself as well. OpenSSL provides > objects to get things as a list, but they are so weird I haven't yet > figured out a way to wrap them in Python so that you would actually be > able to get some values out. I convert X509_name items to a list of tuples. Here's an example: Server: [ ('CN', 'www.apartmentsapart.com'), ('OU', 'Travel Services'), ('O', 'Niche Travel Ltd.'), ('L', 'Nicosia'), ('ST', 'Nicosia'), ('C', 'CY')] That's straightforward. But to do this I have to convert the X509_name item to a string, like this: subjectstr = subject.as_text(flags=(m2.XN_FLAG_RFC2253 | m2.ASN1_STRFLGS_UTF8_CONVERT) & ~m2.XN_FLAG_DUMP_UNKNOWN_FIELDS) which yields a string of items like "L=Nicosia, OU=Travel Services", with backslash escapes where necessary. (The default formatting does not have proper escaping; it's just for debug use.) So I parse that, obeying the escapes, and get out the tuples. This works OK, but shouldn't be necessary. It's not something I need now, though. Most things in X509 certificates map well to lists of tuples. >> 2. Unclear if M2Crypto's X.509 interface is UTF-8 compatible. >> OpenSSL will return info in UTF-8 if you use the >> ASN1_STRFLGS_UTF8_CONVERT flag on as_text, but unclear if the >> M2 glue code handles this correctly. Haven't found a UTF8 cert >> to test it on yet. > > > Yeah, I am not convinced everything works as it should. Any UTF8 (and > other encoding) samples would be welcome. Looking for one. I think all that's needed is to recognize when ASN1_STRFLGS_UTF8_CONVERT is set when converting to a Python string, and convert to the appropriate form of Python string. Just rediscovered bug #5277, "Support certificates with multiple DNS names", which is fixed in 0.18. Looking forward to version 0.18. If you want to test that, try to open "https://www.autumngalleryforthehome.com". John Nagle From fredrik at pythonware.com Thu Jan 4 04:26:53 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Jan 2007 10:26:53 +0100 Subject: pow() works but sqrt() not!? In-Reply-To: References: <1167899693.759071.51450@31g2000cwt.googlegroups.com> Message-ID: siggi wrote: > What is a "namespace" and what is the difference between ">>>import math" > and ">>>from math import *" ? http://preview.tinyurl.com/t4pxq for more on this, *please* read the relevant sections in the tutorial. Python's all about namespaces, and trial and error is not a very good way to figure how they work. From chrolson at gmail.com Fri Jan 19 18:55:23 2007 From: chrolson at gmail.com (chrolson at gmail.com) Date: 19 Jan 2007 15:55:23 -0800 Subject: float comparison confusion Message-ID: <1169250923.146916.206430@s34g2000cwa.googlegroups.com> Type "help", "copyright", "credits" or "license" for more information. >>> cmp(20.10, 20.9) -1 Why is cmp returning -1 instead of returning positive integer? From haisge at gmail.com Mon Jan 8 05:37:31 2007 From: haisge at gmail.com (haisge) Date: 8 Jan 2007 02:37:31 -0800 Subject: the free b2b website guide Message-ID: <1168252651.295075.78890@i15g2000cwa.googlegroups.com> the free b2b website guide http://www.b2bbyte.com From Eric_Dexter at msn.com Wed Jan 24 18:43:01 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 24 Jan 2007 15:43:01 -0800 Subject: ogl example question Message-ID: <1169682181.743117.163600@a34g2000cwb.googlegroups.com> I know this might be the wrong place to ask but I recently modified the ogl example from wxpython and it works fine in spe but when I call it from other programs it wierds out because of the run.py thing they have set it up with doesn't work when I call it from an external program (including .bat files). when I call it outside of spe I manage to just get a box without the tracker part. It is so close to out right theft I was hopeing I could just tweek something to make it work for me. Any help would be apreciated (I am trying to call it with tracker.py bay-at-night.csd ) #!/usr/bin/env python #---------------------------------------------------------------------------- # Name: run.py # Purpose: Simple framework for running individual demos # # Author: Robin Dunn # # Created: 6-March-2000 # RCS-ID: $Id: run.py,v 1.29.2.1 2006/01/26 00:33:39 RD Exp $ # Copyright: (c) 2000 by Total Control Software # Licence: wxWindows license #---------------------------------------------------------------------------- """ This program will load and run one of the individual demos in this directory within its own frame window. Just specify the module name on the command line. """ import wx # This module uses the new wx namespace import sys, os # stuff for debugging print "wx.VERSION_STRING = %s (%s)" % (wx.VERSION_STRING, wx.USE_UNICODE and 'unicode' or 'ansi') print "pid:", os.getpid() ##raw_input("Press Enter...") assertMode = wx.PYAPP_ASSERT_DIALOG ##assertMode = wx.PYAPP_ASSERT_EXCEPTION #---------------------------------------------------------------------------- class Log: def WriteText(self, text): if text[-1:] == '\n': text = text[:-1] wx.LogMessage(text) write = WriteText class RunDemoApp(wx.App): def __init__(self, name, module, useShell): self.name = name self.demoModule = module self.useShell = useShell wx.App.__init__(self, redirect=False) def OnInit(self): wx.Log_SetActiveTarget(wx.LogStderr()) self.SetAssertMode(assertMode) frame = wx.Frame(None, -1, "RunDemo: " + self.name, pos=(50,50), size=(200,100), style=wx.DEFAULT_FRAME_STYLE) frame.CreateStatusBar() menuBar = wx.MenuBar() menu = wx.Menu() item = menu.Append(-1, "E&xit\tAlt-X", "Exit demo") self.Bind(wx.EVT_MENU, self.OnExitApp, item) menuBar.Append(menu, "&File") ns = {} ns['wx'] = wx ns['app'] = self ns['module'] = self.demoModule ns['frame'] = frame frame.SetMenuBar(menuBar) frame.Show(True) frame.Bind(wx.EVT_CLOSE, self.OnCloseFrame) win = self.demoModule.runTest(frame, frame, Log()) # a window will be returned if the demo does not create # its own top-level window if win: # so set the frame to a good size for showing stuff frame.SetSize((640, 480)) win.SetFocus() self.window = win ns['win'] = win frect = frame.GetRect() else: # It was probably a dialog or something that is already # gone, so we're done. frame.Destroy() return True self.SetTopWindow(frame) self.frame = frame #wx.Log_SetActiveTarget(wx.LogStderr()) #wx.Log_SetTraceMask(wx.TraceMessages) if self.useShell: # Make a PyShell window, and position it below our test window from wx import py shell = py.shell.ShellFrame(None, locals=ns) frect.OffsetXY(0, frect.height) frect.height = 400 shell.SetRect(frect) shell.Show() # Hook the close event of the test window so that we close # the shell at the same time def CloseShell(evt): if shell: shell.Close() evt.Skip() frame.Bind(wx.EVT_CLOSE, CloseShell) return True def OnExitApp(self, evt): self.frame.Close(True) def OnCloseFrame(self, evt): if hasattr(self, "window") and hasattr(self.window, "ShutdownDemo"): self.window.ShutdownDemo() evt.Skip() #---------------------------------------------------------------------------- def main(argv): useShell = False for x in range(len(sys.argv)): if sys.argv[x] in ['--shell', '-shell', '-s']: useShell = True del sys.argv[x] break if len(argv) < 2: print "Please specify a demo module name on the command-line" raise SystemExit name, ext = os.path.splitext(argv[1]) module = __import__(name) app = RunDemoApp(name, module, useShell) app.MainLoop() if __name__ == "__main__": main(sys.argv) # -*- coding: iso-8859-1 -*- # 11/20/2003 - Jeff Grimmett (grimmtooth at softhome.net) # # o Updated for wx namespace # # 20040508 - Pierre Hj?lm # # o Changed to use the python version of OGL # o Added TextShape, CompositeShape and CompositeShape with divisions # # 20040830 - Pierre Hj?lm # # o Added DrawnShape # import wx import wx.lib.ogl as ogl import csoundroutines import sys #import images #---------------------------------------------------------------------- class DrawnShape(ogl.DrawnShape): def __init__(self): ogl.DrawnShape.__init__(self) self.SetDrawnBrush(wx.WHITE_BRUSH) self.SetDrawnPen(wx.BLACK_PEN) self.DrawArc((0, -10), (30, 0), (-30, 0)) self.SetDrawnPen(wx.Pen("#ff8030")) self.DrawLine((-30, 5), (30, 5)) self.SetDrawnPen(wx.Pen("#00ee10")) self.DrawRoundedRectangle((-20, 10, 40, 10), 5) self.SetDrawnPen(wx.Pen("#9090f0")) self.DrawEllipse((-30, 25, 60, 20)) self.SetDrawnTextColour(wx.BLACK) self.SetDrawnFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL)) self.DrawText("DrawText", (-26, 28)) self.SetDrawnBrush(wx.GREEN_BRUSH) self.DrawPolygon([(-100, 5), (-45, 30), (-35, 20), (-30, 5)]) self.SetDrawnPen(wx.BLACK_PEN) self.DrawLines([(30, -45), (40, -45), (40 ,45), (30, 45)]) # Make sure to call CalculateSize when all drawing is done self.CalculateSize() #---------------------------------------------------------------------- class DiamondShape(ogl.PolygonShape): def __init__(self, w=0.0, h=0.0): ogl.PolygonShape.__init__(self) if w == 0.0: w = 60.0 if h == 0.0: h = 60.0 points = [ (0.0, -h/2.0), (w/2.0, 0.0), (0.0, h/2.0), (-w/2.0, 0.0), ] self.Create(points) #---------------------------------------------------------------------- class TrackerRectangle(ogl.RectangleShape): def __init__(self, w=0.0, h = 0.0): ogl.RectangleShape.__init__(self, w, h) #self.TextShape(text) class RoundedRectangleShape(ogl.RectangleShape): def __init__(self, w=0.0, h=0.0): ogl.RectangleShape.__init__(self, w, h) self.SetCornerRadius(-0.3) #---------------------------------------------------------------------- class CompositeDivisionShape(ogl.CompositeShape): def __init__(self, canvas): ogl.CompositeShape.__init__(self) self.SetCanvas(canvas) # create a division in the composite self.MakeContainer() # add a shape to the original division shape2 = ogl.RectangleShape(40, 60) self.GetDivisions()[0].AddChild(shape2) # now divide the division so we get 2 self.GetDivisions()[0].Divide(wx.HORIZONTAL) # and add a shape to the second division (and move it to the # centre of the division) shape3 = ogl.CircleShape(40) shape3.SetBrush(wx.CYAN_BRUSH) self.GetDivisions()[1].AddChild(shape3) shape3.SetX(self.GetDivisions()[1].GetX()) for division in self.GetDivisions(): division.SetSensitivityFilter(0) #---------------------------------------------------------------------- class CompositeShape(ogl.CompositeShape): def __init__(self, canvas): ogl.CompositeShape.__init__(self) self.SetCanvas(canvas) constraining_shape = ogl.RectangleShape(120, 100) constrained_shape1 = ogl.CircleShape(50) constrained_shape2 = ogl.RectangleShape(80, 20) constraining_shape.SetBrush(wx.BLUE_BRUSH) constrained_shape2.SetBrush(wx.RED_BRUSH) self.AddChild(constraining_shape) self.AddChild(constrained_shape1) self.AddChild(constrained_shape2) constraint = ogl.Constraint(ogl.CONSTRAINT_MIDALIGNED_BOTTOM, constraining_shape, [constrained_shape1, constrained_shape2]) self.AddConstraint(constraint) self.Recompute() # If we don't do this, the shapes will be able to move on their # own, instead of moving the composite constraining_shape.SetDraggable(False) constrained_shape1.SetDraggable(False) constrained_shape2.SetDraggable(False) # If we don't do this the shape will take all left-clicks for itself constraining_shape.SetSensitivityFilter(0) #---------------------------------------------------------------------- class DividedShape(ogl.DividedShape): def __init__(self, width, height, canvas): ogl.DividedShape.__init__(self, width, height) region1 = ogl.ShapeRegion() region1.SetText('DividedShape') region1.SetProportions(0.0, 0.2) region1.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ) self.AddRegion(region1) region2 = ogl.ShapeRegion() region2.SetText('This is Region number two.') region2.SetProportions(0.0, 0.3) region2.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ|ogl.FORMAT_CENTRE_VERT) self.AddRegion(region2) region3 = ogl.ShapeRegion() region3.SetText('Region 3\nwith embedded\nline breaks') region3.SetProportions(0.0, 0.5) region3.SetFormatMode(ogl.FORMAT_NONE) self.AddRegion(region3) self.SetRegionSizes() self.ReformatRegions(canvas) def ReformatRegions(self, canvas=None): rnum = 0 if canvas is None: canvas = self.GetCanvas() dc = wx.ClientDC(canvas) # used for measuring for region in self.GetRegions(): text = region.GetText() self.FormatText(dc, text, rnum) rnum += 1 def OnSizingEndDragLeft(self, pt, x, y, keys, attch): print "***", self ogl.DividedShape.OnSizingEndDragLeft(self, pt, x, y, keys, attch) self.SetRegionSizes() self.ReformatRegions() self.GetCanvas().Refresh() #---------------------------------------------------------------------- class MyEvtHandler(ogl.ShapeEvtHandler): def __init__(self, log, frame): ogl.ShapeEvtHandler.__init__(self) self.log = log self.statbarFrame = frame def UpdateStatusBar(self, shape): x, y = shape.GetX(), shape.GetY() width, height = shape.GetBoundingBoxMax() self.statbarFrame.SetStatusText("Pos: (%d, %d) Size: (%d, %d)" % (x, y, width, height)) def OnLeftClick(self, x, y, keys=0, attachment=0): shape = self.GetShape() canvas = shape.GetCanvas() dc = wx.ClientDC(canvas) canvas.PrepareDC(dc) if shape.Selected(): shape.Select(False, dc) canvas.Redraw(dc) else: redraw = False shapeList = canvas.GetDiagram().GetShapeList() toUnselect = [] for s in shapeList: if s.Selected(): # If we unselect it now then some of the objects in # shapeList will become invalid (the control points are # shapes too!) and bad things will happen... toUnselect.append(s) shape.Select(True, dc) if toUnselect: for s in toUnselect: s.Select(False, dc) canvas.Redraw(dc) self.UpdateStatusBar(shape) def OnEndDragLeft(self, x, y, keys=0, attachment=0): shape = self.GetShape() ogl.ShapeEvtHandler.OnEndDragLeft(self, x, y, keys, attachment) if not shape.Selected(): self.OnLeftClick(x, y, keys, attachment) self.UpdateStatusBar(shape) def OnSizingEndDragLeft(self, pt, x, y, keys, attch): ogl.ShapeEvtHandler.OnSizingEndDragLeft(self, pt, x, y, keys, attch) self.UpdateStatusBar(self.GetShape()) def OnMovePost(self, dc, x, y, oldX, oldY, display): ogl.ShapeEvtHandler.OnMovePost(self, dc, x, y, oldX, oldY, display) self.UpdateStatusBar(self.GetShape()) def OnRightClick(self, *dontcare): self.log.WriteText("%s\n" % self.GetShape()) #---------------------------------------------------------------------- class TestWindow(ogl.ShapeCanvas): def __init__(self, parent, log, frame): ogl.ShapeCanvas.__init__(self, parent) maxWidth = 1000 maxHeight = 1000 self.SetScrollbars(20, 20, maxWidth/20, maxHeight/20) self.log = log self.frame = frame self.SetBackgroundColour("LIGHT BLUE") #wx.WHITE) self.diagram = ogl.Diagram() self.SetDiagram(self.diagram) self.diagram.SetCanvas(self) self.shapes = [] self.save_gdi = [] rRectBrush = wx.Brush("MEDIUM TURQUOISE", wx.SOLID) dsBrush = wx.Brush("WHEAT", wx.SOLID) #self.MyAddShape( # CompositeDivisionShape(self), # 270, 310, wx.BLACK_PEN, wx.BLUE_BRUSH, "Division" # ) #self.MyAddShape( # CompositeShape(self), # 100, 260, wx.BLACK_PEN, wx.RED_BRUSH, "Composite" # ) #self.MyAddShape( # ogl.CircleShape(80), # 75, 110, wx.Pen(wx.BLUE, 3), wx.GREEN_BRUSH, "Circle" # ) #self.MyAddShape( # ogl.TextShape(120, 45), # 160, 35, wx.GREEN_PEN, wx.LIGHT_GREY_BRUSH, "OGL is now a\npure Python lib!" # ) #self.MyAddShape( # ogl.RectangleShape(85, 50), # 305, 60, wx.BLACK_PEN, wx.LIGHT_GREY_BRUSH, "Rectangle" # ) #self.MyAddShape( # DrawnShape(), # 500, 80, wx.BLACK_PEN, wx.BLACK_BRUSH, "DrawnShape" # ) #ds = self.MyAddShape( # DividedShape(140, 150, self), # 520, 265, wx.BLACK_PEN, dsBrush, '' # ) #self.MyAddShape( # DiamondShape(90, 90), # 355, 260, wx.Pen(wx.BLUE, 3, wx.DOT), wx.RED_BRUSH, "Polygon" # ) #self.MyAddShape( # RoundedRectangleShape(95, 70), # 345, 145, wx.Pen(wx.RED, 2), rRectBrush, "Rounded Rect" # ) instr = csoundroutines.csdInstrumentList2(sys.argv[1]) connections = csoundroutines.return_pins2(sys.argv[1]) shape = [] for i in range(0, len(instr.instrnum)): #shape[i] = ogl.RectangleShape(80, 30) #shape[i].AddText(instr.comments[i]) #canvas.AddShape( shape[i] ) #shape[i].SetX( 25.0 ) # #shape[i].SetY( 25.0 ) self.MyAddShape( TrackerRectangle(70,30), 25, 25, wx.Pen(wx.RED, 2),rRectBrush, instr.comments[i] ) dc = wx.ClientDC(self) self.PrepareDC(dc) print 'is here' line = {} x1 = {} y1 = {} x2 = {} y2 = {} for i in range(0, len(instr.instrnum)): if connections.instr_output[i] != 0: #check for an output for n in range(0,len(instr.comments)): #iterate through names print(connections.instr_number[i], int(instr.instrnum[n])) if connections.instr_number[i] == int(instr.instrnum[n]): #check for a match x1[i] = self.shapes[i].GetX # y1[i] = self.shapes[i].GetY print instr.instrnum print 'instr num' print i print 'iterator' #outstring = instr.comments[n] + ' -> ' #grab the name for o in range(0, len(connections.instr_number)): #iterate through connections #print(o, outstring) if connections.instr_output[i] == connections.instr_input[o]: #check for pin match for n2 in range(0,len(instr.comments)): #iterate through connections if connections.instr_number[o] == int(instr.instrnum[n2]): #match names x2 = self.shapes[n2].GetX y2 = self.shapes[n2].GetY fromShape = self.shapes[i] toShape = self.shapes[n2] line = ogl.LineShape() line.SetCanvas(self) line.SetPen(wx.BLACK_PEN) line.SetBrush(wx.BLACK_BRUSH) line.AddArrow(ogl.ARROW_ARROW) line.MakeLineControlPoints(2) fromShape.AddLine(line, toShape) #fromShape.AddLine(line, toShape) self.diagram.AddShape(line) line.Show(True) #shape[i].AddLine(line[o], shape[n2]) #line[o] = ogl.LineShape() #line[o].SetCanvas(self) #line[o].MakeLineControlPoints(2) # S def MyAddShape(self, shape, x, y, pen, brush, text): # Composites have to be moved for all children to get in place if isinstance(shape, ogl.CompositeShape): dc = wx.ClientDC(self) self.PrepareDC(dc) shape.Move(dc, x, y) else: shape.SetDraggable(True, True) shape.SetCanvas(self) shape.SetX(x) shape.SetY(y) if pen: shape.SetPen(pen) if brush: shape.SetBrush(brush) if text: for line in text.split('\n'): shape.AddText(line) #shape.SetShadowMode(ogl.SHADOW_RIGHT) self.diagram.AddShape(shape) shape.Show(True) evthandler = MyEvtHandler(self.log, self.frame) evthandler.SetShape(shape) evthandler.SetPreviousHandler(shape.GetEventHandler()) shape.SetEventHandler(evthandler) self.shapes.append(shape) return shape def OnBeginDragLeft(self, x, y, keys): self.log.write("OnBeginDragLeft: %s, %s, %s\n" % (x, y, keys)) def OnEndDragLeft(self, x, y, keys): self.log.write("OnEndDragLeft: %s, %s, %s\n" % (x, y, keys)) #---------------------------------------------------------------------- def runTest(frame, nb, log): # This creates some pens and brushes that the OGL library uses. # It should be called after the app object has been created, but # before OGL is used. ogl.OGLInitialize() win = TestWindow(nb, log, frame) return win #---------------------------------------------------------------------- overview = """

Object Graphics Library

The Object Graphics Library is a library supporting the creation and manipulation of simple and complex graphic images on a canvas.

The OGL library was originally written in C++ and provided to wxPython via an extension module wrapper as is most of the rest of wxPython. The code has now been ported to Python (with many thanks to Pierre Hj?lm!) in order to make it be more easily maintainable and less likely to get rusty because nobody cares about the C++ lib any more.

The Python version should be mostly drop-in compatible with the wrapped C++ version, except for the location of the package (wx.lib.ogl instead of wx.ogl) and that the base class methods are called the normal Python way (superclass.Method(self, ...)) instead of the hacky way that had to be done to support overloaded methods with the old SWIG (self.base_Method(...)) """ def main2(programname, filename): import sys, os import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) if __name__ == '__main__': import sys, os import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) From tiedon_jano at hotmail.com Sun Jan 7 04:25:48 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 07 Jan 2007 09:25:48 GMT Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: W. Watson kirjoitti: > Thomas Ploch wrote: >> https://sourceforge.net/projects/pywin32/ >> >> I think this is the place to go >> >> Thomas >> >> > That gets me the python program (pywin), which I got from a URL in a > post above (python-win.msi). I guess these are the same or at least just > the interpreter, and do not provide the IDE-debugger. I can't get > pythonwin, the debugger and IDE. The link was broken last night when I > tried it. Well, let me try now. Nope, it still reports "Error 404: File > Not Found" I don't understand your difficulties. If you've got Python installed and want to install the "Python for Windows extensions" aka pywin32, the above link is the way to go. Clicking it gets you to a Sourceforge page, where you can click "download" which gets you to ap page where you can choose which version of pywin32 build 210 you want. Choose the exe that was built for the Python version (e.g. 2.5) you are using, download and run it to install pywin32. HTH, Jussi From duncan.booth at invalid.invalid Mon Jan 8 05:37:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jan 2007 10:37:48 GMT Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> <1168189375.843789.306180@51g2000cwl.googlegroups.com> <7xps9q19wf.fsf@ruckus.brouhaha.com> <1168248244.134804.138050@51g2000cwl.googlegroups.com> Message-ID: "Paul Boddie" wrote: > Paul Rubin wrote: >> >> Right, the problem is if those methods start changing the "private" >> variable. I should have been more explicit about that. >> >> class A: >> def __init__(self): >> self.__x = 3 >> def foo(self): >> return self.__x >> >> class B(A): pass >> >> class A(B): >> def bar(self): >> self.__x = 5 # clobbers private variable of earlier class named A > > Has this ever been reported as a bug in Python? I could imagine more > sophisticated "name mangling": something to do with the identity of the > class might be sufficient, although that would make the tolerated > "subversive" access to private attributes rather difficult. > > Paul > If it worries you then you can always check for it and disallow any hierarchies where it could be a problem. For that matter PyChecker ought to be able to catch this situation (maybe it already does, I haven't looked). >>> class SafetyNet(type): def __new__(cls, name, bases, dct): print "new",name c = type.__new__(cls, name, bases, dct) assert not name in [b.__name__ for b in c.__mro__[1:]] return c >>> __metaclass__ = SafetyNet >>> class A: pass new A >>> class B(A): pass new B >>> class A(B): pass new A Traceback (most recent call last): File "", line 1, in class A(B): pass File "", line 5, in __new__ assert not name in [b.__name__ for b in c.__mro__[1:]] AssertionError From vpolukcht at gmail.com Tue Jan 16 09:44:35 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 16 Jan 2007 06:44:35 -0800 Subject: Regular expressions question In-Reply-To: References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> <1168957361.204348.30080@s34g2000cwa.googlegroups.com> Message-ID: <1168958674.976563.91260@l53g2000cwa.googlegroups.com> The same regular expression should work for another string (with *200). On Jan 16, 5:40 pm, Neil Cerutti wrote: > On 2007-01-16, Victor Polukcht wrote: > > > Actually, i'm trying to get the values of first field (Global) , fourth > > (200, 4), and fifth (100%) and sixth (100%). > > > Everything except fourth is simple. > >>> g = "Global etsi3 * 4 ok 30 100% 100% Outgoing" > >>> import re > >>> r = re.search('\*\s+(\d+)', g) > >>> r.group() > '* 4' > >>> r.group(1)'4' > > -- > Neil Cerutti > We're not afraid of challenges. It's like we always say: If you want to go out > in the rain, be prepared to get burned. --Brazillian soccer player From matt at tplus1.com Thu Jan 25 11:54:05 2007 From: matt at tplus1.com (Matthew Wilson) Date: Thu, 25 Jan 2007 16:54:05 GMT Subject: assertions to validate function parameters Message-ID: Lately, I've been writing functions like this: def f(a, b): assert a in [1, 2, 3] assert b in [4, 5, 6] The point is that I'm checking the type and the values of the parameters. I'm curious how this does or doesn't fit into python's duck-typing philosophy. I find that when I detect invalid parameters overtly, I spend less time debugging. Are other people doing things like this? Any related commentary is welcome. Matt -- A better way of running series of SAS programs: http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 14:06:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 06:06:45 +1100 Subject: when format strings attack References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> Message-ID: On Fri, 19 Jan 2007 03:51:08 -0800, Eric_Dexter at msn.com wrote: > http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN > > I saw a warning from homeland security about this. I only comment on > the because I am trying to use os.system('command1 arg') and it doesn't > work What do you mean, doesn't work? It works fine for me, precisely as expected. What does it do for you? Crash Windows? Crash Python? Raise an exception? Return an unexpected result? > but I do see examples with % that is borrowed from the c language. The "When Format Strings Attack" article isn't relevant to Python. Unlike C, Python doesn't arbitrary dump bytes from the stack into a string if you print a string containing %s. In Python, print just prints strings, it doesn't do any string formatting. String formatting is done by the % operator, so print "a string containing %s" is safe. You'd be better off looking at Python examples than C. This is what I'm guessing you're doing: >>> command1 = 'dir' >>> args = '-l text.txt' >>> os.system('command1 arg') sh: command1: command not found 32512 os.system doesn't do name-lookups of the string you pass to it. The right way to do this is some variation on this: >>> commandline = "%s %s" % (command1, args) >>> commandline 'dir -l text.txt' >>> os.system(commandline) -rw-rw-r-- 1 steve steve 333 Sep 24 16:51 text.txt 0 or even something like this: os.system('dir -l %s' % 'text.txt') Now, there is a security risk: you might set command1 yourself, and allow the user to set args. If command1 is an external application with a security hole, and the user provides arguments that trigger that bug, then naturally your application will inherit whatever security vulnerabilities the external application suffers from. No surprises there. -- Steven. From horpner at yahoo.com Fri Jan 26 15:25:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 26 Jan 2007 20:25:28 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> Message-ID: On 2007-01-26, Fabrice DELENTE wrote: >> What have you tried? > > I've tried > > stdscr.addstr(0,0,"a??o?") > > or > > stdscr.addstr(0,0,"le?on") > > The ASCII chars show correctly, but the accented characters > don't, so I see 'ao' or 'leon' on the screen. > > The term in which I display is 8-bit-able, so the problem is > either on ncurses side, or on python side. What happens when you try this? stdscr.addstr(0,0, u"le?on".encode('iso8859-15')) I don't really expect it to work, but if anything will, that is it. Curses supports only ASCII and a some special symbol codes defined by curses. > I have > > #!/usr/local/bin/python > #coding: iso8859-15 Be sure to write your non-ASCII strings as unicode literals, and then encode them just before displaying or storing them somewhere. -- Neil Cerutti -- Posted via a free Usenet account from http://www.teranews.com From duncan.booth at invalid.invalid Tue Jan 16 07:05:16 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jan 2007 12:05:16 GMT Subject: How to convert float to sortable integer in Python References: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> Message-ID: robert wrote: > shellon wrote: >> Hi all: >> I want to convert the float number to sortable integer, like the >> function float2rawInt() in java, but I don't know the internal >> expression of float, appreciate your help! >> > > float comparision works well enough for sorting in Python. What is > the actual requirement? > Maybe this is the problem? >>> sorted([-0.0, 0.0, -0.0, 0.0, -0.0]) [-0.0, 0.0, -0.0, 0.0, -0.0] Java sorting imposes an artificial total ordering on float or double values: > The < relation does not provide a total order on all floating-point > values; although they are distinct numbers -0.0 == 0.0 is true and a > NaN value compares neither less than, greater than, nor equal to any > floating-point value, even itself. To allow the sort to proceed, > instead of using the < relation to determine ascending numerical > order, this method uses the total order imposed by > Double.compareTo(java.lang.Double). This ordering differs from the < > relation in that -0.0 is treated as less than 0.0 and NaN is > considered greater than any other floating-point value. For the > purposes of sorting, all NaN values are considered equivalent and > equal. From nmm1 at cus.cam.ac.uk Thu Jan 11 05:37:20 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 11 Jan 2007 10:37:20 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> In article , Sergei Organov writes: |> |> OK, then I don't think the POSIX threads were "perpetrated" to be idle |> most of time. Perhaps I was being unclear. I should have added "In the case where there are more threads per system than CPUs per system". The reasons are extremely obscure and are to do with the scheduling, memory access and communication. I am in full agreement that the above effect was not INTENDED. |> > That is why many POSIX threads programs work until the genuinely |> > shared memory accesses become frequent enough that you get some to the |> > same location in a single machine cycle. |> |> Sorry, I don't understand. Are you saying that it's inherently |> impossible to write an application that uses POSIX threads and that |> doesn't have bugs accessing shared state? I thought that pthreads |> mutexes guarantee sequential access to shared data. Or do you mean |> something entirely different? Lock-free algorithms maybe? I mean precisely the first. The C99 standard uses a bizarre consistency model, which requires serial execution, and its consistency is defined in terms of only volatile objects and external I/O. Any form of memory access, signalling or whatever is outside that, and is undefined behaviour. POSIX uses a different but equally bizarre one, based on some function calls being "thread-safe" and others forcing "consistency" (which is not actually defined, and there are many possible, incompatible, interpretations). It leaves all language aspects (including allowed code movement) to C. There are no concepts in common between C's and POSIX's consistency specifications (even when they are precise enough to use), and so no way of mapping the two standards together. Regards, Nick Maclaren. From calfdog at yahoo.com Wed Jan 31 16:46:07 2007 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 31 Jan 2007 13:46:07 -0800 Subject: Python tools to manipulate JARs ? In-Reply-To: References: <1170259882.613769.118210@v45g2000cwv.googlegroups.com> Message-ID: <1170279967.794312.42990@j27g2000cwj.googlegroups.com> On Jan 31, 1:50 pm, Laszlo Nagy wrote: > Andy Dingley ?rta:> I run build processes for a Java shop using Python (and some Ant). > > > Would anyone care to suggest favoured tools for manipulating the > > innards of JARs? Or do I just treat them as plain zipfiles and get > > stuck right in there? > > > Mainly I'm trying to query lists of classes and their embedded > > versions and do some library dependency reporting. Performance speed > > is starting to be an issue, as there's 1500+ classes in this bucket > > and it's an interactive query. > > I believe that you can rename any jar file to .zip and use zip tools to > list its contents. > > Laszlo To print out the classes you can use zipfile it will list the contents of a jar file also import zipfile zf = zipfile.ZipFile("some.jar") for info in zf.infolist(): print info.filename Or print to a file import zipfile zf = zipfile.ZipFile("some.jar") for info in zf.infolist(): classes = info.filename myfile = file("classes.txt", 'w') print >> myfile, classes Enjoy -Rob Marchetti From weekender_ny at yahoo.com Sat Jan 13 23:54:47 2007 From: weekender_ny at yahoo.com (John) Date: 13 Jan 2007 20:54:47 -0800 Subject: Threaded for loop In-Reply-To: <1168747208.275625.55590@51g2000cwl.googlegroups.com> References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> <1168747208.275625.55590@51g2000cwl.googlegroups.com> Message-ID: <1168750487.337511.213600@38g2000cwa.googlegroups.com> Thanks. Does it matter if I call shell commands os.system...etc in calculate? Thanks, --j parallelpython at gmail.com wrote: > John wrote: > > I want to do something like this: > > > > for i = 1 in range(0,N): > > for j = 1 in range(0,N): > > D[i][j] = calculate(i,j) > > > > I would like to now do this using a fixed number of threads, say 10 > > threads. > > What is the easiest way to do the "parfor" in python? > > > > Thanks in advance for your help, > > As it was already mentioned before threads will not help in terms of > parallelism (only one thread will be actually working). If you want to > calculate this in parallel here is an easy solution: > > import ppsmp > > #start with 10 processes > srv = ppsmp.Server(10) > > f = [] > > for i = 1 in range(0,N): > for j = 1 in range(0,N): > #it might be a little bit more complex if 'calculate' depends on > other modules or calls functions > f.append(srv.submit(calculate, (i,j))) > > for i = 1 in range(0,N): > for j = 1 in range(0,N): > D[i][j] = f.pop(0) > > You can get the latest version of ppsmp module here: > http://www.parallelpython.com/ From hg at nospam.org Mon Jan 15 03:42:19 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 09:42:19 +0100 Subject: check if there is data in stdin without blocking References: <4PMqh.47441$X97.9536@newsfe18.lga> Message-ID: hg wrote: > Hi, > > Is there a way ? ... select ? > > > > hg PS: import sys import select l_r = select.select([sys.stdin],[],[],0) gives me: File "select.py", line 2, in ? import select File "/home/philippe/Desktop/select.py", line 4, in ? l_r = select.select([sys.stdin],[],[],0) TypeError: 'module' object is not callable From scott.daniels at acm.org Sun Jan 7 22:50:16 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 07 Jan 2007 19:50:16 -0800 Subject: how to find the longst element list of lists In-Reply-To: References: Message-ID: <45a1b4da$1@nntp0.pdx.net> Dan Sommers wrote: > ... > longest_list, longest_length = list_of_lists[ 0 ], len( longest_list ) > for a_list in list_of_lists[ 1 : ]: > a_length = len( a_list ) > if a_length > longest_length: > longest_list, longest_length = a_list, a_length > will run faster than sorting the list just to pick off one element (O(n) > vs. O(n log n) for all of you Big-Oh notation fans out there; you know > who you are!). Or, more succinctly, after: list_of_lists = [["q", "e", "d"], ["a", "b"], ["a", "b", "c", "d"]] You can find the longest with: maxlength, maxlist = max((len(lst), lst) for lst in list_of_lists) or (for those pre-2.5 people): maxlength, maxlist = max([(len(lst), lst) for lst in list_of_lists]) --Scott David Daniels scott.daniels at acm.org From nospam at nospam.com Tue Jan 30 20:48:45 2007 From: nospam at nospam.com (soutjhyDin) Date: Tue, 30 Jan 2007 19:48:45 -0600 Subject: BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job References: <1170200864.492655.11850@s48g2000cws.googlegroups.com> Message-ID: <45bff548$0$97249$892e7fe2@authen.yellow.readfreenews.net> wrote in message news:1170200864.492655.11850 at s48g2000cws.googlegroups.com... > http://portland.indymedia.org/en/2006/06/341238.shtml > > BYU Physics Prof Finds Thermate in WTC Physical Samples, Building > Collapses an Inside Job > author: Jacob Hamblin > Based on chemical analysis of WTC structural steel residue, a Brigham > Young University physics professor has identified the material as > Thermate. Thermate is the controlled demolition explosive thermite > plus sulfur. WRONG! you must make this stuff up as you go along. Thermate and thermite have nothing to do with "controlled demolition", moron. What is the prime ingredient of both? Rust. The Iron Oxide(s), dummy. From olsonas at gmail.com Mon Jan 29 13:57:36 2007 From: olsonas at gmail.com (Drew) Date: 29 Jan 2007 10:57:36 -0800 Subject: List Behavior when inserting new items Message-ID: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> I'm looking to add an element to list of items, however I'd like to add it at a specific index greater than the current size: list = [1,2,3] list.insert(10,4) What I'd like to see is something like: [1,2,3,,,,,,4] However I see: [1,2,3,4] Is there any way to produce this kind of behavior easily? Thanks, Drew From dilbert01 at gmail.com Mon Jan 22 11:13:05 2007 From: dilbert01 at gmail.com (alessandro) Date: 22 Jan 2007 08:13:05 -0800 Subject: closing a "forever" Server Socket In-Reply-To: <1169143715.222186.30530@51g2000cwl.googlegroups.com> References: <1169123381.930403.24170@38g2000cwa.googlegroups.com> <1169143715.222186.30530@51g2000cwl.googlegroups.com> Message-ID: <1169482385.253887.249030@51g2000cwl.googlegroups.com> thanks infact the server_forever() method is only a serve() method inside an infinite loop. many thanks again, Alessandro Matimus ha scritto: > > I want to ask if someone knows a better way for closing a "forever > > server" or if there is a lack in my design. > > Generally you don't create a 'forever server'. You create an 'until I > say stop' server. I would do this by looking at the 'serve_forever' > method, and implementing my own 'serve_until_?' method that is similar, > but will stop if a flag is set. Then you have to create a method for > setting that flag. It could be as simple as a keypress, or you could > add a quit method to your dispatcher that sets the flag when a certain > address is visited. That second method probably needs some added > security, otherwise anybody can just visit 'your.server.com/quit' and > shut it down. From larry.bates at websafe.com Tue Jan 30 19:32:02 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 30 Jan 2007 18:32:02 -0600 Subject: Sorting a List of Lists In-Reply-To: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> References: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> Message-ID: apotheos at gmail.com wrote: > I can't seem to get this nailed down and I thought I'd toss it out > there as, by gosh, its got to be something simple I'm missing. > > I have two different database tables of events that use different > schemas. I am using python to collate these records for display. I do > this by creating a list of lists that look roughly like this: > > events = [['Event URL as String', 'Event Title as String ', Event Date > as Datetime], ...] > > I then thought I'd just go events.sort(lambda x,y: x[2] it a day. That didn't work. But then lamda functions like to be very > simple, maybe object subscripts aren't allowed (even though I didn't > get an error). So I wrote a comparison function that looks much as you > would expect: > > def date_compare(list1, > list2): > x = list1[2] > y = list2[2] > if > x>y: > return > 1 > elif > x==y: > return > 0 > else: # > x return -1 > > But as before sorting with this function returns None. > > What have I overlooked? > Sort doesn't return a list, it sorts in place. None is the result code (if you will) of the sort completion. -Larry From martin.witte at gmail.com Fri Jan 5 10:10:14 2007 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 5 Jan 2007 07:10:14 -0800 Subject: How to get file name on a remote server with ftplib? In-Reply-To: <1168008952.020516.130890@s80g2000cwa.googlegroups.com> References: <1168008952.020516.130890@s80g2000cwa.googlegroups.com> Message-ID: <1168009814.236723.105280@51g2000cwl.googlegroups.com> alex wrote: > Hello, > > My script is trying to get a file from a remote server, every day it > ftps from a directory. My code works perfect if I know the name of the > file in the remote directory. > > ftp.retrbinary('RETR ' + filename, handleDownload) > > The problem is that in the future the name of the file is going to be > aleatory. How can I get the file's name (only one file is in that > directory) and store it in a variable before executing ftp.retrbinary? > > Thanks a lot for your help, > > Alex You can use the nlst(dirname) method to retrieve a directory listing on the remote server. If the remote server doesn't support NLST command rhen you could do ftp.retrlines('LIST') and parse the results to get a directory listing. From gagsl-py at yahoo.com.ar Thu Jan 25 14:36:21 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 16:36:21 -0300 Subject: How can i do this in Python? References: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> <1169719194.084162.148380@v33g2000cwv.googlegroups.com> Message-ID: escribi? en el mensaje news:1169719194.084162.148380 at v33g2000cwv.googlegroups.com... > I'm just curious, what's the advantage of using itemgetter there > compared to something simpler like this (untested!)? None! -- Gabriel Genellina From antroy at gmail.com Fri Jan 5 03:44:49 2007 From: antroy at gmail.com (Ant) Date: 5 Jan 2007 00:44:49 -0800 Subject: Anyone persuaded by "merits of Lisp vs Python"? In-Reply-To: <1167324666.002153.27570@a3g2000cwd.googlegroups.com> References: <1167324666.002153.27570@a3g2000cwd.googlegroups.com> Message-ID: <1167986689.741094.252270@v33g2000cwv.googlegroups.com> Hi all, On Dec 28 2006, 4:51 pm, "Paddy3118" wrote: > This month there was/is a 1000+ long thread called: > "merits of Lisp vs Python" > In comp.lang.lisp. > > If you followed even parts of the thread, AND previously > used only one of the languages AND (and this is the > crucial bit), were persuaded to have a more positive view > of the other language; I sort of fall into this category. I'm a Java developer by trade, but use Python for all of my non-work related projects, and any scripting I need at work. I hadn't looked at Lisp. I've been tempted a few times to look more into Lisp, especially after reading some of Paul Graham's stuff which has a strong bias toward Lisp. The thread gave me a kick start into looking into Lisp more deeply, and over the Christmas break I downloaded CLisp and ordered a couple of Lisp books. There were no arguments that persuaded me particularly - more curiosity about a few of the concepts that were bandied about: a) Closures - and what they give you that Python co-routines don't. b) Macros - how they can be used, and what advantages they give you. They were the real persuasion points for me. So far? After a bit of pain getting started and finding decent docs (while waiting for the books to arrive) I've found the language quite easy to use. I haven't got into closures or macros yet - I need to get more familiar with the basics first, but first impressions are favorable. It seems that there is nothing conceptually in Python that I can't reasonably easily do in Lisp, but the Python syntax is much more straightforward for most of the basics I think (such as dictionaries, sets, list comprehensions etc), and the function/naming conventions for the core language is much clearer and more obvious than in Lisp. From carsten at uniqsys.com Thu Jan 4 20:21:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 04 Jan 2007 20:21:19 -0500 Subject: Turn off line wrap for lists? In-Reply-To: <1167958863.538291.60820@s34g2000cwa.googlegroups.com> References: <1167958863.538291.60820@s34g2000cwa.googlegroups.com> Message-ID: <1167960079.3332.7.camel@localhost.localdomain> On Thu, 2007-01-04 at 17:01 -0800, _ wrote: > (I did google for this, I promise) > > How do I get python NOT to insert newlines into string representations > of lists when I do something like this: > > strCollector += "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements'] > * 100) What makes you think that that inserts newline characters? My python doesn't do that: >>> a = "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements'] * 100) >>> "\n" in a False > FYI I am using this to export data into tab delimited format You could avoid reinventing the wheel by using the "csv" module. -Carsten From sturlamolden at yahoo.no Tue Jan 9 10:04:11 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 9 Jan 2007 07:04:11 -0800 Subject: Execute binary code In-Reply-To: References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> Message-ID: <1168355051.339026.211830@v33g2000cwv.googlegroups.com> Jorgen Grahn wrote: > For what it's worth[1], under Unix it /is/ impossible. The only way to bring in > new code (short of dynamic libraries) is to call exec(2) or its variations, > and all need a file system object to load the code from. The x86 processor cannot tell the difference between code segments and data segments. If the executable code is stored in string, all you need is a pointer to the string holding the code. You can cast the string address to a function pointer (possibly through a void* if the compiler complains), then dereference (call) the function pointer. Trojans, viruses and JIT compilers do this all the time. Here is an (untested) example: static PyObject* call_code_in_string(PyObject *self, PyObject *args) { char *s; int size; int arg1, arg2, arg3; typedef int (*func_t)(int,int,int); func_t pfunc; if(!PyArg_ParseTuple(args, "s#(iii)", &s, &size, &arg1, &arg2, &arg3)) return NULL; pfunc = (func_t)((void *)s); /* if it fails, try memcpy(&pfunc,&s,sizeof(void*)) instead */ return PyInt_FromLong((long)pfunc(arg1, arg2, arg3)); } Another possibility would be to just return the string address, and then make the call possibly using ctypes. static PyObject* get_string_addr(PyObject *self, PyObject *args) { char *s; int size; if(!PyArg_ParseTuple(args, "s#", &s, &size)) return NULL; return PyInt_FromLong((long)((void*)s)); } From rzantow at gmail.com Sat Jan 6 14:47:43 2007 From: rzantow at gmail.com (rzed) Date: Sat, 06 Jan 2007 14:47:43 -0500 Subject: still struggling, howto use a list-element as a name ? References: Message-ID: Stef Mientki wrote in news:b7908$459fef43$d443bb3a$26766 at news.speedlinq.nl: > In the example below, "pin" is an object with a number of > properties. Now I want > 1- an easy way to create objects that contains a number of these > "pin" 2- an multiple way to access these "pin", i.e. > device.pin[some_index] > device.some_logical_name > ad 1: > a dictionary (as "pinlist" in the example) seems a very > convenient > way (from a viewpoint of the device creator). > As you can see in the "__init__" section this dictionary can > easily be transported to the pin-objects. > > ad 2: > THAT's the problem: how do automate these lines "self.GND = > self.pin[0]" > > I'm also in for other solutions. > > thanks, > Stef > > > class Power_Supply(device): > pinlist = { > 0: ('GND', _DIG_OUT, _par2), > 1: ('VCC', _DIG_OUT, _par33) > } > > def __init__(self): > # store pin-names and pin-parameters in pins > for k in self.pinlist.keys(): > self.pin[k].Name = self.pinlist[k][0] > self.pin[k].Value = self.pinlist[k][2] > > # for some pins, we also want to be able to use logical > names # HOW TO USE SOMETHING like > # "self.pinlist[0] = self.pin[0]" > # INSTEAD OF > self.GND = self.pin[0] > self.VCC = self.pin[1] > > # create a Power_Supply instance and > # test if pins can be referenced in > Power = Power_Supply() > netlist1 = ( Power.VCC, Power.pin[1], Power.GND, Power.pin[0] ) I may be confused about what you're after, but wouldn't something like this work? (I don't know what a _par2 object is; I've named it something here.) class Power_Supply(device): def __init__(self): self.pin = { 0:dict(Name='GND',Value=_DIG_OUT,something=_par2), 1:dict(Name='VCC',Value=_DIG_OUT,something=_par33), } for k in self.pin.keys(): self.__dict__[self.pin[k]['Name']] = self.pin[k] From nono at hotmail.com Mon Jan 1 12:39:57 2007 From: nono at hotmail.com (Osiris) Date: Mon, 01 Jan 2007 18:39:57 +0100 Subject: BOOST confuses me: a few assumptions: true or false..... Message-ID: I read a lot of the html pages on installing boost etc. Still a lot of confusion. Here is what I want: I have old, stable wonderful C-code I want to use in Python projects. So I encapsulate the C-code in some C++ stuf and try to compile it into a DLL. 1: I DL-ed boost_1_33_1.exe (I use WinXP) and unpacked to D:\boost 2: I started my MS Visual C++ 2005 and told the Studio that my python2.4 includes and libs are at c:\python24\include and c:\python24\libs 3: I found the project in D:\boost\libs\python\build\VisualStudio and Studio converted that to the 8.0 version of my VC. 4: I compiled and got stuff in D:\boost\libs\python\build\bin-stage: 208.896 boost_python.dll 99.090 boost_python.exp 166.216 boost_python.lib 532.480 boost_python_debug.dll 99.102 boost_python_debug.exp 168.490 boost_python_debug.lib 6.450.176 boost_python_debug.pdb (the numbers are sizes) Am I now set up to start on my own projects ? Do I need bjam from here on ? or can I continue to do my own projects in VC ? do I need all the stuff in the folders like D:\boost\libs\* (except D:\boost\libs\python) ? they do not seem to be used till now... here is an example of mine, to play around with: However, I get the compile log (http://213.10.133.192/BuildLog.htm) ======================================== #include #include namespace { // Avoid cluttering the global namespace. int my_int; /* a global integer: or outside namespace ? */ double calc ( double f) { my_int = (int) (f/2); // printf( "Half of %f is %d\n", f, my_int ); return f/2; } } #include using namespace boost::python; BOOST_PYTHON_MODULE( half ) { def("calc", calc ); } From aeon.descriptor at gmail.com Tue Jan 30 05:33:42 2007 From: aeon.descriptor at gmail.com (Brian Visel) Date: Tue, 30 Jan 2007 05:33:42 -0500 Subject: Is any python like linux shell? In-Reply-To: 1169398326.510530.180860@51g2000cwl.googlegroups.com References: 1169398326.510530.180860@51g2000cwl.googlegroups.com Message-ID: <1170153222.5050.22.camel@orbital.earthlink.net> ipython is probably what you're looking for. From nogradi at gmail.com Wed Jan 31 14:25:57 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 31 Jan 2007 20:25:57 +0100 Subject: subway In-Reply-To: References: <5f56302b0701310802y7e45c98fmaaebe090e34d410@mail.gmail.com> <17856.50898.477998.112022@montanaro.dyndns.org> Message-ID: <5f56302b0701311125nca98bc7gfe4e036357aa21c7@mail.gmail.com> > > the egg file can not be downloaded completely, the connection is > > closed at byte 138903 all the time and the file is bigger than that. > > If anyone managed to grab the file please let me know so far I tried > > wget and firefox. > > I've checked on my hd and found a recent (Jun 2006) checkout > on the original SVN repos. > > There's everything in it: Subway code, web site and examples: > > > > HTH Great! Thanks very much indeed. From martin at v.loewis.de Mon Jan 8 02:25:13 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 08 Jan 2007 08:25:13 +0100 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> Message-ID: <45A1F1D9.8070206@v.loewis.de> vizcayno schrieb: > Need your help in the "correct" definition of the next function. If > necessary, I would like to know about a web site or documentation that > tells me about best practices in defining functions, especially for > those that consider the error exceptions management. I agree with George Sakkis' remarks. The best way to define this function is def ExecuteSQL(cmdSQL, cursor): return cursor.execute(cmdSQL) If this raises an exception, it likely means there is something wrong with the SQL statement. The program should abort, and the developer should correct it. Regards, Martin From steve at holdenweb.com Thu Jan 11 11:43:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Jan 2007 16:43:54 +0000 Subject: Newbie question: SMTP -> SQL Server In-Reply-To: <1168531934.015865.177100@i56g2000hsf.googlegroups.com> References: <1168529572.873867.207730@k58g2000hse.googlegroups.com> <1168531934.015865.177100@i56g2000hsf.googlegroups.com> Message-ID: jrpfinch wrote: > Thank you. I have just realised I completely misunderstand how SMTP > servers work. From what I can tell, when you run the cookbook script > it listens locally on port 8025. > > You then have to configure a Linux (in my case) account with a username > and password so my external piece of software (on another Windows > machine) can log in and use the SMTP server. > > Then I write the some code in the cookbook example to redirect any mail > content to the MS SQL server database. > > Note that the external piece of software can only talk SMTP - this is > why I am having to develop this script. > > Does this sound sensible? Any tips on how to configure my Linux box (I > don't have much experience with Linux either)? > > Many thanks > > Jon > Presumably you can configure the external piece of software at least to the extent of setting the email address it delivers to? In that case it will be *much* simpler to set up an account on a mail server to receive these emails. That way the server will be available whenever the SMTP-based sender wants or needs to send mail, and you can use Python to collect the emails in batched using the POP protocol, as a client. Once you receive the email messages then yes, it's perfectly practical to save the content in a SQL server database. mxODBC is one possible driver package (though it requires you to purchase a license for commercial use), and I seem to remember there's another one called adodbapi that is open source. There are almost certainly others, but it's a while since I used SQL Server with Python. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From fdelente at mail.cpod.fr Fri Jan 26 14:04:39 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 26 Jan 2007 19:04:39 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> Message-ID: <45ba50c7$0$31432$426a74cc@news.free.fr> > What have you tried? I've tried stdscr.addstr(0,0,"a??o?") or stdscr.addstr(0,0,"le?on") The ASCII chars show correctly, but the accented characters don't, so I see 'ao' or 'leon' on the screen. The term in which I display is 8-bit-able, so the problem is either on ncurses side, or on python side. I have #!/usr/local/bin/python #coding: iso8859-15 at the top of my python file. -- Fabrice DELENTE From no-spam at no-spam-no-spam.invalid Mon Jan 1 07:51:51 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Mon, 01 Jan 2007 13:51:51 +0100 Subject: Forking in windows. Possible? In-Reply-To: <1165949756.863476.57870@73g2000cwn.googlegroups.com> References: <1165949756.863476.57870@73g2000cwn.googlegroups.com> Message-ID: dakman at gmail.com wrote: > I know under mac/*nix it's possible to fork the proccess to the > background and exit the parent process. I have used this on a couple of > my projects, but right now I am working on a project that will be > required to run in the background, I have considered using the .pyw > extension on my files, but there will be parts of the program that will > be required to show the console. So if anyone has an ideas... > > -Thanks > "Background" has not much meaning on Win as long as not another process is waiting for return. And you obviously want to click an icon in Explorer. If you don't need the data memory status of the current process inherited, CreateProcess would be most similar. Then there is win32console.GetConsoleWindow , ShowWindow(SW_HIDE), win32console.AllocConsole, win32ui.CreateEdit, taskbar functions, win32service etc. Robert From marcpp at gmail.com Fri Jan 26 07:40:28 2007 From: marcpp at gmail.com (Marcpp) Date: 26 Jan 2007 04:40:28 -0800 Subject: Mounting shares with python Message-ID: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> Hi, when i mount a share with python... os.system ("mount -t smbfs -o username=nobody ...") the problem is that I'll to be root. Have a comand to send a root password...? I've tried os.system ("su") os.system ("the password") but it doesn't works. From michael at mustun.ch Wed Jan 3 20:10:44 2007 From: michael at mustun.ch (Michael M.) Date: Thu, 04 Jan 2007 02:10:44 +0100 Subject: code optimization (calc PI) / Full Code of PI calc in Python and C. In-Reply-To: <1167872076.937415.250340@11g2000cwr.googlegroups.com> References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> <1167872076.937415.250340@11g2000cwr.googlegroups.com> Message-ID: Ok, here is the code. It is a translation of the following code, found on the internet. * The C is very fast, Python not. * Target: Do optimization, that Python runs nearly like C. Auf 800 Stellen in 160 Zeichen... ------ int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5; for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a, f[b]=d%--g,d/=g--,--b;d*=b);} $ ./a.exe 31415926535897932384626433832795028841971693993751058209749445923078164062862089 98628034825342117067982148086513282306647093844609550582231725359408128481117450 28410270193852110555964462294895493038196442881097566593344612847564823378678316 52712019091456485669234603486104543266482133936072602491412737245870066063155881 74881520920962829254091715364367892590360011330530548820466521384146951941511609 43305727036575959195309218611738193261179310511854807446237996274956735188575272 48912279381830119491298336733624406566430860213949463952247371907021798609437027 70539217176293176752384674818467669405132000568127145263560827785771342757789609 17363717872146844090122495343014654958537105079227968925892354201995611212902196 08640344181598136297747713099605187072113499999983729780499510597317328160963185 Here the Python: ---------------------------------------------------- #!/usr/bin/python # -*- coding: utf-8 -*- ## http://de.wikipedia.org/wiki/Pi_(Kreiszahl) from __future__ import division from array import array import decimal import time #int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5; # for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a, # f[b]=d%--g,d/=g--,--b;d*=b);} # print "\nTiming a 1 million loop 'for loop' ..." start = time.clock() for x in range(1000000): y = x # do something end = time.clock() print "Time elapsed = ", end - start, "seconds" start_prg = time.clock() #pi=[] ## create an empty array pi='' a=10000 b=0 c=5600 ## c=2800 d=0 e=0 f=[] # f[2801] g=0 counter=c while 0<=counter+4000: f.append(2000) # f.append( int(a/5) ) counter=counter-1 # b=b+1 #print "DEBUG: b counter: ", b, counter while (c*2): d=0 g=c*2 ## see while condition ## --------------------------- b=c ## anzahl elemente #print "DEBUG: before 3 while loop..." #print "DEBUG: b=", b while (b-1): d = d + f[b]*a g=g-1 f[b] = d%g d = int(d/g) ## needs cast to int g=g-1 d=d*b b=b-1 ## see while condition #print "DEBUG: d=", d c = c-14; #pi.append(str("%04d" % int(e + d/a))) # append to it pi = pi + str("%04d" % int(e + d/a)) #print "%04d" % int(e + d/a), ## need cast to int #print int(e + int(d/a)) e = d%a; #print "".join(pi) print pi end_prg = time.clock() print "Total Time elapsed = ", end_prg - start_prg, "seconds" ## EOF. ------------------------------- Matimus wrote: >>If someone is really interested in speed optimization, I can publish my >>PI-calc code. > > > I wouldn't mind seeing it. Chances are you will get much better help if > you post your code anyway. > > -Matt > From bdesth.quelquechose at free.quelquepart.fr Tue Jan 9 18:19:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 Jan 2007 00:19:35 +0100 Subject: injecting functions into a python sandbox within a python program In-Reply-To: <45a4172e$0$71751$c30e37c6@ken-reader.news.telstra.net> References: <45a4172e$0$71751$c30e37c6@ken-reader.news.telstra.net> Message-ID: <45a41cb7$0$308$426a74cc@news.free.fr> Graham Menhennitt a ?crit : > I have a large Python 2.5 program that I want my users to be able to > "extend" using a Python script. However, I want their script to run in a > sandbox within the overall program so that they only have access to the > rest of the program via a single simple interface. Note that this is not > meant to be a real anti-hacker type security sandbox - just "help them > to avoid shooting themselves in the foot" type security. > > So I created a single object that has the interface that I want them to > access. I call their script via "exec" passing the single interface > object in the "globals" parameter to exec. It (conceptually) looks like > this: > > i = Interface() > glob = { 'i': i } > exec script in glob > > Then they can call i.whatever() from within their script. This all works > fine. > > Now, what I want to do is provide some "helper" functions for them to > use in the script. These functions still only access the rest of the > program via 'i'. They just wrap some of the interface functions to make > life easier for the user. My current solution is to prepend these > functions onto the start of the script. I.e. > > helperFuncs = """ > def f1(): i.whatever() > """ > > exec helperFuncs + "\n" + script.read() in glob > > This works but doesn't seem very elegant. Indeed. If all your helper functions are really methods of the Interface instance, you may try this instead (NB : not tested): glob = { 'i': i, 'f1': i.whatever, } exec script in glob HTH From tmaroff at yahoo.com Wed Jan 10 21:24:08 2007 From: tmaroff at yahoo.com (Tristan) Date: 10 Jan 2007 18:24:08 -0800 Subject: IDLE Python and Environment Variables Message-ID: <1168482248.828858.161320@i39g2000hsf.googlegroups.com> Hello community: I post this because I could not find satisfactory answers in the posts generated by this nice group. I work on winXP. I have many little python applications in different folders, each application can share or not other objects located in the same or other folders. The way I work to use these applications is: 1) For almost everyone, I execute a corresponding ".bat file" into which I define and/or include values for some "temporal" environment variables that let me find all the objects that the selected application uses. Sometimes I include in the .bat file the execution of the application, but generally I leave in a prompt status, ready to invoke python or some dos commands. 2) When I close the command prompt window, there are no traces of my enviroment variables in my windows system (that is right). Only the default windows environment variables remain. I tried to do the same with the IDLE (and I imagine tha same occurs with Python command line), but I have the next problem: I can not find in IDLE (or another app?) the way to previously define and/or include automatically values for my "temporal" environment variables as I do in the .bat files. The use of Control Panel -> System -> Advanced is tedious to use as, my enviroment variables values are "temporal". Any advice, please??? From ccw.thomas at gmail.com Mon Jan 22 22:48:13 2007 From: ccw.thomas at gmail.com (ThomasC) Date: 22 Jan 2007 19:48:13 -0800 Subject: Try to porting Python2.5 to Zaurus Message-ID: <1169524093.736183.43370@q2g2000cwa.googlegroups.com> Hi, I'm a python newbie, I learn it on my notebook, but it too heavy and too big. I try to porting python2.5 to my Zaurus, It running on Zaurus well, (just for my study, I didn't test all modules and functions.) If you have a Zaurus, and like python, welcome to use it. I post it on here: http://bean-pig.idv.tw/emb_study/archives/001049.html Best Regards, Thomas# From toto at titi.de Fri Jan 5 16:25:20 2007 From: toto at titi.de (laurent rahuel) Date: Fri, 05 Jan 2007 22:25:20 +0100 Subject: find a .py path In-Reply-To: References: Message-ID: <459ec336$0$21144$7a628cd7@news.club-internet.fr> Hi, What about : import os.path print os.path.abspath(__file__) hg a ?crit : > Hi, > > Is there an easy way for a script being executed (from anywhere) to know > where is is ... something in os.path ? > > Thanks, > > hg > From dummy at dummy.nl Thu Jan 18 07:59:50 2007 From: dummy at dummy.nl (Cecil Westerhof) Date: Thu, 18 Jan 2007 13:59:50 +0100 Subject: Is it possible to fasten the import of cgi? Message-ID: <45af6f47$0$322$e4fe514c@news.xs4all.nl> I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I can not time the time used to import time, but os and sys do not take more as a millisecond. My script itself takes 3 or 4 milliseconds. But importing cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is there a way to make this more fast? The import off cgi makes the script at least 20 times as slow. Something like mod-python is not a possibility. I could use it on my test machine, but not at the osting provider. From deets at nospam.web.de Tue Jan 9 02:18:58 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Jan 2007 08:18:58 +0100 Subject: class unbound method and datetime.datetime.today() In-Reply-To: <1168324795.850400.65150@i15g2000cwa.googlegroups.com> References: <1168324795.850400.65150@i15g2000cwa.googlegroups.com> Message-ID: <50gtv7F1g042nU1@mid.uni-berlin.de> cinsky at gmail.com schrieb: > Hi, I got confused when I learned the function datetime.today(). > > So far I learned, unless an instance is created, it is not possible to > call the class method. For example: > > class Foo: > def foo(self): > pass > > Foo.foo() # error: unbound method foo(). > > What makes me confused is that datetime class? in datetime module > provides today() function that returns the datetime object. > >>>> import datetime >>>> datetime.datetime.today() > datetime.datetime(2007, 1, 9, 15, 34, 35, 23537) > > It looks like that datetime class provides today() method that can be > callable even if it is unbound method. Do I correct? > > If it is possible to make that kind of function (looks like static > member function in C++), how can I make that? It is called a classmethod (in contrast to an instancemethod, which is the usual thing), and you can do it - depending on the version of python you have - using the built-in funtion/decorator "classmethod". Like this: class Foo(object): @classmethod def bar(cls): pass Note that a classmethod gets passed the class as first argument, not an instance. You can also create static methods, using "staticmethod". They won't get passed anything. Diez From michele.simionato at gmail.com Wed Jan 10 23:47:14 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 Jan 2007 20:47:14 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <45A18D68.5020308@v.loewis.de> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <45A18D68.5020308@v.loewis.de> Message-ID: <1168490834.576808.183840@k58g2000hse.googlegroups.com> Martin v. L?wis wrote: > If you want to, you can combine this with the factory/singleton > patterns, to transparently create the objects on first access: > > class Registry: > def __getitem__(self, name): > # only invoked when attribute is not set > r = pin(name) > setattr(self, name, r) > return r > registry = Registry() > > class pin: > def __init__(self, name): > self.name = name > > print registry.aap You probably meant __getattr__ instead of __getitem__ here ;) This is an interesting approach, but I would probabily use the traditional registry you discussed before (too much magic here). Michele Simionato From dotancohen at gmail.com Thu Jan 4 01:15:09 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 4 Jan 2007 08:15:09 +0200 Subject: Unsubscribing from the list In-Reply-To: <459C19D5.2040706@dcube-resource.be> References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> <880dece00701031247l3d2354a3le318340653969de8@mail.gmail.com> <459C19D5.2040706@dcube-resource.be> Message-ID: <880dece00701032215i646bec13kddd953b7f69e3c1c@mail.gmail.com> On 03/01/07, Jan Dries wrote: > Dotan Cohen wrote: > > On 03/01/07, Robert Kern wrote: > >> He misunderstood you (as I nearly did, too). The way you phrased "decided that > >> there was no futher interest on the page for me" is somewhat ambiguous: it can > >> seem like it refers to the second time, not the first. > >> > > > > Ah. Sorry. I'm getting better at confusing people :) > > > > if ($you=="got_offended") { > > $dotan="sorry"; > > } > > Except that on this list, you might offend people just by using vulgar > language like that. Better rephrase it to: > > if you == "got_offended": > dotan = "sorry" > > Er, that was quite the reason that I subscribed to the list in the first place- to abandon php and get into python. I think that I had better unsubscribe soon before I do any more damage :) Thanks, all, for the wonderfully entertaining thread. I'll resubscribe in a few months when I actually do have time to learn a new language- and I hope that I haven't ruined any goodwill here. That was never my intention, anyway. Dotan Cohen http://essentialinux.com/linux-software.php http://tussik.com From hg at nospam.org Fri Jan 5 04:09:00 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 10:09:00 +0100 Subject: find a .py path Message-ID: Hi, Is there an easy way for a script being executed (from anywhere) to know where is is ... something in os.path ? Thanks, hg From wolfgang.grafen at marconi.com Tue Jan 16 10:02:36 2007 From: wolfgang.grafen at marconi.com (Wolfgang Grafen) Date: Tue, 16 Jan 2007 16:02:36 +0100 Subject: Regular expressions question In-Reply-To: <1168947810.175793.228620@51g2000cwl.googlegroups.com> References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> Message-ID: Victor Polukcht wrote: > I have 2 strings: > > "Global etsi3 *200 ok 30 100% 100% > Outgoing" > and > "Global etsi3 * 4 ok 30 100% 100% > Outgoing" > > The difference is "*200" instead of "* 4". Is there ability to write a > regular expression that will match both of that strings? > ---------------------------- x.py begin -------- import re s1 = "Global etsi3 *200 ok 30 100% 100% Outgoing" s2 = "Global etsi3 * 4 ok 30 100% 100% Outgoing" re_m = re.compile( "^" "(\S+)" # Global "\s+" "(\S+)" # etsi3 "\s+" "((\*)\s*(\d+))" # *200 * 4 "\s+" "(\S+)" # ok "\s+" "(\S+)" # 30 "\s+" "(\S+)" # 100% "\s+" "(\S+)" # 100% "\s+" "(\S+)" # Outgoing "$" ).match print "match s1:", re_m(s1).groups() print "match s2:", re_m(s2).groups() ----------------------------- x.py file end --------- % python x.py match s1: ('Global', 'etsi3', '*200', '*', '200', 'ok', '30', '100%', '100%', 'Outgoing') match s2: ('Global', 'etsi3', '* 4', '*', '4', 'ok', '30', '100%', '100%', 'Outgoing') From surekap at gmail.com Thu Jan 25 17:39:59 2007 From: surekap at gmail.com (Prateek) Date: 25 Jan 2007 14:39:59 -0800 Subject: Fast Imaging for Webserver In-Reply-To: References: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> Message-ID: <1169764799.867071.184160@h3g2000cwc.googlegroups.com> Thanks for all the responses so far.. The 'imaging' app that I mentioned is actually serving as a library for a bunch of other apps. A typical scenario is icon processing. The source image *could* be large (in this case it was 128x128 PNGA) Think of it as a Mac Finder/Win Explorer style view (grid + imagelist) where you're showing a bunch of data in icon form (16x16). For small amounts of data, everything is ok... but as soon as I get to 600-700 items, the page takes forever to load. The obvious solution is pagination but I'm doing some aggregate analysis on the data (like a frequency distribution) where if I were to paginate the data, i'd lose the client-side sorting ability (I'd have to sort server side which is a whole other can of worms). I'm gonna take Paul's advice and report as soon as I can. One other alternative is to save this information on the filesystem (as temp files) and route all future requests via the static file processing mechanism (which can be handled by Apache)... do you think that is a good idea? Prateek On Jan 25, 3:11 pm, "Fredrik Lundh" wrote: > "Prateek" wrote: > > Hi. I'm creating a web-application using CherryPy 2.2.1. My application > > needs to process images (JPG/PNG files) to > > > 1) create thumbnails (resize them) > > 2) overlay them on a custom background (a simple frame) > > 3) Overlay 'badges' (small 16x16 images) on top of the final thumbnail > > > I am using PIL 1.1.5 which I have custom compiled on my development > > machine (MacBook Pro 2.33Ghz Core Duo).. > > I am using im.thumbnail for step 1 and im.paste for steps 2 and 3. > > > The problem is that this thing is just way too slow. > > For ab -n 1000 -C session_id=2f55ae2dfefa896f67a80f73045aadfa4b4269f1 > >http://localhost:8080/imaging/icon/def/128/255(where def is the name > > of the image - default in this case - 128 is the size in pixels and 255 > > is the background color), I am getting: > > > Document Path: /imaging/icon/def/128/255 > > Document Length: 14417 bytes > > > Concurrency Level: 1 > > Time taken for tests: 18.664 seconds > > Complete requests: 1000 > > Failed requests: 0 > > Broken pipe errors: 0 > > Total transferred: 14680000 bytes > > HTML transferred: 14417000 bytes > > Requests per second: 53.58 [#/sec] (mean) > > Time per request: 18.66 [ms] (mean) > > Time per request: 18.66 [ms] (mean, across all concurrent > > requests) > > Transfer rate: 786.54 [Kbytes/sec] received > > > FYI: This request returns a PNG image (image/png) and not html > > > My understanding is that the problem is either with the CherryPy setup > > (which is likely because even in other cases, i don't get much more > > than 65 requests per second) or PIL itself (even though I'm caching the > > background images and source images)without knowing more about what kind of source images you're using, the > amount of data they represent etc, it's not entirely obvious to me that 50+ > images per second on a single server is that bad, really. unless the source > images are rather tiny, that's plenty of pixels per second to crunch. > > are you really receiving more than 4500000 source images per day per > server? > > From horpner at yahoo.com Wed Jan 17 09:24:31 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 17 Jan 2007 15:24:31 +0100 Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: On 2007-01-17, Will McGugan wrote: > Hi, > > I'd like a generator that takes a sequence and yields tuples containing > n items of the sqeuence, but ignoring the 'odd' items. For example > > take_group(range(9), 3) -> (0,1,2) (3,4,5) (6,7,8) > > This is what I came up with.. > > def take_group(gen, count): > i=iter(gen) > while True: > yield tuple([i.next() for _ in xrange(count)]) > > Is this the most efficient solution? This is starting to seem like an FAQ. ;) The Python library contains a recipe for this in the itertools recipes in the documentation (5.16.3). def grouper(n, iterable, padvalue=None): "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) It's more general and cryptic than what you asked for, though. -- Neil Cerutti We're not afraid of challenges. It's like we always say: If you want to go out in the rain, be prepared to get burned. --Brazillian soccer player From S.Mientki-nospam at mailbox.kun.nl Thu Jan 11 17:21:46 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 11 Jan 2007 23:21:46 +0100 Subject: globals accros modules In-Reply-To: <45a69cca$0$321$426a74cc@news.free.fr> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> <45a66cea$0$289$426a34cc@news.free.fr> <3137a$45a6851a$d443bb3a$24085@news.speedlinq.nl> <45a69cca$0$321$426a74cc@news.free.fr> Message-ID: <38388$45a6b867$d443bb3a$10089@news.speedlinq.nl> Bruno Desthuilliers wrote: > Stef Mientki a ?crit : >> Bruno Desthuilliers wrote: >> >>> stef a ?crit : > (snip) >>>> You can explain your collegaes, that >>>> - the startindex of arrays changes from 1 to 0 >>>> - slices are upto, instead of including the final border >>>> - indention is th? key >>>> And tell them about all beautiful things in Python, >>>> but tell them that they are going to loose all their globals ??? >>> >>> >>> It's a feature. Globals are definitively a BadThing(tm). >> >> >> yes, I know, but my audience will accept that only in the long term. > > Unless you clearly explain the benefits... Any code relying on the > existence of a global is: > 1/ dependent on the existence of this global > 2/ harder to understand And you think physicians will believe that ? And suppose they believe it, are the willing to stop their research to rethink and rewrite their code ;-) > > FWIW, I'm currently fixing a simple Delphi program that's using quite a > few globals, Then it was certainly not written by a Delphi-guy ;-) and since I'm not familiar with ObjectPascal (my experience > with Pascal boils down to a few cs101 stuff like implementing a linked > list, some 6 or 7 years ago), I'm losing a lost of time with these [bip] > globals... > >> But maybe this idea works: >> >> >> global var1 >> global var2 >> > > The 'global' statement only makes sens within a function, and it's only > a declaration, not a definition (-> it won't bind the following name by > itself - only tell the interpreter that this name is to be considered as > belonging to the module's namesepace ). > > The minimal working example requires that you assign a default value: > > # myglobs.py > meaning_of_life = 42 thanks for the tip. > > # another.py > import myglobs > print myglobs.meaning_of_life > >> >> >> import Ugly_MatLab_Globals >> >> def some_function(): >> import Ugly_MatLab_Globals > > You don't have to reimport it here... Then I miss something: TEN = 10 TWELVE = 12 def some_function(): global TEN TEN = 9 TWELVE = 11 print TEN, TWELVE some_function() #will print 9,11 print TEN, TWELVE #will print 9,12 Or am I mistaken ? cheers, Stef Mientki From gagsl-py at yahoo.com.ar Thu Jan 18 23:25:35 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 01:25:35 -0300 Subject: Iterator length In-Reply-To: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070119012013.0406b9d0@yahoo.com.ar> At Thursday 18/1/2007 20:26, bearophileHUGS at lycos.com wrote: >def leniter(iterator): > """leniter(iterator): return the length of an iterator, > consuming it.""" > if hasattr(iterator, "__len__"): > return len(iterator) > nelements = 0 > for _ in iterator: > nelements += 1 > return nelements > >Is it a good idea to extend the functionalities of the built-in len >function to cover such situation too? I don't think so, because it may consume the iterator, and that's a big side effect that one would not expect from builtin len() -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From erikgast at gmail.com Tue Jan 16 07:20:05 2007 From: erikgast at gmail.com (Erik) Date: 16 Jan 2007 04:20:05 -0800 Subject: wxPython, having images in a textCtrl Message-ID: <1168950003.235431.231010@m58g2000cwm.googlegroups.com> Is it possible with wxPython to place images in a textctrl (or a styledtextctrl)? If you don't get what I mean, just think about emoticons in the MSN messenger chat window. So is it possible to use images in a textCtrl? Thanks Erik From bearophileHUGS at lycos.com Wed Jan 3 20:18:11 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 Jan 2007 17:18:11 -0800 Subject: Sorting on multiple values, some ascending, some descending In-Reply-To: <1167868015.112325.219410@i80g2000cwc.googlegroups.com> References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> <1167852652.416990.158610@k21g2000cwa.googlegroups.com> <1167868015.112325.219410@i80g2000cwc.googlegroups.com> Message-ID: <1167873490.470862.156240@6g2000cwy.googlegroups.com> dwelden wrote: > > L.sort(key=lambda r: r.secondary, reverse=True) > > L.sort(key=lambda r: r.primary) > Excellent! That looks just like what I needed. Note that there is the (probably little used) operator.attrgetter() too, with that you can avoid the possibly slow lambda: L.sort(key=attrgetter("primary") operator.itemgetter(n) is when you have items that can be be accessed by index. Bye, bearophile From bill.mill at gmail.com Tue Jan 16 14:36:49 2007 From: bill.mill at gmail.com (Bill Mill) Date: 16 Jan 2007 11:36:49 -0800 Subject: Regex Question In-Reply-To: References: Message-ID: <1168976209.504793.51890@38g2000cwa.googlegroups.com> James Stroud wrote: > Bill Mill wrote: > > Hello all, > > > > I've got a test script: > > > > ==== start python code ===== > > > > tests2 = ["item1: alpha; item2: beta. item3 - gamma--", > > "item1: alpha; item3 - gamma--"] > > > > def test_re(regex): > > r = re.compile(regex, re.MULTILINE) > > for test in tests2: > > res = r.search(test) > > if res: > > print res.groups() > > else: > > print "Failed" > > > > ==== end python code ==== > > > > And a simple question: > > > > Why does the first regex that follows successfully grab "beta", while > > the second one doesn't? > > > > In [131]: test_re(r"(?:item2: (.*?)\.)") > > ('beta',) > > Failed > > > > In [132]: test_re(r"(?:item2: (.*?)\.)?") > > (None,) > > (None,) > > > > Shouldn't the '?' greedily grab the group match? > > > > Thanks > > Bill Mill > > bill.mill at gmail.com > > The question-mark matches at zero or one. The first match will be a > group with nothing in it, which satisfies the zero condition. Perhaps > you mean "+"? > > e.g. > > py> import re > py> rgx = re.compile('1?') > py> rgx.search('a1').groups() > (None,) > py> rgx = re.compile('(1)+') > py> rgx.search('a1').groups() But shouldn't the ? be greedy, and thus prefer the one match to the zero? This is my sticking point - I've seen that plus works, and this just confuses me more. -Bill Mill bill.mill at gmail.com From gagsl-py at yahoo.com.ar Tue Jan 30 12:20:41 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 14:20:41 -0300 Subject: How can I know both the Key c and Ctrl on the keyboard are pressed? References: <1170147029.261981.322740@a75g2000cwd.googlegroups.com> Message-ID: En Tue, 30 Jan 2007 05:50:29 -0300, escribi?: > How can I know the Key c and Ctrl on the keyboard are pressed? Or how > to let the program press the > > key Ctrl+c automatically? I just want to use python to develop a > script program. > gear If you are on Windows and want to trap the Ctrl-C combination, just catch the KeyboardInterrupt exception: --- cut --- from time import sleep while 1: try: sleep(1) except KeyboardInterrupt: print "Ctrl-C pressed" --- cut --- -- Gabriel Genellina From http Mon Jan 29 10:08:48 2007 From: http (Paul Rubin) Date: 29 Jan 2007 07:08:48 -0800 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <7x3b5uwfa2.fsf@ruckus.brouhaha.com> <1170082883.393745.244840@a34g2000cwb.googlegroups.com> Message-ID: <7x64apzx8f.fsf@ruckus.brouhaha.com> "Szabolcs Nagy" writes: > file('/dev/urandom').read(6).encode('base64') > (oneliner and without import sa op requested) Nice, though Un*x dependent (os.urandom is supposed to be portable). From time.swift at gmail.com Sat Jan 6 19:07:05 2007 From: time.swift at gmail.com (time.swift at gmail.com) Date: 6 Jan 2007 16:07:05 -0800 Subject: Why less emphasis on private data? Message-ID: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Coming from a C++ / C# background, the lack of emphasis on private data seems weird to me. I've often found wrapping private data useful to prevent bugs and enforce error checking.. It appears to me (perhaps wrongly) that Python prefers to leave class data public. What is the logic behind that choice? Thanks any insight. From __peter__ at web.de Fri Jan 5 09:23:38 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Jan 2007 15:23:38 +0100 Subject: bug in copy.deepcopy or in getattr or in my understanding? References: <1167942359.246311.80700@s34g2000cwa.googlegroups.com> <1168005716.195293.121490@38g2000cwa.googlegroups.com> Message-ID: Emin wrote: > Thank you for your reply. As you guessed, I want to be able to select > the method at runtime as in your final example, but when I tried your > suggestion I got the same error (see below). I think the problem is > that getattr is donig something different than in my example where I > explicitly get it from the dict (see the very end of the transcript > below): This has nothing to do with getattr(). You currently can deep-copy functions, but neither bound nor unbound methods: >>> import copy >>> def check(obj): ... try: ... copy.deepcopy(obj) ... except: ... return "FAILED" ... return "OK" ... >>> def function(*args): pass ... >>> class A: ... method = function ... >>> check(function), check(A.method), check(A().method) ('OK', 'FAILED', 'FAILED') Whether this a bug or a sensible limitation I don't know. Peter From matt at tplus1.com Mon Jan 29 12:17:19 2007 From: matt at tplus1.com (Matthew Wilson) Date: Mon, 29 Jan 2007 17:17:19 GMT Subject: Can I undecorate a function? Message-ID: The decorator as_string returns the decorated function's value as string. In some instances I want to access just the function f, though, and catch the values before they've been decorated. Is this possible? def as_string(f): def anon(*args, **kwargs): y = f(*args, **kwargs) return str(y) return anon @as_string def f(x): return x * x Matt -- A better way of running series of SAS programs: http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles From TimDGCB at gmail.com Tue Jan 30 16:37:05 2007 From: TimDGCB at gmail.com (TimDGCB at gmail.com) Date: 30 Jan 2007 13:37:05 -0800 Subject: DCOP memory leak? Message-ID: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> Hello, I'm writing a python script for Amarok, I communicate with Amarok using DCOP. Now, I have to call DCOP very often and I noticed that every time I make a DCOP call my program keeps growing in memory size. To make sure it was DCOP i wrote the small program below: from dcopext import DCOPClient, DCOPApp while 0==0: dcop=DCOPClient() dcop.attach() AmarokDcopRes = DCOPApp ("amarok", dcop) ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() print Ms If you run this script and monitor it's memory use you'll see that it keeps growing. Does anyone know how I can solve this problem? Kind regards, Tim From webraviteja at gmail.com Fri Jan 5 08:01:10 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 5 Jan 2007 05:01:10 -0800 Subject: program deployment In-Reply-To: <1167998448.978001.3720@38g2000cwa.googlegroups.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> Message-ID: <1168002070.704739.76470@q40g2000cwq.googlegroups.com> king kikapu wrote: > hi to all folks here, > > i am learning Python, just finished a book and i am starting to write > programs. > I just want to ask, is the "correct" way to deploy my programs to other > computers, the .pyc files ?? > > I now that with the "-m compileall ." switch can compile a .py file > into bytecodes. So i suppose that if Python has to run a .pyc file, it > will load and execute it faster. And if i have some "sensitive" data in > my source, like passwords (and the source of cource!) they will be more > secure in a compiled file. > > Is that correct ? > > Thanks a lot for any help! Python code is normally deployed as straight source code. It gets compiled automatically on its first run and will subsequently load this quickly. Passwords do not belong in the source code and they are not secure simply by distributing bytecode instead. This applies to any language, native or byte code compiled. Distributing bytecode may deter non-technical users but that's just about it. From michael at mustun.ch Wed Jan 3 10:30:45 2007 From: michael at mustun.ch (mm) Date: Wed, 03 Jan 2007 16:30:45 +0100 Subject: Unsubscribing from the list In-Reply-To: References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> Message-ID: Fredrik Lundh wrote: > if you're unable to follow written instructions, how on earth did you manage > to subscribe to this list ? > > > > > *lol* Just click.... ;-) From tomas at fancy.org Tue Jan 2 20:16:34 2007 From: tomas at fancy.org (Tom Plunket) Date: Tue, 02 Jan 2007 17:16:34 -0800 Subject: DOS, UNIX and tabs References: Message-ID: Peter Decker wrote: > > Maybe I'm also weird, but I use a variable-pitch font when programming > > in Python. So a "tab equals some number of spaces" really isn't useful > > to me. My setup is, "tab equals this much space". > > A year ago I would have thought you were weird, but after reading a > post by Ed Leafe, one of the creators of Dabo about using proportional > fonts for readability, I thought I'd try it out, thinking that it was > pretty wacky. Turns out that after a very brief adjustment period, I > liked it! Yep, I had a similar experience although a bit more forced. The editor that I was using was configured out-of-the-box with variable-pitch, and I didn't want to bother figuring out how to change it for the quickie stuff I was writing, then eventually I found that it no longer bothered me... -tom! -- From TimDGCB at gmail.com Wed Jan 31 12:46:25 2007 From: TimDGCB at gmail.com (TimDGCB at gmail.com) Date: 31 Jan 2007 09:46:25 -0800 Subject: DCOP memory leak? In-Reply-To: References: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> Message-ID: <1170265582.892012.69290@v45g2000cwv.googlegroups.com> On 31 jan, 01:03, Larry Bates wrote: > TimD... at gmail.com wrote: > > Hello, > > > I'm writing a python script for Amarok, I communicate with Amarok > > using DCOP. > > Now, I have to call DCOP very often and I noticed that every time I > > make a DCOP call my program keeps growing in memory size. > > > To make sure it was DCOP i wrote the small program below: > > > from dcopext import DCOPClient, DCOPApp > > > while 0==0: > > dcop=DCOPClient() > > dcop.attach() > > AmarokDcopRes = DCOPApp ("amarok", dcop) > > ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() > > print Ms > > > If you run this script and monitor it's memory use you'll see that it > > keeps growing. > > > Does anyone know how I can solve this problem? > > > Kind regards, > > > Tim > > I think you will find the objects are getting created so fast that > garbage collection doesn't have time to clean them up as fast > as you are creating new ones. Since del dcop is not guaranteed > to be "immediate" that won't help. > > Q: Can't you create dcop instance outside the loop and reuse it > for every time through the loop? > > Q: Can you sleep or something after each loop or do you really > want to peg the CPU checking forever? > > Q: How do you ever get out of this infinite loop? > Note: while 0=0 is better written as while 1: and you need a > break somewhere to get out of the loop. > > -Larry Hi, Thanks for the quick response. The code I posted is not my actual program and was only to demonstrate my problem. The complete program I'm writing uses QT and so the loop is replaced by a Timer event. I tried out the suggestion. I had already tried the del dcop instruction, so I knew that wasn't it. I also placed the DCOP variable outside my loop but that didn't help either. What I did notice that my program only grew in memory use when the 'ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() ' code was executed (or any other function using the AmarokDcopRes variable like 'ok, volume = AmarokDcopRes.player.getVolume()' ) Then I also tried to make my take a pause of a second in the loop but this also didn't help, the program was still growing in memory use (a lot slower though but I don't call that a solution) So if you have any more ideas let me know. I'll keep on trying Kind regards, Tim From oliphant.travis at ieee.org Wed Jan 24 03:02:17 2007 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 24 Jan 2007 01:02:17 -0700 Subject: numpy or _numpy or Numeric? In-Reply-To: References: Message-ID: auditory wrote: > I am a newbie here > > I am trying to read "space separated floating point data" from file > > I read about csv module by searching this group, > but I couldn't read space separated values with csv. > (which may be matter of course..) > > I also read about numpy.fromfile(file, sep=' ') which i can use. > but on my machine(ubuntu linux) numpy is unknown module, > which I didn't install by myself. You will need to install NumPy. > > While trying to install numpy accroding to its homepage. > (http://numpy.scipy.org/numpydoc/numdoc.htm). > i am quite confused. You are reading old documentation for Numeric and so any installation description is how to install the Numeric module (not its newer replacement which is called NumPy). So: 1) Yes, you need NumPy 2) This *is different* from Numeric 3) You get it by either installing a pre-built package for your system or by a) downloading the source tar-file from http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 (get the numpy-.tar.gz file b) tar zxvf numpy-.tar.gz c) cd numpy- d) sudo python setup.py install e) If you want to link against high-performance libraries on your system, then either put them in standard locations or edit the site.cfg file appropriately (Optional). > > 4. Or what is general way to read 'space separated values' from file? You can easily read space-separated values from a file by reading in a line at a time and using the split method of strings: fid = open('filename') linedata = fid.readlines() new = [[float(x) for x in line.split()] for line in linedata] new will be a nested sequence of floats. You can convert it to an array (if you want to do math on it) using anew = numpy.array(new) -Travis From horpner at yahoo.com Wed Jan 10 09:53:49 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Jan 2007 15:53:49 +0100 Subject: Working with named groups in re module Message-ID: A found some clues on lexing using the re module in Python in an article by Martin L?wis. http://www.python.org/community/sigs/retired/parser-sig/towards-standard/ He writes: [...] A scanner based on regular expressions is usually implemented as an alternative of all token definitions. For XPath, a fragment of this expressions looks like this: (?P\\d+(\\.\\d*)?|\\.\\d+)| (?P\\$""" + QName + """)| (?P"""+NCName+""")| (?P"""+QName+""")| (?P\\()| Here, each alternative in the regular expression defines a named group. Scanning proceeds in the following steps: 1. Given the complete input, match the regular expression with the beginning of the input. 2. Find out which alternative matched. [...] Item 2 is where I get stuck. There doesn't seem to be an obvious way to do it, which I understand is a bad thing in Python. Whatever source code went with the article originally is not linked from the above page, so I don't know what Martin did. Here's what I came up with (with a trivial example regex): import re r = re.compile('(?Px+)|(?Pa+)') m = r.match('aaxaxx') if m: for k in r.groupindex: if m.group(k): # Find the token type. token = (k, m.group()) I wish I could do something obvious instead, like m.name(). -- Neil Cerutti After finding no qualified candidates for the position of principal, the school board is pleased to announce the appointment of David Steele to the post. --Philip Streifer From rridge at csclub.uwaterloo.ca Thu Jan 18 20:57:01 2007 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 18 Jan 2007 17:57:01 -0800 Subject: Determining when a file is an Open Office Document References: Message-ID: <1169171821.468301.78770@51g2000cwl.googlegroups.com> tubby wrote: > Silly question, but here goes... what's a good way to determine when a > file is an Open Office document? I could look at the file extension, but > it seems there would be a better way. VI shows this info in the files: > > mimetypeapplication/vnd.oasis.opendocument.textPK It's a ZIP archive. The info you've found are the file name "mimetype", the uncompressed contents of that file "application/vnd.oasis.opendocument.text", and part of the ZIP magic number "PK". You should be able to use the "zipfile" module to check to see if the file a ZIP file, if it has a member named "mimetype" and if the contents of the file match one of the OpenOffice MIME types. Ross Ridge From martin at v.loewis.de Wed Jan 3 14:55:39 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 20:55:39 +0100 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167852636.403469.69220@h40g2000cwb.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <1167543262.361311.123700@v33g2000cwv.googlegroups.com> <459BCF07.6080302@v.loewis.de> <1167852636.403469.69220@h40g2000cwb.googlegroups.com> Message-ID: <459C0A3B.1030400@v.loewis.de> vbgunz schrieb: >>> I don't understand what all the fuss is about. Add a single page to the >>> installer and on it, have 3 radio buttons. The choices could be "add to >>> path (recommended)", "add to path with version", "do not add to path >>> (not recommended)". >> Please submit a patch to sf.net/projects/python that does so. > > If I could I would. My only point jumping in here is this; adding > python to the path has got to be more beneficially productive for > everyone than not adding it at all. I don't even use Windows enough to > complain about it and I thought I'll voice my agreement on it. Ok. So I can answer your (implied) question: much of the fuss is about lack of contributions. Regards, Martin From rythin at gmail.com Sat Jan 6 11:47:18 2007 From: rythin at gmail.com (Rythin) Date: 6 Jan 2007 08:47:18 -0800 Subject: C++/Python programmers for a MUD's gamedriver wanted. Message-ID: <1168102038.680286.73330@42g2000cwt.googlegroups.com> Hi everyone. We are looking for a volunteer co-programmers for a MUD's gamedriver project. As of now, a gamedriver is divided into two separate but tightly interconnected systems - C++ driver and Python lib. C++ Driver is supposed to be managing memory, proccesses and communication between them (transparent as far as net is concerned). Python lib is to define the user's interfaces. Both of them are designed to work in an object-oriented enviroment, with lib's classes being driver's child-classes. Competent level of knowledge on C++ and Python (especially embedding Python's interpreter in apps) is required. Alternatively, we are seeking people skilled in a use of Unix sockets and C++ system programming. If you are interested, email me at rythin at gmail.com (subject: Gamedriver project) with a brief summary of your skills, C++/Python/mud experience and things you are looking to find in this job. You are welcome to ask any additional questions at rythin at gmail.com (subject: Gamedriver project). Take care, Michael From deets at nospam.web.de Sat Jan 20 11:14:34 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 20 Jan 2007 17:14:34 +0100 Subject: confused on python rpc with apache, is it possible? In-Reply-To: References: <51ce8uF1k0tl5U1@mid.uni-berlin.de> <1169276359.477277.17930@q2g2000cwa.googlegroups.com> Message-ID: <51etfpF1kappuU1@mid.uni-berlin.de> krishnakant Mane schrieb: >> Use mod_python with some xmlrpc handler. There is more than one around. >> Google for them. That way you can keep Apache for both Python and PHP. >> > I am confused. > I have some documents on xml-rpc but none of them mentioned apache. There is nothing an apache will do for you - except from possibly proxing python. Go read up upon xmlrpc and python, possibly doing it with twisted, but there are other options. Don't bother with the apache. Diez From jan.m.danielsson at gmail.com Tue Jan 23 00:54:55 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 23 Jan 2007 06:54:55 +0100 Subject: Removing outdated files In-Reply-To: References: <45b59949@griseus.its.uu.se> Message-ID: <45b5a21d$1@griseus.its.uu.se> Gabriel Genellina wrote: >> I've been looking at the datetime.date class, but I can't see any >> easy way to parse the week number from it. I could calculate this >> information by brute force -- but I get a feeling that there are >> functions in Python to extract week numbers from a date. > > .isocalendar() .thanks() -- Kind regards, Jan Danielsson From kkkisok at operamail.com Wed Jan 10 18:00:57 2007 From: kkkisok at operamail.com (kkkisok at operamail.com) Date: Wed, 10 Jan 2007 23:00:57 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> <0001HW.C1CA63B1059BC980F0203648@news.verizon.net> Message-ID: On 10-Jan-2007, krw wrote: > ...and "HexaPussy" just wouldn't be right. SexagesimalPussy (base 60) has kind of a nice ring to it. From aboudouvas at panafonet.gr Fri Jan 19 04:07:57 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 19 Jan 2007 01:07:57 -0800 Subject: PyODBC Stored proc calling In-Reply-To: <1169115954.917268.74210@51g2000cwl.googlegroups.com> References: <1169115954.917268.74210@51g2000cwl.googlegroups.com> Message-ID: <1169197677.745994.262540@s34g2000cwa.googlegroups.com> No one is using pyodbc ?? :) From ask at me Thu Jan 11 08:52:42 2007 From: ask at me (alf) Date: Thu, 11 Jan 2007 07:52:42 -0600 Subject: globals accros modules In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > Change a=1 to amodule.a=1 I have multiple command line programs creating 'a' and amodule using it. Plus some import sequence dependency. So it would not work. Currently the solution in amodule is: import __main__ print __main__.a > If you find yourself doing tricks with the module globals, think about > redesigning your application. For what I do it is good enough. If I hit the same problem, will refactor it. A. From jan.dries at dcube-resource.be Thu Jan 4 10:51:27 2007 From: jan.dries at dcube-resource.be (Jan Dries) Date: Thu, 04 Jan 2007 16:51:27 +0100 Subject: Best way to implement a timed queue? In-Reply-To: <459D0FF5.4020703@gmx.net> References: <459D0FF5.4020703@gmx.net> Message-ID: <459D227F.1020502@dcube-resource.be> Thomas Ploch wrote: > I am having troubles with implementing a timed queue. I am using the > 'Queue' module to manage several queues. But I want a timed access, i.e. > only 2 fetches per second max. I am horribly stuck on even how I > actually could write it. Has somebody done that before? And when yes, > how is the best way to implement it? I don't know about "the best way" to implement it, but I once solved a similar problem with the following scenario. The idea is that you create a "token" queue, a Queue object of the desired depth, 2 in your case. You then have a separate thread that, in a loop, puts two "tokens" on the queue and then puts itself to sleep for one second. And the worker thread or threads that must be doing whatever twice per second try to get an object from the queue prior to doing their thing. The following piece of code does the trick. Note that it allows worker threads to do something two times every second, and not once every half second, though it could easily be modified to accomodate that too. Also note that the code below keeps running forever as worker threads never stop working. You will probably want to change that. Regards, Jan import time from Queue import Queue,Full,Empty from thread import start_new_thread class Manager(object): def __init__(self, number_of_workers=10, max_per_sec=5): self.MAX_PER_SEC = max_per_sec self.NUMBER_OF_WORKERS = number_of_workers self.timelimit = Queue(self.MAX_PER_SEC) self.donelock = Queue(0) self.finished = False def do_work(self,number): print "Starting worker thread %s" % number while True: if self.get_time(): # do whatever can only be done x times per second print "Worker %s doing work" % number time.sleep(3) # simulate worker doing some work self.signal_done() def signal_done(self): self.donelock.put(None,True) def wait_done(self): for i in range(0,self.MAX_PER_SEC): self.donelock.get(True) self.finished = True def feed_time(self): while not self.is_finished(): for i in range(0,self.MAX_PER_SEC): self.insert_time() time.sleep(1) def insert_time(self): try: self.timelimit.put_nowait(None) except Full: pass def get_time(self): try: self.timelimit.get(True,10) return True except Empty: return False def is_finished(self): return self.finished def start_worker_threads(self): for i in range(0,self.NUMBER_OF_WORKERS): start_new_thread(self.do_work,(i + 1,)) def start_time_thread(self): start_new_thread(self.feed_time,()) def run(self): self.start_time_thread() self.start_worker_threads() self.wait_done() def main(): Manager(10,2).run() if __name__ == "__main__": main() From rweth at cisco.com Sat Jan 6 14:37:55 2007 From: rweth at cisco.com (rweth) Date: Sat, 06 Jan 2007 11:37:55 -0800 Subject: nntplib downloads content with extra linebreaks In-Reply-To: References: <1168110213.436860@sj-nntpcache-1.cisco.com> Message-ID: <1168112276.194982@sj-nntpcache-1.cisco.com> Klaus Alexander Seistrup wrote: > Rweth wrote: > >> I am using nntplib to download archived xml messages from our >> internal newsgroup. This is working fine except the download >> of files to the connected server, has extra embedded lines in >> them (all over the place), from the >> s.body(id,afile) # body method > > The 'linebreaks' are probably '\r\n' pairs, so you could do a > > buf.replace('\r\n', '\n') > > to convert all such pairs to single LFs (buf being the buffer or > string that holds the text with 'linebreaks'). > > Cheers, > Well Klaus I tried it .. sadly no joy. Lets see if I did it the way you would have: buf = s.body(id)[3] # indexes 0 .. 2 contain disjoint portions but the big part is in # [3] so .. i only did it for 3 for simplification bufHeal = [] for aline in buf: bufHeal.append(aline.replace('\r\n', '\n')) fn = "c:/boing.xml" fh = open(fn.'w') for aline in bufHeal: fh.write(aline) fh.close() This is giving me a file with no line breaks .. in fact when I look at the elements in buf .. they don't have \r\n or \n at the end of them .. I think the s.body(id,afile) .. does a variety of magic to the contents of the buffer .. along with applying "some magic template directive like an xsd file" again just guessing here. From salvatore.difazio at gmail.com Mon Jan 15 16:49:25 2007 From: salvatore.difazio at gmail.com (Salvatore Di Fazio) Date: 15 Jan 2007 13:49:25 -0800 Subject: Watch log In-Reply-To: <512astF1i9fgbU1@mid.individual.net> References: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> <512astF1i9fgbU1@mid.individual.net> Message-ID: <1168897765.370442.201660@51g2000cwl.googlegroups.com> Bjoern Schliessmann ha scritto: > Why not read the file continuously and only do something if a new > line is complete (i. e. a newline char is detected)? How can I read the file continuously? From bignose+hates-spam at benfinney.id.au Wed Jan 3 20:28:55 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Jan 2007 12:28:55 +1100 Subject: static object References: <459c306c$0$314$426a74cc@news.free.fr> Message-ID: <87d55vbmw8.fsf@benfinney.id.au> meelab writes: > In other words, that is a class which would result in only 1 instance > always the same no matter how many times I will "instantiate" it. The "Singleton" pattern does what you say here. Implementing a proper Singleton in Python is complicated and hard to understand. However, there's nothing in your description that requires only one *instance* of the class; you only require that any instance of that class should share the same *state* with all other instances. If that's true, you'll be better served by the much simpler Borg class (referred to elsewhere in this thread, but for reference ). > My purpose is to permit this class to initialize a massive amount of > data that I need to access from different points of my program > without duplicating this data in memory and without loosing time in > reloading it each time I need it. This can be further simplified by instantiating all that stuff in a *module*, and importing the module wherever it is needed. No need for custom classes at all, then. -- \ "Even if the voices in my head are not real, they have pretty | `\ good ideas." -- Anonymous | _o__) | Ben Finney From mirandacascade at yahoo.com Sun Jan 7 10:34:20 2007 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 7 Jan 2007 07:34:20 -0800 Subject: AES256 in PyCrypto In-Reply-To: References: <1168134542.337448.261510@s34g2000cwa.googlegroups.com> Message-ID: <1168184060.548851.11540@i15g2000cwa.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > `a` must be of length 32 for AES256. And the length of `plainText` must > be a multiple of 16 because it's a block cypher algorithm. Thank you. I have some follow up questions and 1 tangential question. Follow up question: Would it be correct to infer that: a) the AES.pyd extension module (plus whatever additional files within the PyCrypto package that it uses) has the capability to perform AES256 encryption? b) the AES256 encryption happens based on the characteristics of the input to the new() method...if the first argument has a length of 32, the result will be AES256-style encryption? c) will AES256-style encryption also happen if the first argument to the new() method has a length that is a multiple of 32, e.g. 64? Tangential question: Is there functionality available (either in the PyCrypto package or some other package) that generates an initialization vector that can be used as input to the new() method? What prompts this question is that the original posting referenced a snippet of C# code; some other related snippets I saw seemed to suggest that: a) a RijndaelManaged() class gets instantiated b) that class has a GenerateIV() method which appears to populate someting in a IV property c) the application that was employing the AES256 encryption made use of the left-most 16 characters of the IV property So, I was curious whether something analgous exists in the Python world. Thank you. From gagsl-py at yahoo.com.ar Thu Jan 25 01:47:15 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 03:47:15 -0300 Subject: How can i do this in Python? In-Reply-To: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> References: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070125033729.04414ae8@yahoo.com.ar> At Thursday 25/1/2007 01:25, NoName wrote: >perl -ane "print join(qq(\t), at F[0,1,20,21,2,10,12,14,11,4,5,6]).qq(\n)" Must be done on a single line? I'm not sure if I've got right the behavior - it's been some time since I quit writing Perl code. The script iterates over all lines contained on all files specified on the command line; for each line, splits it on whitespace; then it prints a selected set of fields (columns 0, 1, 20, 21...) using a tab character as field separator. === cut === import operator,fileinput mapper = map(operator.itemgetter, [0,1,20,21,2,10,12,14,11,4,5,6]) for line in fileinput.input(): fields = line.split() print '\t'.join(m(fields) for m in mapper) === cut === -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ptmcg at austin.rr._bogus_.com Mon Jan 8 03:44:20 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 8 Jan 2007 02:44:20 -0600 Subject: regex question References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> <1168243020.304940.212700@42g2000cwt.googlegroups.com> Message-ID: <45a20464$0$9644$4c368faf@roadrunner.com> "proctor" <12cc104 at gmail.com> wrote in message news:1168243020.304940.212700 at 42g2000cwt.googlegroups.com... > > > it does work now...however, one more question: when i type: > > rx_a = re.compile(r'a|b|c') > it works correctly! > Do you see the difference between: rx_a = re.compile(r'a|b|c') and rx_a = re.compile("r'a|b|c'") There is no difference in the variable datatype between "string" and "raw string". Raw strings are just a notational helper when creating string literals that have lots of backslashes in them (as happens a lot with regexps). r'a|b|c' is the same as 'a|b|c' r'\d' is the same as '\\d' There is no reason to "add raw strings" to your makeRE method, since you don't have a single backslash anywhere. And even if there were a backslash in the 'w' argument, it is just a string - no need to treat it differently. -- Paul From Thomas.Ploch at gmx.net Fri Jan 5 10:35:00 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 16:35:00 +0100 Subject: program deployment In-Reply-To: <12psqtppgi5cme6@corp.supernews.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> Message-ID: <459E7024.3040204@gmx.net> Grant Edwards schrieb: > On 2007-01-05, king kikapu wrote: > >>> Python code is normally deployed as straight source code. >> But isn't this a problem of its own? I mean, many people do not feel >> good if the know that their source code is lying around on other >> machines... > > Are they embarassed by their code? > hehehe, but what I am thinking: Is it somehow possible to _really_ hide the source from being viewed by other persons when using python? Not that I want to do that ( I am an Open Source friend ), but that might get others that rely on that (commercial) to use python for more projects as it is done now. Thomas From huayang.xia at gmail.com Thu Jan 4 12:02:28 2007 From: huayang.xia at gmail.com (Huayang Xia) Date: 4 Jan 2007 09:02:28 -0800 Subject: what is this? In-Reply-To: References: Message-ID: <1167930148.312902.71540@6g2000cwy.googlegroups.com> Sequence slicing [starting-at-index : but-less-than-index [ : step]]. Start defaults to 0, end to len(sequence), step to 1. So l[i::rows] means: slicing start from i, ending with len(l) and step with rows. So function colsplit(l, cols) returns a list of sequence with conversion of: Assume cols = 4: From: ABCD ABCD ABCD AB To: AAAABBBBCCCDDD On Jan 4, 11:42 am, "Eric Price" wrote: > Hello; > I'm studying some code examples from the python cookbook site. I came across > this: > > def colsplit(l, cols): > rows = len(l) / cols > if len(l) % cols: > rows += 1 > m = [] > for i in range(rows): > m.append(l[i::rows]) > return m > > What I'd like to know is what is the double colon? What does it do? > m.append(l[i::rows]) > > Thanks, > Eric > > _________________________________________________________________ > Type your favorite song. Get a customized station. Try MSN Radio powered > by Pandora.http://radio.msn.com/?icid=T002MSN03A07001 From gagsl-py at yahoo.com.ar Sat Jan 13 09:15:12 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Jan 2007 11:15:12 -0300 Subject: module file References: <45a7ba78$0$316$426a74cc@news.free.fr> <87hcuv527c.fsf@smsnet.pl> Message-ID: "Rob Wolfe" escribi? en el mensaje news:87hcuv527c.fsf at smsnet.pl... > Imbaud Pierre writes: > >> I am willing to retrieve the file an imported module came from; >> module.__file__, or inspect.getfile(module) only gives me the >> relative file name. How do I determine the path? > >>>> import os >>>> os.path.abspath(module.__file__) Note that this works only if the current dir has not changed. So it's a good idea to store the absolute path as early as possible (before the program have a chance to change the current dir) -- Gabriel Genellina From Hieu.D.Hoang at gmail.com Thu Jan 25 06:31:43 2007 From: Hieu.D.Hoang at gmail.com (Hieu.D.Hoang at gmail.com) Date: 25 Jan 2007 03:31:43 -0800 Subject: Do I need Python to run Blender correctly? In-Reply-To: <1169722064.189055.61620@v45g2000cwv.googlegroups.com> References: <1169722064.189055.61620@v45g2000cwv.googlegroups.com> Message-ID: <1169724703.257330.188030@v45g2000cwv.googlegroups.com> On Jan 25, 5:47 pm, g... at dsdata.it wrote: > On Jan 25, 9:25 am, "AKA gray asphalt" > wrote: > > > I downloaded Blender but there was no link for python. Am I on the right > > track? > Don't worry, Blender includes its own bundled Python interpreter, which > is usually one version behind; just leave it alone. > > Lorenzo Gatti Also note that only standard modules bundled in the Blender package are available. And extension modules e.g. numpy can't be installed into it. You must have the same version of python as the one in Blender. Starting blender from a terminal told me that. Happy designing! Hieu From __peter__ at web.de Tue Jan 23 13:42:01 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Jan 2007 19:42:01 +0100 Subject: Overloading assignment operator References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Achim Domma wrote: > I want to use Python to script some formulas in my application. The user > should be able to write something like > > A = B * C > > where A,B,C are instances of some wrapper classes. Overloading * is no > problem but I cannot overload the assignment of A. I understand that > this is due to the nature of Python, but is there a trick to work around > this? >>> class D(dict): ... def __setitem__(self, key, value): ... print key, "<--", value ... dict.__setitem__(self, key, value) ... >>> namespace = D(B=42, C=24) >>> exec "A = B * C" in namespace A <-- 1008 Peter From kernel1983 at gmail.com Tue Jan 16 21:44:20 2007 From: kernel1983 at gmail.com (kernel1983) Date: 16 Jan 2007 18:44:20 -0800 Subject: How can I create a linked list in Python? In-Reply-To: References: Message-ID: <1169001860.627239.116000@v45g2000cwv.googlegroups.com> Every language has its own way to do the business! Python has a more abstract data type as the common tools. Just do things in pythonic way! On 1?17?, ??9?55?, Gabriel Genellina wrote: > At Tuesday 16/1/2007 17:07, Dongsheng Ruan wrote: > > >Thanks for your kindly help. > >I am new CS student taking datat structure and algorithms with AHO's book > >with the same title. > > >The book is done in Pascal, which might be an outdated language. > > >However, my instructor probably wants us to understand the list ADT better > >by not using the built in list in Python.Just use the same structure as the book. Instead of nil, use None; > instead of new(P) where P:^Foo, use P=Foo(); records become classes > without methods... > > Anyway, implementing linked lists, dictionaries, and other basic > structures in a language like Pascal, or C -which doesn't have them > natively- may be a good learning exercise. But doing that in Python > is not a good idea. Of course, using Python in a second or third > algorithms course *is* a good idea, because you can forget about > these implementation details and concentrate on the algorithms. > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya!http://www.yahoo.com.ar/respuestas From jackdied at jackdied.com Wed Jan 3 16:33:33 2007 From: jackdied at jackdied.com (Jack Diederich) Date: Wed, 3 Jan 2007 16:33:33 -0500 Subject: Py_BuildValue or PyList_SetItem() In-Reply-To: <1167858998.103361.222490@i12g2000cwa.googlegroups.com> References: <1167858998.103361.222490@i12g2000cwa.googlegroups.com> Message-ID: <20070103213333.GD14633@performancedrivers.com> On Wed, Jan 03, 2007 at 01:16:38PM -0800, Sheldon wrote: > I have a function that creates python objects out of C arrays and > returns them to Python. Below is a working example that I later want to > expand to return 12 arrays back to Python. The problem is that when I > print out the values in Python I get undesired reults. See below. Does > anyone know what is going on here? > The array values are good before the conversion. > > ************************************** > int createPythonObject(void) { > int i,j,k; > PyObject *Rva=PyList_New(12); > > for (i = 0; i < 12; i++) { > PyObject *op = PyFloat_FromDouble((double)va[i]); > if (PyList_SetItem(Rva,i,op) !=0) { > fprintf(stderr,"Error in creating python va object\n"); > exit(EXIT_FAILURE); > } > Py_DECREF(op); > op = 0; > return Py_BuildValue("N",Rva); > } > > Results in Python: > > , , 0x80d885c>, , , at 0x80d885c>, , , > , , 0x80d885c>, > PyList_SetItem steals a reference to "op" so DECREF'ing it reduces the refcount to zero. http://docs.python.org/api/listObjects.html -Jack From martin.laloux at gmail.com Thu Jan 25 09:55:25 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 25 Jan 2007 06:55:25 -0800 Subject: how to unistall a Python package? In-Reply-To: References: Message-ID: <1169736925.096771.233740@k78g2000cwa.googlegroups.com> you delete it from lib From Barry.Carroll at psc.com Fri Jan 19 15:20:26 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 19 Jan 2007 12:20:26 -0800 Subject: OT Annoying Habits (Was: when format strings attack) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A96@eugsrv400.psc.pscnet.com> Greetings: Personally, I don't think top-posting is the most annoying newsgroup habit. I think it's making a big fuss about minor inconveniences. One of the nicest things about being human is the amazing flexibility of our brains. For example, if a block of text isn't arranged in the order we're used to, we can easily rearrange it mentally and read it anyway. Oriental and Arabic peoples, for example, do this each time they read something written in English. It's EASY, once you get used to it! It took me about 3 seconds to realize that Mr. D'Aprano' Q&A session was laid out bottom-to-top instead of top-to-bottom. After that, it made perfect sense. While it was a excellent way to demonstrate his argument, it failed to prove his point, because, while top-to-bottom may be the way he reads things, it isn't the way _everyone_ reads things. So, as far as I'm concerned, post your posts in whatever manner works for you. If it's in English, I'll figure it out. If not, well, there's always Babelfish. ;^) Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: Steven D'Aprano [mailto:steve at REMOVE.THIS.cybersource.com.au] > Sent: Friday, January 19, 2007 11:30 AM > To: python-list at python.org > Subject: Re: when format strings attack > > On Fri, 19 Jan 2007 10:43:53 -0800, John Zenger wrote: > > > Perhaps it is not as severe a security risk, but pure Python programs > > can run into similar problems if they don't check user input for % > > codes. > > Please don't top-post. > > A: Because it messes up the order that we read things. > Q: Why? > A: Top-posting. > Q: What is the most annoying newsgroup habit? > > > > Example: > > > >>>> k = raw_input("Try to trick me: ") > > Try to trick me: How about %s this? > >>>> j = "User %s just entered: " + k > >>>> print j % "John" > > Traceback (most recent call last): > > File "", line 1, in ? > > print j % "John" > > TypeError: not enough arguments for format string > > That's hardly the same sort of vulnerability the article was talking > about, but it is a potential bug waiting to bite. > > In a serious application, you should keep user-inputted strings separate > from application strings, and never use user strings unless they've been > made safe. See Joel Spolsky's excellent article about one way of doing > that: > > http://www.joelonsoftware.com/articles/Wrong.html > > > > -- > Steven. > From S.Mientki-nospam at mailbox.kun.nl Tue Jan 30 18:41:11 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 31 Jan 2007 00:41:11 +0100 Subject: how to "free" an object/var ? Message-ID: If I create a large array of data or class, how do I destroy it (when not needed anymore) ? Assign it to an empty list ? thanks, Stef Mientki From laurent.pointal at limsi.fr Tue Jan 23 07:16:20 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 23 Jan 2007 13:16:20 +0100 Subject: I need suggests In-Reply-To: <1169551582.196591.48140@v45g2000cwv.googlegroups.com> References: <1169551582.196591.48140@v45g2000cwv.googlegroups.com> Message-ID: Pat a ?crit : > I have to do a big programm. Could someone give me some suggests about > IDE (on Linux) and books to learn. > + For the IDE: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Test some, take the one corresponding to your taste/feeling. + For books: http://wiki.python.org/moin/PythonBooks You may get more help in c.l.python about book choice by explaining to readers what is your computer science knowledge level, and what is the domain of this big program (text processing, network, GUI...). A+ Laurent. From martin at v.loewis.de Tue Jan 9 17:46:41 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Jan 2007 23:46:41 +0100 Subject: Python - C# interoperability In-Reply-To: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> References: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> Message-ID: <45a41b51$0$19653$9b622d9e@news.freenet.de> mc schrieb: > Is there an easy way to compile a Python class (or set of classes) into > a .DLL that a C# program can call? Or otherwise to use an existing > library of Python classes from a C# program as seamlessly as possible? You should take a look at IronPython, which supports that kind of thing. Regards, Martin From webraviteja at gmail.com Tue Jan 9 01:41:47 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Jan 2007 22:41:47 -0800 Subject: How to write temporary data to file? In-Reply-To: References: Message-ID: <1168324907.803841.79020@42g2000cwt.googlegroups.com> Thomas Ploch wrote: > Hi folks, > > I have a data structure that looks like this: > > d = { > 'url1': { > 'emails': ['a', 'b', 'c',...], > 'matches': ['d', 'e', 'f',...] > }, > 'url2': {... > } > > This dictionary will get _very_ big, so I want to write it somehow to a > file after it has grown to a certain size. > > How would I achieve that? > > Thanks, > Thomas Pickle/cPickle are standard library modules that can persist data. But in this case, I would recommend ZODB/Durus. (Your code example scares me. I hope you have benevolent purposes for that application.) Ravi Teja. From gagsl-py at yahoo.com.ar Wed Jan 17 16:20:31 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Jan 2007 18:20:31 -0300 Subject: 2.3-2.5 what improved? In-Reply-To: <1169040587.340057.11040@m58g2000cwm.googlegroups.com> References: <1169040587.340057.11040@m58g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20070117181603.046aa858@yahoo.com.ar> At Wednesday 17/1/2007 10:29, billie wrote: > > Python 2.5 became quite fat. For bare CGI the Python load/init > > time eats all improvements. Smaller scripts even loose lot of speed. >What do you mean? Fat of libraries or fat itself? >I tought that 2.5 was faster than precedent versions! :-\ It runs faster, but has a slower start time. For CGI, when you launch a new process with every request, this is bad. (This is a general problem with CGI itself - perhaps one should consider other alternatives, like FastCGI, mod_python, WSGI...) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Thu Jan 25 20:21:45 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 22:21:45 -0300 Subject: Right-Justifying Numeric Output In-Reply-To: References: Message-ID: <7.0.1.0.0.20070125222128.04779e10@yahoo.com.ar> At Thursday 25/1/2007 19:34, Rich Shepard wrote: > > assuming max size = 10 > > > > #with spaces > >>> '% 10d' % 11 > > ' 11' > > #with zeros > >>> '%010d' % 11 > > '0000000011' > > Thank you very much! I didn't see this in any of my Python books or on the >Web. http://docs.python.org/lib/typesseq-strings.html -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From deets at nospam.web.de Tue Jan 30 07:41:04 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 Jan 2007 13:41:04 +0100 Subject: error messages containing unicode References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> <1170160464.576122.62230@h3g2000cwc.googlegroups.com> Message-ID: <528sn0F1nhkoiU1@mid.uni-berlin.de> >> (2) convert the file name to ASCII before you store it; or > I need the non-ascii information, though, which is why I included it > in the error message. Then convert it to utf-8, or some encoding you know it will be used by your terminal. Diez From R.Brodie at rl.ac.uk Mon Jan 8 09:06:36 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Mon, 8 Jan 2007 14:06:36 -0000 Subject: Bizarre floating-point output References: Message-ID: "Nick Maclaren" wrote in message news:enthjb$p0l$1 at gemini.csx.cam.ac.uk... > > x = (1.234567890125, 1.2345678901255) > print x > print x[0], x[1] > >>>> (1.2345678901249999, 1.2345678901254999) >>>> 1.23456789012 1.23456789013 > > Is there a rational reason, or is that simply an artifact of the way > that the code has evolved? It is clearly not a bug :-) print x[0] gives the same result as printing str(x[0]), the value of x formatted as a string (rounded to a sensible number of places). x[0] at the command prompt gives the same result as printing repr(x), the representation of the text value as a string. When you do print on a tuple it doesn't recursively call str(), so you get the repr representations. You can get similar results with anything where the str() and repr() values are different. e.g. x = ( u'a', u'b') From mail at microcorp.co.za Tue Jan 9 02:13:37 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 9 Jan 2007 09:13:37 +0200 Subject: Bitwise expression References: Message-ID: <021a01c733c8$40684700$03000080@hendrik> "Gigs_" wrote: > Can someone explain me bitwise expression? > few examples for every expression will be nice > > x << y Left shift > x >> y Right shift > x & y Bitwise AND > x | y Bitwise OR > x ^ y Bitwise XOR (exclusive OR) > ~x Bitwise negation The short, and possibly weird, but true, answer is: If you have to ask this question, you should avoid using these things. - Think of them as "Advanced Magic" But this is unhelpful, so a slightly longer answer is: Computer memory is like a long string of flip-flops that can take on one of two states - "on" or "True" represented normally by a digit 1, and "off" or "False" - a digit 0. Hence the term binary. Binary means "two valued", just like a Bicycle has two wheels. These flip-flops are the smallest element of memory, and one of them is called a "bit". The plural is "bits". "plural" means "more than one of". Eight bits are called a Byte. Half a Byte is a Nibble - four bits (sometimes spelt Nybble by people who are trying to be cute). There is a concept called a "Word" of memory which is ill defined. Sometimes it is one or two Bytes, sometimes three nibbles, sometimes four, eight or sixteen bytes - depends on the hardware's bus width. No, I am not going to explain what a bus is. You can think of a python number as a word of eight bytes long, and a python string as a number of bytes of arbitrary length. I am also not going to explain big and little endian representation. Yahoo for it. Now the logic operators, as applied to nibbles: 1110 << 0111 - shifted left, filled with zero from right (multiply by two - seven to fourteen) 0010 >> 0100 - shifted right, filled with zero from left (divide by two - four to two) 0100 = 0101 & 1110 - true if both bits true, false otherwise (used for masking, clearing bits) 1101 = 0101 | 1100 - false if both bits false, true otherwise (True if either bit true - used to set bits) 1001 = 0101 ^ 1100 - true if only one of the bits true, else false (anything xored with itself is all zero) (used to toggle bits, identity testing) 1001 ~ 0110 - inversion "not" - not true is false, not false is true Also yahoo for "Boolean algebra" and "De Morgan" and "IEEE floating point representation" hth - Hendrik From richard at nospam.com Mon Jan 8 16:47:41 2007 From: richard at nospam.com (Richard Townsend) Date: Mon, 8 Jan 2007 21:47:41 +0000 Subject: Bitwise expression References: Message-ID: <1xe2u3rh89yyj.zuucb7yepvdj.dlg@40tude.net> On Mon, 08 Jan 2007 22:32:12 +0100, Gigs_ wrote: > Can someone explain me bitwise expression? > few examples for every expression will be nice > http://wiki.python.org/moin/BitwiseOperators -- Richard From smusnmrNOSPAM at yahoo.com Fri Jan 12 04:15:30 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Fri, 12 Jan 2007 10:15:30 +0100 Subject: pygame and python 2.5 Message-ID: Hi all, when I rtry to install pygame (pygame-1.7.1release.win32-py2.4.exe, the most ciurrent version I found) it requires Python 2.4! Will I really have to uninstall my Python 2.5 and install the old Python 2.4 in order to use pygame? Thanks, Siggi From bthom at cs.hmc.edu Fri Jan 5 00:57:22 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Thu, 04 Jan 2007 21:57:22 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: <459DCC77.2030708@gmx.net> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> <459DCC77.2030708@gmx.net> Message-ID: <103909CE-118D-428A-B865-46896785A30E@cs.hmc.edu> On Jan 4, 2007, at 7:56 PM, Thomas Ploch wrote: > Gabriel Genellina schrieb: >> At Thursday 4/1/2007 23:52, jeremito wrote: >> >>> I am writing a class that is intended to be subclassed. What is the >>> proper way to indicate that a sub class must override a method? >> >> If any subclass *must* override a method, raise >> NotImplementedError in >> the base class (apart from documenting how your class is supposed >> to be >> used). >> >> > > I learn so much from this list. I didn't even know this error existed. Me too. I was looking for a definitive list of Python errors, although I realize some folks do things like: class foo : def __init__() : def bar() : abstract class baz(foo) : def __init__() : def bar() : This does what you want in that if baz's bar wasn't defined, calling this method on a baz instance would give some kind of "variable not found error." I imagine the NotImplementedError is actually a defined object, but I really don't know. So, back to my question: is a catalog of standard python errors available? I've looked on the python site but had no success. Thanks, --b From rtw at freenet.co.uk Fri Jan 5 05:09:03 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Fri, 05 Jan 2007 04:09:03 -0600 Subject: where to find wx package References: Message-ID: siggi wrote in news:enl7h1$49m$1 at zam602.zam.kfa-juelich.de in comp.lang.python: > Hi all, > > a newbie question: > > I have a program gui03A.py using wxPython, importing it such: > "from wxPython.wx import *" > > The program works, but I get the warning message: > > "gui03A.py:4: DeprecationWarning: The wxPython compatibility package > is no longer automatically generated or activly maintained. Please > switch to the wx package as soon as possible." > > However, after extensive searching on www.python.org and Googling the > web, I do not find any package with "wx" as its only name. > > Where can I get the wx package (for win32 XP)? The "wx package" talked about above is also part of WxPython, so you have already got it. To import it use: import wx You will need to translate all (well most) identifiers in your programme from wxBlah to wx.Blah so: class MyFrame( wxFrame ): pass becomes class MyFrame( wx.Frame ): pass Rob. -- http://www.victim-prime.dsl.pipex.com/ From gagsl-py at yahoo.com.ar Sun Jan 7 13:40:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 10:40:49 -0800 Subject: Recommended way to force a thread context switch? In-Reply-To: References: <1168103258.602286.146100@42g2000cwt.googlegroups.com> <1168104008.910681.46800@38g2000cwa.googlegroups.com> Message-ID: <1168195249.257166.322740@51g2000cwl.googlegroups.com> On 6 ene, 20:01, Lloyd Zusman wrote: > It seems that the original writer of the app had set this interval to a > high value in a part of the code that I overlooked until you mentioned > this right now. > > [...] once one of the big > number-crunching threads gets control, it starves out the monitoring > threads, which is not a good thing for my app ... or at least it did > so with the original large checkinterval. This is why such settings should be in a configuration file or in a prominent place in the application... I had a program where, deep in an unknown function, the original coder changed the process priority - with no valid reason, and in any case, that should be an application-level setting. It was hard to find why, after doing such and such things, the system responsiveness were so slow. -- Gabriel Genellina From wanjunfeng at gmail.com Tue Jan 16 21:53:01 2007 From: wanjunfeng at gmail.com (Kevin Wan) Date: 16 Jan 2007 18:53:01 -0800 Subject: I wrote a C++ code generator in Python, would anyone please help me to review the code? :) In-Reply-To: <1168943577.936249.191040@s34g2000cwa.googlegroups.com> References: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> <1168943577.936249.191040@s34g2000cwa.googlegroups.com> Message-ID: <1169002381.334281.218390@s34g2000cwa.googlegroups.com> I'm writing the document for fgen. You can use SVN to access the most updated files. Basically you can use fgen --help to get the usage. It's my c++ development tool, and I didn't spend that much time on writing document. Sorry. But I'm writing now. Thanks and waiting to work with you guys, Kevin Vineeth Kashyap wrote: > Hi, > I am interested in your proposal. I am basically a C/C++ programmer, > but recently fell in love with python. Please send more details on > fgen. We could probably start working. :) > Kevin Wan wrote: > > fgen is a free command line tool that facilitates cross platform c++ > > development, including header generation, cpp file generation, makefile > > generation, unit test framework generation, etc. > > > > http://sf.net/projects/fgen > > > > I'm not very familiar with Python. Any feedback are appreciated! Or > > anyone like to develop it with me? > > > > Thanks. From gandalf at designaproduct.biz Mon Jan 22 13:52:17 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 22 Jan 2007 19:52:17 +0100 Subject: closing a "forever" Server Socket In-Reply-To: <1169488142.312711.322320@51g2000cwl.googlegroups.com> References: <1169123381.930403.24170@38g2000cwa.googlegroups.com> <1169143715.222186.30530@51g2000cwl.googlegroups.com> <1169482385.253887.249030@51g2000cwl.googlegroups.com> <1169488142.312711.322320@51g2000cwl.googlegroups.com> Message-ID: <45B507E1.2000803@designaproduct.biz> alessandro ?rta: > Oh my God! it's really so complicated? > > 3 modules (threading, SocketServer, select) only for design a way to > shutdown a TCP server???? > ...but they told me that python was easy... :) > I believe that SockerServer was created for testing purposes, although there are some programs using it in production. Yes, Python is easy. The language is very clear, and you do not need to install third party modules in order to create a server. :-) Of course the easiest way is to call serve_forever. Isn't it easy? The other way is to implement your own message handling loop. The SocketServer is flexible enough to do this; and I don't think it is complicated. 7 lines of code will allow you to stop the server safely from anywhere, even from other threads. Try to implement the same in C or Delphi... > but it doesen't work because the server remain alive...maybe > SocketServer create immortal server... > I need only to close my application, there is a way to force the server > thread to close? > In pure Python, no. Python threads are "cooperative". In other words, they cannot be terminated from outside. A thread will stop after the execution exits its "run" method. (You can, of course terminate the tread with an operating system function, but it is not recommended.) Here is a class that can be stopped with an event: import threading stop_requested = threading.Event() class SoftWaitThread(threading.Thread): """SoftWaitThread can wait for a given time except if the thread was asked to terminate itself.""" def waitsome(self,amount=10): """Wait the specified amount of time. This can be terminated by stop_requested within 0.1 seconds.""" for idx in range(int(10*amount)): time.sleep(0.1) if stop_requested.isSet(): break Then you can do this: class MyServerThread(SoftWaitThread): def run(self): server = MySocketServerClass() srvfd = server.fileno() while not stop_requested.isSet(): ready = select.select([srvfd], [], [], 1) if srvfd in ready[0]: server.handle_request() else: pass And then: import time def main(): sth = MyServerThread() # Create your thread sth.start() # Start handling requests in another thread try: time.sleep(TIMEOUT_IN_SECONDS) # Wait... finally: stop_requested.set() # Request the server thread to stop itself sth.join() # Wait until the server thread stops print "Stopped." You could start several threads and request them to stop with the same event. I hope this helps. Laszlo p.s.: Not all of the above was tested, be careful. From bearophileHUGS at lycos.com Sun Jan 7 08:22:57 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Jan 2007 05:22:57 -0800 Subject: I want to learn In-Reply-To: <1168174097.252001.71130@s80g2000cwa.googlegroups.com> References: <1168174097.252001.71130@s80g2000cwa.googlegroups.com> Message-ID: <1168176177.793184.122250@v33g2000cwv.googlegroups.com> joeyslistings at yahoo.com: > I am looking for a python guru who has instant messenger or gtalk or > whatever who can meet me > online in the mornings, give me some direction for the day and then > answer some questions here and there online throughout the day. Maybe a Python gury isn't necessary, maybe a person that know the language enough may be enough. Bye, bearophile From stou.sandalski at gmail.com Fri Jan 19 02:59:54 2007 From: stou.sandalski at gmail.com (Stou Sandalski) Date: 18 Jan 2007 23:59:54 -0800 Subject: Pass 'this' to a python script in an extended application References: <1169165539.529443.289120@v45g2000cwv.googlegroups.com> Message-ID: <1169193594.727868.39160@s34g2000cwa.googlegroups.com> I figured it out. I just made my main class a singleton and it worked fine... it always works right after I post a message =) Stou Stou Sandalski wrote: > Hi, > > I have an application consisting of a main C++ class (and other > classes) stored inside a DLL. The application uses a small main > executable that links against the main DLL, then initializes and runs > the core class. The python bindings are inside a .pyd module that also > links against the core DLL file. I was able to generate the python > bindings against the core class using SWIG. The application can now > be run either by the bootstrap executable or through the python console > like: > > import foo > s = foo.MainClass() > s.run(); > > This is awesome, however I want to be able to launch python scripts > from within the application itself (no matter how it was started) and > supply these scripts with a "pointer" to the already initialized main > Class something like: > > import foo > > s = foo.GetMainClass() > s.someMethod(). > > I found this: > > http://docs.python.org/ext/extending-with-embedding.html > > but the problem is that I don't know how to "give" the python > interpreter a "pointer" to my class that will be compatible with the > already defined bindings that SWIG generated. I am trying to keep the > core application dll from knowing about the .pyd extension module. > > I apologize if this post belongs in a group dedicated to SWIG. > > Stou From gagsl-py at yahoo.com.ar Fri Jan 5 10:16:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 12:16:26 -0300 Subject: bug in copy.deepcopy or in getattr or in my understanding? In-Reply-To: <1168005716.195293.121490@38g2000cwa.googlegroups.com> References: <1167942359.246311.80700@s34g2000cwa.googlegroups.com> <1168005716.195293.121490@38g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070105120717.05ce0ef8@yahoo.com.ar> At Friday 5/1/2007 11:01, Emin wrote: >Thank you for your reply. As you guessed, I want to be able to select >the method at runtime as in your final example, but when I tried your >suggestion I got the same error (see below). I think the problem is >that getattr is donig something different than in my example where I >explicitly get it from the dict (see the very end of the transcript >below): I've modified it as follows: - using new.instancemethod to create the dynamic method - copy uses __getstate__ to determine what is needed to copy/save. Assuming that self.x is derived from other attributes, it's not actually needed in the saved state, and can be omited. - __setstate__ does the inverse: after reconstructing the object state, sets self.x to the right value === cut === import new class A: def foo(self, arg): print "in foo, self=%r arg=%r" % (self, arg) class B(A): def __init__(self): self.update_dynamic_methods() def update_dynamic_methods(self): "Should assign the dynamic methods based on other attributes" self.x = new.instancemethod(getattr(A,"foo"),self,B) def __getstate__(self): state = self.__dict__.copy() if 'x' in state: del state['x'] return state def __setstate__(self, state): self.__dict__.update(state) self.update_dynamic_methods() b=B() b.something = 'something' b.foo(123) b.x(123) import copy b2 = copy.deepcopy(b) assert b2.something=='something' b2.foo(123) b2.x(123) === cut === -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From klaus at seistrup.dk Sun Jan 28 05:26:57 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sun, 28 Jan 2007 10:26:57 +0000 (UTC) Subject: IP address References: Message-ID: Scripter47 wrote: > How do i get my ip address? > > in cmd.exe i just type "ipconfig" then it prints: > ... > IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 > ... > how can i do that in python?? #v+ python -c 'import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' #v- Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From noway at ask.me Wed Jan 24 09:00:49 2007 From: noway at ask.me (Giovanni Bajo) Date: Wed, 24 Jan 2007 15:00:49 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: <45b69f63$0$24463$88260bb3@free.teranews.com> References: <45b69f63$0$24463$88260bb3@free.teranews.com> Message-ID: On 24/01/2007 1.45, Joshua J. Kugler wrote: >> I've downloaded both the wxPython and the PyQt4 package, and by the >> first impression I must say that the PyQt4 system had a very >> compelling presentation. From what I can understand from the feedback >> I've gotten so far is that the wxPython is a better choice when it >> comes to compability (with linux), and it's free even if I want to >> create applications and sell them. >> So, from what I understand I will have to go with PyQt4 since (from >> my understanding): >> 1. I will not sell the applications I'm working with since they will >> only be used by the internal QA at a computer game company. > > Even that is getting on shaky ground, at least according to Troll Tech. > See: http://www.trolltech.com/developer/knowledgebase/190/ So, write it > for internal use, and put up for distribution on your personal web site > (pending company approval, of course). That page is legal babble, trying to trick you into buying (or making your boss buy) a commercial license. The Qt Open Source edition *IS* GPL and thus it falls under all the normal GPL clauses and uses, irrespective of what Trolltech may or may not think. For instance, see this FAQ: http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic which makes pretty clear that a "company"/"organization" is basically the same of an "individual". "Releasing a software within a company for internal usage" is by no means the same of "releasing it to the public". Basically, for what the GPL is concerned, it is *not* a "release" or a "distribution" at all. Thus, it is well possible to write internal GPL software, using the Qt Open Source library, and to release/distribute/use it *ONLY* internally. Also, it should be made clear that a company can of course relicense its own proprietary libraries as GPL for internal usage only, so that they can be linked to other GPL libraries "legally". For instance, in the case of Daniel and his game company, they can link their proprietary game code to PyQt4 (Open source edition) to produce an internal tool, like a level editor, which would then fall under the GPL. If and only if they were to release that tool to the public (either for free or for sale), they would have to either go GPL and release full source code (include the parts of their game code linked to it), or buy a Qt commercial license. [[ Another page of similar babble is the one where they try to convince you that you cannot use the Qt Open Source edition to develop a software, and then buy the commercial edition only the day before you want to release it as non open-source. I can't even understand how they can even try to support such a nonsense position. You're free to develop your software for years as GPL without distributing it, and then relicense your own code whenever you want. They're obviously just trying to scare people. ]] -- Giovanni Bajo From skip at pobox.com Wed Jan 17 16:49:44 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Jan 2007 15:49:44 -0600 Subject: Would a Dutch speaker please check this wiki page please? Message-ID: <17838.39416.809225.736074@montanaro.dyndns.org> Got a note about a new page on the Python Wiki: >>>>> "Wade" == Wade McDaniel writes: http://wiki.python.org/moin/Selcuk_Altun I suspect it's junk since it doesn't seem to mention Python and the website it mentions doesn't seem to exist. Still, just in case... Thx, Skip From wccppp at gmail.com Thu Jan 4 12:32:02 2007 From: wccppp at gmail.com (wcc) Date: 4 Jan 2007 09:32:02 -0800 Subject: where to ask questions related to comtypes? In-Reply-To: References: <1167891509.842292.125420@i80g2000cwc.googlegroups.com> Message-ID: <1167931922.412066.27630@i15g2000cwa.googlegroups.com> Thank you Thomas. On Jan 3, 11:10 pm, Thomas Heller wrote: > wcc schrieb: > > > Hello group, > > > Is there a separate mailing list for comtypes? Or this is the > > appropriate place to post questions related to this package(from Thomas > > Heller)?It seems the python-win32 mailing list is the place where the most COM knowledge > is, so that would be most appropriate. Other places are *this* list or the > ctypes-users lists (since comtypes is based on ctypes). > > Thomas From pavlovevidence at gmail.com Sat Jan 13 19:05:40 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 13 Jan 2007 16:05:40 -0800 Subject: Threaded for loop In-Reply-To: References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> Message-ID: <1168733139.935538.118500@38g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > On 13 Jan 2007 12:15:44 -0800, "John" declaimed > the following in comp.lang.python: > > > > > I want to do something like this: > > > > for i = 1 in range(0,N): > > for j = 1 in range(0,N): > > D[i][j] = calculate(i,j) > > > > I would like to now do this using a fixed number of threads, say 10 > > threads. > > What is the easiest way to do the "parfor" in python? > > > > Thanks in advance for your help, > > --j > > Don't know if it's the easiest -- and if "calculate" is a CPU-bound > number cruncher with no I/O or other OS-blocking calls, it won't be > faster either as the GIL will only let one run at a time, even on > multi-core processors. It could still be helpful if you'd like to get as much done as possible in as short a time as possible, and you suspect that one or two cases are likely to hold everything up. Carl Banks From usenet200701 at tobyinkster.co.uk Sun Jan 28 09:15:27 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Sun, 28 Jan 2007 14:15:27 +0000 Subject: Commandline wrapper: help needed References: <45bb7527$0$20806$5fc30a8@news.tiscali.it> Message-ID: Toby wrote: > Any idea how to improve the script and solve this problem? Hello Toby, excellent name you have there. What advantage (if any) does this method have over standard UNIX-style pipes? -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact From tsuraan at gmail.com Mon Jan 8 10:41:23 2007 From: tsuraan at gmail.com (tsuraan) Date: Mon, 8 Jan 2007 09:41:23 -0600 Subject: Suitability for long-running text processing? Message-ID: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> I have a pair of python programs that parse and index files on my computer to make them searchable. The problem that I have is that they continually grow until my system is out of memory, and then things get ugly. I remember, when I was first learning python, reading that the python interpreter doesn't gc small strings, but I assumed that was outdated and sort of forgot about it. Unfortunately, it seems this is still the case. A sample program (to type/copy and paste into the python REPL): a=[] for i in xrange(33,127): for j in xrange(33,127): for k in xrange(33,127): for l in xrange(33, 127): a.append(chr(i)+chr(j)+chr(k)+chr(l)) del(a) import gc gc.collect() The loop is deep enough that I always interrupt it once python's size is around 250 MB. Once the gc.collect() call is finished, python's size has not changed a bit. Even though there are no locals, no references at all to all the strings that were created, python will not reduce its size. This example is obviously artificial, but I am getting the exact same behaviour in my real programs. Is there some way to convince python to get rid of all the data that is no longer referenced, or do I need to use a different language? This has been tried under python 2.4.3 in gentoo linux and python 2.3 under OS X.3. Any suggestions/work arounds would be much appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.one at comcast.net Wed Jan 3 12:48:48 2007 From: tim.one at comcast.net (Tim Peters) Date: Wed, 03 Jan 2007 11:48:48 -0600 Subject: a question on python dict References: Message-ID: [Tim Peters] >> ... >> Taking my response out of context to begin with doesn't really change >> that I answered the question he asked ;-) [Fredrik Lundh] > welcome to comp.lang.python. > > Thanks for the welcome! It's tough to be a newbie here ;-) From tiedon_jano at hotmail.com Mon Jan 8 04:09:23 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Mon, 08 Jan 2007 09:09:23 GMT Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: <1168194009.220437.286210@q40g2000cwq.googlegroups.com> <1168198159.798783.168010@i15g2000cwa.googlegroups.com> Message-ID: <7Tnoh.62$cQ2.11@read3.inet.fi> W. Watson kirjoitti: > Gabriel Genellina wrote: >> On 7 ene, 16:20, "W. Watson" wrote: >> >>> We seem to be looping. I have the Python interpreter. I would like the >>> pythonwin editor. The download link doesn't work on SourceForge. >>> Where can I >>> get it? If not there, where? If it can't be obtained, then I'll go to >>> the >>> default editor built into python-2.5.msi. >> >> It *does* work for me. Try >> https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063 >> >> > I can easily see the page you refer to, but where's the pythonwin editor? > > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > A road sign along many highways reads, "$1000 > fine for littering" I have yet to find any > $1000 bills. WTW The editor is only a part of pywin32, which is a handy package to do all kinds of Windows only stuff with Python. So download and install pywin32 to get the editor and all that other nice stuff. HTH, Jussi From S.Mientki-nospam at mailbox.kun.nl Fri Jan 5 14:09:47 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 05 Jan 2007 20:09:47 +0100 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? Message-ID: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Not sure I wrote the subject line correct, but the examples might explain if not clear *** first attempt *** class pin: def __init__ (self): self.Name = 'Unknown Pin' aap = pin() # create an instance aap.Name = 'aap' # set it's name print aap.Name # print it's name # but why should I set it's name ?? print 'aap' # I can just as well print a constant string !! # (ok there will be an extra check) *** second attempt *** class pin2: def __init__ (self, naam): self.Name = naam aap2 = pin2('aap2') # seems completely redundant to me. print aap2.Name print 'aap2' Can this be achieved without redundancy ? thanks, Stef Mientki From paul at boddie.org.uk Fri Jan 12 13:23:41 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Jan 2007 10:23:41 -0800 Subject: parsing a file name References: <1168622211.188972.179680@38g2000cwa.googlegroups.com> Message-ID: <1168626221.581533.128750@s34g2000cwa.googlegroups.com> Chris Mellon wrote: > > I'm trying to think of a good reason to extract the version from the > filename instead of using RPM to get the real version from the > metadata and I can't come up with one. The inquirer doesn't have any RPM handling tools installed/available or is dealing with a lot of versioned filenames which might be a selection of different, arbitrary formats. Try harder! ;-) Paul From larry.bates at websafe.com Tue Jan 30 19:03:44 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 30 Jan 2007 18:03:44 -0600 Subject: DCOP memory leak? In-Reply-To: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> References: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> Message-ID: TimDGCB at gmail.com wrote: > Hello, > > I'm writing a python script for Amarok, I communicate with Amarok > using DCOP. > Now, I have to call DCOP very often and I noticed that every time I > make a DCOP call my program keeps growing in memory size. > > To make sure it was DCOP i wrote the small program below: > > from dcopext import DCOPClient, DCOPApp > > while 0==0: > dcop=DCOPClient() > dcop.attach() > AmarokDcopRes = DCOPApp ("amarok", dcop) > ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() > print Ms > > If you run this script and monitor it's memory use you'll see that it > keeps growing. > > Does anyone know how I can solve this problem? > > Kind regards, > > Tim > I think you will find the objects are getting created so fast that garbage collection doesn't have time to clean them up as fast as you are creating new ones. Since del dcop is not guaranteed to be "immediate" that won't help. Q: Can't you create dcop instance outside the loop and reuse it for every time through the loop? Q: Can you sleep or something after each loop or do you really want to peg the CPU checking forever? Q: How do you ever get out of this infinite loop? Note: while 0=0 is better written as while 1: and you need a break somewhere to get out of the loop. -Larry From nogradi at gmail.com Wed Jan 31 12:59:26 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 31 Jan 2007 18:59:26 +0100 Subject: subway In-Reply-To: <17856.50898.477998.112022@montanaro.dyndns.org> References: <5f56302b0701310802y7e45c98fmaaebe090e34d410@mail.gmail.com> <17856.50898.477998.112022@montanaro.dyndns.org> Message-ID: <5f56302b0701310959o424ab298jac4b21fb38b20a99@mail.gmail.com> > Daniel> Does anyone know what has happened to the codebase of the subway > Daniel> project? It seems the whole project has been shut down leaving > Daniel> no trace of the code on net but I would be very happy to see it, > Daniel> apparently it had some cool features that would be fun to look > Daniel> at. Does anyone have access to the code and/or is willing to > Daniel> make it publically available? > > No guarantee that it will have any remnants of the subway project, but the > Wayback Machine might be a good place to start: > > http://web.archive.org/web/*/http://subway.python-hosting.com Thanks, that's a great idea, actually loads of stuff are on it, but somehow from the link http://web.archive.org/web/20060206044039/http://www.gosubway.org/install/Subway-0.2rc1-py2.4.egg the egg file can not be downloaded completely, the connection is closed at byte 138903 all the time and the file is bigger than that. If anyone managed to grab the file please let me know so far I tried wget and firefox. From metaperl at gmail.com Wed Jan 24 14:51:27 2007 From: metaperl at gmail.com (metaperl) Date: 24 Jan 2007 11:51:27 -0800 Subject: Re-thinking my if-thens - a software engineering question Message-ID: <1169668287.517657.24450@l53g2000cwa.googlegroups.com> Ok, I have a module called textgen.py. The point of this module is to generate a csv file from an array of dictionaries. As I iterate through each dictionary, I "massage" the dictionary values before writing them out to csv. Now, for one dictionary entry, I have the following code: if dict_key == 'PCN': fields = dict_val.split("/") mo = re.match( '(\w{2})(\d{2})(\d{2})' , fields[1] ) if mo: dict_val = "%s/%s%s/%s" % (fields[0], mo.group(1), mo.group(3), fields[2][1:]) else: dict_val = dict_val Ok, so now here is what has happened. This code was based on the assumption that dict_val would have 2 forward slashes in it. It turns out that I need to follow a different process of massaging when no slashes are present. A naive solution would be something like: if dict_key == 'PCN': fields = dict_val.split("/") if fields == 3: dict_val = pcn_three(fields) # where pcn_three is the code above else: # new logic But I am wondering if I should abstract the flow of control into a class or something. Ideas welcome. From jgodoy at gmail.com Fri Jan 19 19:28:03 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Fri, 19 Jan 2007 22:28:03 -0200 Subject: OT Annoying Habits References: Message-ID: <874pqmwnho.fsf@gmail.com> "Carroll, Barry" writes: > Secondly, can someone point me to the Standard Usenet Convention that > mandates against top-posting. This is not sarcasm; I would really like You can read RFC 1855. Section 3.1.3 talks about newsgroups. Section 3.1.1 has general guidelines and it includes this: If you are sending a reply to a message or a posting be sure you summarize the original at the top of the message, or include just ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ enough text of the original to give a context. This will make sure readers understand when they start to read your response. Since NetNews, especially, is proliferated by distributing the postings from one host to another, it is possible to see a response to a message before seeing the original. Giving context helps everyone. But do not include the entire original. I've added the "^" to mark the part where it says what should be on the top of the message. You can check it: http://www.dtcc.edu/cs/rfc1855.html Be seeing you, -- Jorge Godoy From karoly.kiripolszky at gmail.com Sun Jan 28 07:52:40 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky at gmail.com) Date: 28 Jan 2007 04:52:40 -0800 Subject: binary for osx needed Message-ID: <1169988760.823656.39710@v45g2000cwv.googlegroups.com> helo ppl! i wrote a small mp3 streaming server called "csikk" in python using basehttpserver. you can give it a try if you wish: http://code.google.com/p/csikk/ actually i need help in compiling an osx binary for my app, cause i don't own a mac. i wonder if anyone could help me. thanks in advance! From nospam at riddergarn.dk Mon Jan 29 15:04:47 2007 From: nospam at riddergarn.dk (Scripter47) Date: Mon, 29 Jan 2007 21:04:47 +0100 Subject: SQL connecting In-Reply-To: References: Message-ID: <45BE535F.90904@riddergarn.dk> John Nagle skrev: > Scripter47 wrote: >> Hey >> >> It got a problem with python to connect to my SQL DBs, that's installed >> on my apache server. how do i connect to sql? Gettting data? Insert into >> it? > > You need a third-party open source package called "MySQLdb". > > John Nagle Yeah look great but im using python 2.5, and it only support 2.3-2.4 :(, but thanks :) Any better solutions :) From mohan.us2010 at gmail.com Tue Jan 9 09:15:08 2007 From: mohan.us2010 at gmail.com (mohan) Date: 9 Jan 2007 06:15:08 -0800 Subject: Using with CSV library in Python 2.2!!! In-Reply-To: References: <1168348224.843657.27330@42g2000cwt.googlegroups.com> Message-ID: <1168352108.295247.280690@51g2000cwl.googlegroups.com> skip at pobox.com wrote: > mohan> 1. Does Python 2.2 come with CSV library module or not? If yes, > mohan> have I lost it somewhere?? > > As the docs for the csv module indicate, it was new in 2.3. > > mohan> 2. If Python 2.2 does not come with CSV module, is it possible to > mohan> add the csv module to the Python root and start working?? > > You might find that it will work with 2.2, though you might have to make > some source code changes to _csv.c to get it to compile. > > mohan> 3. If yes, where do I get this module from?? > > You can get both csv.py and _csv.c via ViewCVS: > > http://svn.python.org/view/*checkout*/python/tags/r236/Modules/_csv.c?content-type=text%2Fplain&rev=52574 > http://svn.python.org/view/*checkout*/python/tags/r236/Lib/csv.py?content-type=text%2Fplain&rev=52574 > > Skip Hi Skip, Thanks man. What kind of source code changes should I do to "_csv.c" file , have you any idea on that too?? Otherwise upgrading to Python 2.4 would be the easiest choice. Thanks again. cheers, Mohan. From tgrav at mac.com Thu Jan 11 09:12:25 2007 From: tgrav at mac.com (Tommy Grav) Date: Thu, 11 Jan 2007 09:12:25 -0500 Subject: Progress count in terminal (Mac OS X) Message-ID: <9079A3B8-47A8-495A-BFAE-09A603CFB819@mac.com> I have a program that does a lot of iterations and would like to follow its progress by having it print out the current iteration number as it progresses. How do I do this so that it appears like a counter that increases in the same place in the terminal window? I am using python2.5 on a Mac OSX and its terminal tcsh window. Cheers Tommy From sturlamolden at yahoo.no Sun Jan 7 11:47:07 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 7 Jan 2007 08:47:07 -0800 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <1168188427.144219.206490@s80g2000cwa.googlegroups.com> time.swift at gmail.com wrote: > Coming from a C++ / C# background, the lack of emphasis on private data > seems weird to me. I've often found wrapping private data useful to > prevent bugs and enforce error checking.. > > It appears to me (perhaps wrongly) that Python prefers to leave class > data public. What is the logic behind that choice? The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that if an object's 'internal' variables or states cannot be kept private, programmers get an irresistible temptation to mess with them in malicious ways. But if you are that stupid, should you be programming in any language? The most widely used language is still C, and there is no concept of private data in C either, nor is it needed. As mentioned in other replies, it is not rocket science to access a class private data. In C++ you can cast to void*, in Java and C# you can use reflection. C++ is said to be an "unsafe" language because programmers can, using a few tricks, mess with the vtables. But how many really do that? In Python variables are kept in strict namespaces. You can ask the compiler to name mangle a variable by prepending underscores. The variable then becomes just as 'private' as a C++ private variable, because as previously mentioned, 'private' variables in C++ can be accessed through a cast to void*. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 11 12:24:33 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 11 Jan 2007 18:24:33 +0100 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> Message-ID: <50na6hF1g30l4U4@mid.individual.net> Laurent Pointal wrote: > Not so sure, there is low CPU in the Python script, Yes. > but there may be CPU+disk activity on the database sides [with > cache management and other optimizations on disk access]. That's it. So data queues up on the database side and you won't get much value from faked concurrency with CPU cycles. > So, with a reader thread and a writer thread, he can have a select > on a database performed in parallel with an insert on the other > database. Explain. Remember, threads aren't really working concurrently. Even on a multiprocessor machine you have constraints for IO traffic. (And the GIL exists too) > But, if its only a do-once job, maybe the optimization is net > really necessary. I still don't understand how threads would help optimizing a task that largely depends on IO and will probably be executed on one CPU. Regards, Bj?rn -- BOFH excuse #14: sounds like a Windows problem, try calling Microsoft support From paul at boddie.org.uk Mon Jan 8 04:24:04 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 8 Jan 2007 01:24:04 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> <1168189375.843789.306180@51g2000cwl.googlegroups.com> <7xps9q19wf.fsf@ruckus.brouhaha.com> Message-ID: <1168248244.134804.138050@51g2000cwl.googlegroups.com> Paul Rubin wrote: > > Right, the problem is if those methods start changing the "private" > variable. I should have been more explicit about that. > > class A: > def __init__(self): > self.__x = 3 > def foo(self): > return self.__x > > class B(A): pass > > class A(B): > def bar(self): > self.__x = 5 # clobbers private variable of earlier class named A Has this ever been reported as a bug in Python? I could imagine more sophisticated "name mangling": something to do with the identity of the class might be sufficient, although that would make the tolerated "subversive" access to private attributes rather difficult. Paul From pjmlp at progtools.org Fri Jan 12 04:12:13 2007 From: pjmlp at progtools.org (Paulo Pinto) Date: Fri, 12 Jan 2007 09:12:13 GMT Subject: What happened to SPE? References: Message-ID: Hi, Thanks for the feedback. Paulo From cjw at sympatico.ca Fri Jan 26 08:27:59 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 26 Jan 2007 08:27:59 -0500 Subject: stop script w/o exiting interpreter In-Reply-To: References: Message-ID: Alan Isaac wrote: > I'm fairly new to Python and I've lately been running a script at > the interpreter while working on it. Sometimes I only want to > run the first quarter or half etc. What is the "good" way to do this? > > Possible ugly hacks include: > > - stick an undefined name at the desired stop point > - comment out the last half > > I do not like these and assume that I have overlooked the obvious. > > Thanks, > Alan Isaac > > Alan, If you are using Windows, you might consider PyScripter. http://mmm-experts.com/Products.aspx?ProductId=4 Colin W. From robert.kern at gmail.com Sat Jan 6 18:46:17 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 06 Jan 2007 17:46:17 -0600 Subject: c# application calling Scipy In-Reply-To: <1168108637.270801.155950@42g2000cwt.googlegroups.com> References: <1168108637.270801.155950@42g2000cwt.googlegroups.com> Message-ID: dongarbage at hotmail.com wrote: > Hi, > > Novice here. :) > > I'm building a c# application and I want to call functions in SciPy > from that application. > > What's the best way to call SciPy methods from a C# program? > > Is there a best Python implementation for this? Ironython? Python for > .NET? Enthought? scipy is a package with many C and FORTRAN extensions, so IronPython won't work unless someone has figured out a magic way to compile them. The Enthought distribution (disclosure: I work for Enthought) is just a bundling of the normal python.org distribution of Python with a bunch of packages; it knows nothing about C#. I know little about Python for .NET beyond its README, but it does seem to be able to embed CPython into a C# application and with some elbow grease, that might work for you. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From vodel at hrz.tu-chemnitz.de Fri Jan 5 07:19:18 2007 From: vodel at hrz.tu-chemnitz.de (Matthias Vodel) Date: Fri, 5 Jan 2007 13:19:18 +0100 Subject: Change coords of a canvas.line item Message-ID: Hi all, I want to change the beginning/end-coordinates of a canvas.line item. Something like: self.myCanvas.itemconfigure(item_id, coords=(x1_new, y1_new, x2_new, y2_new)) I don't want to delete and repaint a new line item. Is this possible? Thanks Matthias From fredrik at pythonware.com Thu Jan 11 09:22:07 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Jan 2007 15:22:07 +0100 Subject: Progress count in terminal (Mac OS X) References: <9079A3B8-47A8-495A-BFAE-09A603CFB819@mac.com> Message-ID: Tommy Grav : >I have a program that does a lot of iterations and would like > to follow its progress by having it print out the current iteration > number as it progresses. How do I do this so that it appears > like a counter that increases in the same place in the terminal > window? I am using python2.5 on a Mac OSX and its terminal > tcsh window. print a carriage return before, and no line feed after, each line: for i in range(100): print "\r" + "count", i, print # done From salvatore.difazio at gmail.com Tue Jan 16 08:58:46 2007 From: salvatore.difazio at gmail.com (Salvatore Di Fazio) Date: 16 Jan 2007 05:58:46 -0800 Subject: Watch log In-Reply-To: References: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> <512astF1i9fgbU1@mid.individual.net> <1168897765.370442.201660@51g2000cwl.googlegroups.com> Message-ID: <1168955926.261983.97320@51g2000cwl.googlegroups.com> Thinker ha scritto: > What you want is something like 'tail -f' in linux. > If you look into it's source code, you will find it check file periodically. > When a read() reach the end of the file, read() will return a empty string. > You can try to read data from the file periodically after a EOF. > I think it is what you want. So every 2 sec: - open the file - read the file from the oldPosition to the EOF - save the last position in file - first point mmm ok From arkanes at gmail.com Fri Jan 12 13:16:31 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 12 Jan 2007 12:16:31 -0600 Subject: parsing a file name In-Reply-To: <1168622211.188972.179680@38g2000cwa.googlegroups.com> References: <1168622211.188972.179680@38g2000cwa.googlegroups.com> Message-ID: <4866bea60701121016q245b50f3n3b0929b0e195dca0@mail.gmail.com> On 12 Jan 2007 09:16:51 -0800, CSUIDL PROGRAMMEr wrote: > I have a filename > cairo-2.3.4.src.rpm > Is there any way i can only get 2.3.4 from this file name > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm trying to think of a good reason to extract the version from the filename instead of using RPM to get the real version from the metadata and I can't come up with one. From steve at REMOVEME.cybersource.com.au Mon Jan 29 21:48:11 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 30 Jan 2007 13:48:11 +1100 Subject: error messages containing unicode References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> Message-ID: On Mon, 29 Jan 2007 18:01:56 -0800, Jim wrote: > Hello, > > I'm trying to write exception-handling code that is OK in the > presence > of unicode error messages. I seem to have gotten all mixed up and > I'd > appreciate any un-mixing that anyone can give me. [snip] >>> class MyException(Exception): pass ... >>> fn = u'a\N{LATIN SMALL LETTER O WITH DIAERESIS}k' >>> raise MyException("hello") Traceback (most recent call last): File "", line 1, in ? __main__.MyException: hello >>> Works fine with an ASCII argument, but not with Unicode: >>> raise MyException(fn) Traceback (most recent call last): File "", line 1, in ? __main__.MyException>>> Notice the terminal problem? (The error message doesn't print, and the prompt ends up stuck after the exception.) Let's capture the exception and dissect it: >>> try: raise MyException(fn) ... except Exception, err: ... print type(err) ... print err ... Traceback (most recent call last): File "", line 4, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128) Now we have the answer: your exception (which just sub-classes Exception) does the simplest conversion of Unicode to ASCII possible, and when it hits a character it can't deal with, it barfs. That doesn't happen until you try to print the exception, not when you create it. The easiest ways to fix that are: (1) subclass an exception that already knows about Unicode; (2) convert the file name to ASCII before you store it; or (3) add a __str__ method to your exception that is Unicode aware. I'm going to be lazy and do a real simple-minded version of (2): >>> class MyBetterException(Exception): ... def __init__(self, arg): ... self.args = arg.encode('ascii', 'replace') ... self.unicode_arg = arg # save the original in case >>> raise MyBetterException(fn) Traceback (most recent call last): File "", line 1, in ? __main__.MyBetterException: a?k And now it works. -- Steven D'Aprano From smusnmrNOSPAM at yahoo.com Mon Jan 8 09:33:21 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Mon, 8 Jan 2007 15:33:21 +0100 Subject: help: code formatter? Message-ID: Hi all, as a newbie I have problems with formatting code of downloaded programs, because IDLE's reformatting capabilities are limited . Incorrect indentation, mixing of TAB with BLANKs or eol are often very nasty to correct. Is there a simple code formatter that first removes all indentations and then refomats correctly? Please help! Thank you, siggi From carsten at uniqsys.com Fri Jan 12 15:28:00 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 12 Jan 2007 15:28:00 -0500 Subject: dynamic argument name for functions In-Reply-To: <8c7f10c60701121222p2187225fn3e0559388a83a16e@mail.gmail.com> References: <8c7f10c60701121222p2187225fn3e0559388a83a16e@mail.gmail.com> Message-ID: <1168633680.3382.96.camel@dot.uniqsys.com> On Fri, 2007-01-12 at 20:22 +0000, Simon Brunning wrote: > On 1/12/07, mark wrote: > > I want to pass a value to an argument of a function. The argument name is > > dynamic and is stored in a > > variable. How do I call the function using with arg_name and value as the > > parameters. > > thanks > > mark > > > > For ex: > > def function(arg1='None', arg2='None', arg3='None'): > > print arg1 > > print arg2 > > print arg3 > > > > > > arg_name = 'arg1' > > arg_value = 'i am passing a value to argument 1' > > function(???????) > > Untested: > > function(**{arg_name: arg_value}) My version is superior: I tested it before replying. ;) -Carsten From richard.szlachta at gmail.com Fri Jan 5 14:02:23 2007 From: richard.szlachta at gmail.com (Richard Szlachta) Date: Fri, 5 Jan 2007 20:02:23 +0100 Subject: Piskworky - "five-in-row" over jabber network Message-ID: <7a7ba5760701051102o33ad8e48xf3e087ba8e64bb15@mail.gmail.com> Readers of python mailing list of all ages and systems, I'd like to introduce you program called ' Piskworky '. It is written in python, uses tkinter gui and is made for playing game known as five-in-row. Game is pure multiplayer (two-player exactly ;) and it does it's synchronization via jabber network. Well, check the website: http://piskworky.ic.cz/ From UncleAl0 at hate.spam.net Tue Jan 30 09:45:50 2007 From: UncleAl0 at hate.spam.net (Uncle Al) Date: Tue, 30 Jan 2007 06:45:50 -0800 Subject: Secret Technology of THERMATE and 911 Crime References: <1170127646.046184.213690@k78g2000cwa.googlegroups.com> Message-ID: <45BF5A1E.79964DEE@hate.spam.net> thermate at india.com wrote: [snip crap] > I do not plan to make a career out of 9/11 research, [snip more crap] > We have found evidence for thermates in the molten metal seen pouring > from the South Tower minutes before its collapse, [snip still more crap] > Thermate is the red > powder in the steel base. The prototype worked well, and the thermate- > jet cut through a piece of structural steel in a fraction of a second. Google thermite 595,000 You can't even spell it correctly. If you wish to see the light, begin by pullng your head out of your ass, http://www.mazepath.com/uncleal/sunshine.jpg Idiot. You don't know dick about incendiaries. -- Uncle Al http://www.mazepath.com/uncleal/ (Toxic URL! Unsafe for children and most mammals) http://www.mazepath.com/uncleal/lajos.htm#a2 From universal_used at hotmail.com Wed Jan 17 21:37:41 2007 From: universal_used at hotmail.com (questions?) Date: 17 Jan 2007 18:37:41 -0800 Subject: example from the book Message-ID: <1169087861.453278.58680@a75g2000cwd.googlegroups.com> I am a little confused by an example in python book: class wrapper: def __init__(self,object): self.wrapped=object def __getattr__(self,attrname): print "Trace:",attrname print getattr(self.wrapped,attrname) (*) return getattr(self.wrapped,attrname) (**) x=wrapper({"a":1, "b":2}) print x.keys() (**) (*) will output: while two (**) statements together will print the keys of the dictionary which is ['a','b'] why (*) doen't output the same result as (**)? Thanks From osantana at gmail.com Tue Jan 16 12:45:59 2007 From: osantana at gmail.com (Osvaldo Santana) Date: Tue, 16 Jan 2007 14:45:59 -0300 Subject: Python for Maemo -- new version released Message-ID: We from INdT (Nokia Institute of Technology -- Brazil) have the pleasure to announce the new version of Python for Maemo, for Maemo SDK 2.1 ("Scirocco") and SDK 3.0 ("Bora"). Highlights of this version: * Support for Nokia N800[1] device/software (SDK 3.0) * Language updated to Python 2.5 * Updated bindings * Added bindings to new Hildon widgets * Improved OSSO bindings * Project home has moved to Garage.maemo.org. The new project page is http://pymaemo.garage.maemo.org. There you can find directions about repositories, installation on SDK/device etc. The release notes for this version can be found at http://pymaemo.garage.maemo.org/pymaemo25_releasenotes.html. We encourage everybody to try the software and report bugs/improvement requests. Thanks, Osvaldo Santana Neto [1] http://europe.nokia.com/phones/n800 -- Osvaldo Santana Neto (aCiDBaSe) http://www.pythonologia.org From hg at nospam.org Tue Jan 23 01:55:45 2007 From: hg at nospam.org (hg) Date: Tue, 23 Jan 2007 07:55:45 +0100 Subject: beep or sound playing under linux References: Message-ID: Chuck Rhode wrote: > hg wrote this on Mon, Jan 22, 2007 at 04:12:50PM +0100. My reply is > below. > >> Is there a way to do that? (Make noise.) > > In Gnome there is: > > gtk.gdk.beep() > > -- > .. Chuck Rhode, Sheboygan, WI, USA > .. Weather: http://LacusVeris.com/WX > .. 28? ? Wind WSW 10 mph ? Sky overcast. well wx.Bell() I assume does the same since wxPython use gtk+ ... still I'm under gnome with system bell enabled and I do not hear anything hg From Thomas.Ploch at gmx.net Sat Jan 6 19:41:05 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 01:41:05 +0100 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <45A041A1.6020108@gmx.net> time.swift at gmail.com schrieb: > Coming from a C++ / C# background, the lack of emphasis on private data > seems weird to me. I've often found wrapping private data useful to > prevent bugs and enforce error checking.. > It appears to me (perhaps wrongly) that Python prefers to leave class > data public. What is the logic behind that choice? > > Thanks any insight. > Python doesn't prefer public data in classes. It leaves the choice to the programmer. You can define your own private instance variables (or functions) by using a '__' prefix: example: class Foo: def __init__(self, data): self.__data = data def get_data(self): return self.__data >>> f = Foo('bar') >>> f.__data Traceback (most recent call last): File "", line 1, in AttributeError: Foo instance has no attribute '__data' >>> f.get_data() 'bar' From sjmachin at lexicon.net Sat Jan 20 13:26:48 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Jan 2007 10:26:48 -0800 Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: References: Message-ID: <1169317608.819304.321210@l53g2000cwa.googlegroups.com> Michael.Coll-Barth at VerizonWireless.com wrote: [snip] > The information contained in this message and any attachment may be > proprietary, confidential, and privileged or subject to the work > product doctrine and thus protected from disclosure. If the reader > of this message is not the intended recipient, or an employee or > agent responsible for delivering this message to 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 me > immediately by replying to this message and deleting it and all > copies and backups thereof. Thank you. ... and while we're talking about annoyances ... From donn at u.washington.edu Mon Jan 22 13:24:10 2007 From: donn at u.washington.edu (Donn Cave) Date: Mon, 22 Jan 2007 10:24:10 -0800 Subject: Is any python like linux shell? References: <1169398326.510530.180860@51g2000cwl.googlegroups.com> <1169400157.075307.31340@l53g2000cwa.googlegroups.com> <1169437900.726137.237650@51g2000cwl.googlegroups.com> Message-ID: In article , James Stroud wrote: ... > Paddy wrote:' > > Frank, > > IPython is great, but it is not a replacement for a shell like bash. If > > you have a Linux system then you still need to know the rudiments of > > bash > > Or better yet, csh. ;) Careful, someone will think you're serious. From http Wed Jan 3 06:07:36 2007 From: http (Paul Rubin) Date: 03 Jan 2007 03:07:36 -0800 Subject: Synchronization methodology References: <7x64boml1l.fsf@ruckus.brouhaha.com> Message-ID: <7x1wmcmkqv.fsf@ruckus.brouhaha.com> Paul Rubin writes: > # add the user to the connected user list, with timestamp and remote IP > status = request(user_list.append, self, time(), remote_ip=whatever) Editing error, ignore the "self," arg up there. Of course there may be other mistakes too, I didn't test any of that code ;-) From timr at probo.com Thu Jan 11 02:19:22 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 11 Jan 2007 07:19:22 GMT Subject: how to clean sys.path References: Message-ID: "siggi" wrote: > >when I do >>>sys.path in IDLE (winXP), i get a horrendously long list of >paths, paths I may have used during a lot of trials and errors. How can I >clean up sys.path? I mean, trim it of unnecessary paths? What do mean by "used during a lot of trials and errors"? sys.path is recreated from scratch every time Python starts. It doesn't accumulate over time, other than from new packages that you install. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From johnpote at blueyonder.co.uk Wed Jan 31 12:13:39 2007 From: johnpote at blueyonder.co.uk (John Pote) Date: Wed, 31 Jan 2007 17:13:39 GMT Subject: where has Stani's Py Editor gone? Message-ID: <774wh.208375$MO2.74678@fe3.news.blueyonder.co.uk> Hi everyone, Been trying to get the latest version of Stani's Python Editor the last few days. But I cannot get any response out of 'pythonide.stani.be'. Anyone know what's happened? Ta much, John Pote From pavlovevidence at gmail.com Tue Jan 2 17:22:41 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 2 Jan 2007 14:22:41 -0800 Subject: array of class In-Reply-To: References: Message-ID: <1167776561.041382.60300@s34g2000cwa.googlegroups.com> mm wrote: > How can I do a array of class? > > s1=[] ## this array should hold classes > > ## class definition > class Word: > word="" > > > ## empty words... INIT > for i in range(100): ## 0..99 > s1.append(Wort) > > s1[0].word="There" > s1[1].word="should" > s1[2].word="be" > s1[3].word="different" > s1[4].word="classes" > > ... but it's not. I presume you want an list (not array) of objects (not classes). In that case, you're missing parentheses after Word. You have to call the class object, same as you'd call a function, so you have to follow it with parentheses: s1.append(Word()) You could, in fact, have an array of classes, and there are actually reasons you might want to do that, but that's pretty advanced. Carl Banks From marcpp at gmail.com Tue Jan 23 06:30:41 2007 From: marcpp at gmail.com (Marcpp) Date: 23 Jan 2007 03:30:41 -0800 Subject: I need suggests In-Reply-To: <1169551582.196591.48140@v45g2000cwv.googlegroups.com> References: <1169551582.196591.48140@v45g2000cwv.googlegroups.com> Message-ID: <1169551841.053212.160320@j27g2000cwj.googlegroups.com> Hi, I'm using SPE (Stani's Python Editor) http://projects.blender.org/projects/spe It works very good and incorporates WX support. Pat wrote: > I have to do a big programm. Could someone give me some suggests about > IDE (on Linux) and books to learn. From slowness.chen at gmail.com Wed Jan 24 04:00:18 2007 From: slowness.chen at gmail.com (Slowness Chen) Date: 24 Jan 2007 01:00:18 -0800 Subject: [OT]Could anyone send me a copy of "timeout sockets for jython" Message-ID: <1169629217.082199.242100@d71g2000cwa.googlegroups.com> The information about this module: http://www.xhaus.com/alan/python/timeout.html I can't access the download url due to the severe network issue these days, and I need to use this module for work. Could anyone do me a favor to send a copy? the download url : http://cvs.sourceforge.net/viewcvs.py/jython/jython/Lib/socket.py?rev=1.16&view=log Thanks. From jdvolz at gmail.com Thu Jan 18 11:25:03 2007 From: jdvolz at gmail.com (jdvolz at gmail.com) Date: 18 Jan 2007 08:25:03 -0800 Subject: urllib2 and transfer-encoding = chunked References: <1169108468.497013.228520@l53g2000cwa.googlegroups.com> Message-ID: <1169137502.990783.222150@51g2000cwl.googlegroups.com> Haha! My mistake. The error is that when a web server is chunking a web page only the first chunk appears to be acquired by the urllib2.urlopen call. If you check the headers, there is no 'Content-length' (as expected) and instead there is 'transfer-encoding' = 'chunked'. I am getting about the first 30Kb, and then nothing else. I don't get a ValueError like described at the following post: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e3f87a65c4c7e875/8a3ea9ca84b28669?lnk=gst&q=chunked&rnum=1#8a3ea9ca84b28669 Here's the code that I think is failing, it's basically textbook Python for accessing a url: file = urllib2.urlopen(url) contenttype = file.info().type if contenttype and contenttype.find('text') > -1: return file.read() # # I am checking the content type because I don't want to download .jpegs and the like # I have typed similar commands into the interpreter, which also produces only about the first 30KB of the url. Sorry for the confusion. Gabriel Genellina wrote: > escribi? en el mensaje > news:1169108468.497013.228520 at l53g2000cwa.googlegroups.com... > >I am having errors which appear to be linked to a previous bug in > > urllib2 (and urllib) for v2.4 and v2.5 of Python. Has this been fixed? > > Has anyone established a standard workaround? I keep finding old > > posts about it, that basically give up and say "well it's a known bug." > > Any help would be greatly appreciated. > > Perhaps if you said what the supposed error is... > > -- > Gabriel Genellina From duncan.booth at invalid.invalid Sat Jan 13 11:22:24 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Jan 2007 16:22:24 GMT Subject: Boilerplate in rich comparison methods References: <1168674664.792869.213260@m58g2000cwm.googlegroups.com> <45a90301$0$7677$4c368faf@roadrunner.com> Message-ID: "Paul McGuire" wrote: > In Python, this would look like: > > class Parrot: > def __eq__(self, other): > return self is other or self.plumage() == other.plumage() > def __ne__(self, other): > return self is not other and self.plumage() != other.plumage() > def __lt__(self, other): > return self is not other and self.plumage() < other.plumage() > def __gt__(self, other): > return self is not other and self.plumage() > other.plumage() > def __le__(self, other): > return self is not other and self.plumage() <= other.plumage() > def __ge__(self, other): > return self is not other and self.plumage() >= other.plumage() > > and George's metaclass would have similar changes. > > On the other hand, I haven't seen this idiom in any Python code that > I've read, and I wonder if this was just a coding fad of the time. It is a perfectly reasonable short-cut for those types where you know an object is equal to itself, but that isn't always the case. e.g. floating point NaN values are not equal to themselves, and a list of numbers might contain a NaN which would mean the list wouldn't be equal to itself. Also note that for the __le__, __ge__ cases you got the shortcut test the wrong way round. From bj_666 at gmx.net Mon Jan 22 03:23:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 22 Jan 2007 09:23:02 +0100 Subject: instancemethod References: Message-ID: In , Gert Cuykens wrote: >> > > gert.excecute('select * from person') >> > > for x in range(0,gert.rowcount): >> > > print gert.fetchone() >> > > gert.close() >> > > > [?] > > python always seems to amaze me how other languages make a mess of > things that suppose to be simple It gets even simpler: cursor objects are iterable after the `execute()` call. So you don't need the number of rows:: gert.excecute('select * from person') for row in gert: print row gert.close() Ciao, Marc 'BlackJack' Rintsch From tim.one at comcast.net Fri Jan 26 01:33:56 2007 From: tim.one at comcast.net (Tim Peters) Date: Fri, 26 Jan 2007 00:33:56 -0600 Subject: doctest problem with null byte References: Message-ID: [Stuart D. Gathman] > I am trying to create a doctest test case for the following: > > def quote_value(s): > """Quote the value for a key-value pair in Received-SPF header > field if needed. No quoting needed for a dot-atom value. > > >>> quote_value(r'abc\def') > '"abc\\\\\\\\def"' > >>> quote_value('abc..def') > '"abc..def"' > >>> quote_value('') > '""' > >>> quote_value('-all\x00') > '"-all\\\\\\\\x00"' > ... > > However, doctest does *not* like the null byte in the example (yes, > this happens with real life input): > ********************************************************************** > File "/home/stuart/pyspf/spf.py", line 1453, in spf.quote_value > Failed example: > quote_value('-all') > Exception raised: > Traceback (most recent call last): > File > "/var/tmp/python2.4-2.4.4c1-root/usr/lib/python2.4/doctest.py", > line 1248, in __run > compileflags, 1) in test.globs > TypeError: compile() expected string without null bytes > ********************************************************************** > > How can I construct a test cast for this? As the docs say, doctest examples are parsed /twice/: once when Python compiles the module and creates string objects, and again when doctest extracts and passes example substrings to the compile() function (which you can see in your traceback). The first time, the \x00 in the quote_value('-all\x00') portion of your docstring got changed into an honest-to-goodness NUL byte. Passing that to compile() can't work. To alleviate that, and the "leaning toothpick syndrome" in your other examples, a simple approach is to make your docstring a raw string (stick the letter 'r' in front of the opening triple-quote). For example, this works fine: def f(): r""" >>> len("\\") 1 >>> ord("\x00") 0 """ Because it's a raw string, Python does /not/ change the \x00 portion into a NUL byte when it compile the module. Instead the docstring continues to contain the 4-character substring: \x00 and that's what compile() needs to see. To perform the same test without using a raw string requires slamming in more backslashes (or other ad-hoc escaping tricks): def g(): """ >>> len("\\\\") 1 >>> ord("\\x00") 0 """ From liam_jones at yahoo.com Wed Jan 10 10:22:59 2007 From: liam_jones at yahoo.com (liam_jones at yahoo.com) Date: 10 Jan 2007 07:22:59 -0800 Subject: Using Excel With Python Message-ID: <1168442579.066246.16650@k58g2000hse.googlegroups.com> I'm very new to Python, well IronPython to precise, and have been having problems when using Excel. The problem I'm having is the closing of my Excel object. I'm able to successfully quit the Excel Application that I create, but when I open a Workbook in the Application I can't successfully Quit Excel (by this I mean I can quit it, but the Excel process isn't getting killed and I have to manually go this through Task Manager). I've given a sample of code below to hopefully make things clearer. I've then given all of the information I think might be useful (sorry if I've gone over the top!). import System import clr from System.Data import * from System.Web import * from System.Web.UI import * from clr import * clr.AddReference("Microsoft.Office.Interop.Word") clr.AddReference("Microsoft.Office.Interop.Excel") clr.AddReference("Microsoft.Office.Interop.PowerPoint") clr.AddReference("Office") from Microsoft.Office.Interop.Word import ApplicationClass as WordApplication from Microsoft.Office.Interop.Excel import ApplicationClass as ExcelApplication from Microsoft.Office.Interop.PowerPoint import ApplicationClass as PowerPointApplication from Microsoft.Office.Interop.Word import WdReplace from Microsoft.Office.Interop.Excel import XlCellType from Microsoft.Office.Interop.Excel import XlSearchDirection from System.Type import Missing from System import GC missing = Missing FileLocation = "C:\\test.xls" ExcelApp = ExcelApplication() workbook= None workbook = ExcelApp.Workbooks.Open(FileLocation, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing) workbook.Save() workbook.Close(SaveChanges=0) ExcelApp.Quit() workbook = None ExcelApp = None GC.Collect() GC.WaitForPendingFinalizers() I've simpilised the code by taking all of my Workbook processing from it and the problem is still occurring. As I said above if I don't create the workbook, then ExcelApp closes as expected (there are no stray processes). I've read many articles and postings over the last few days regarding this, but have had no luck with anything I've seen, examples of this are now given. I've tried adding the below code, but with no luck. ExcelApp.ActiveWorkbook.Save() ExcelApp.ActiveWorkbook.Close(SaveChanges=0) ExcelApp.Workbooks.Close() I've also tried the below (again with no luck). System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook) System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp) And, I've also tried the following (again with no luck!). del(workbook) del(excelApp) It may seem strange using the Garbage Collector (well I wouldn't have thought about using it here), but it was something that I read about using for code written in C#. I've tried the code in C# (what I normally write in) and all works fine, the only real difference is that I'm setting the objects to NULL in C# and None here in IronPython - Does this make a difference, is there something else I should be setting it to? The Workbook object HAS to be set to NULL in C#, it's then picked up by the Garbage Collector and the task disappears from the Task Manager. I did think of killing the actual EXCEL.EXE process at the end of my code, but there might be several versions of the containing application running on the same box, so I can't kill all of the Excel processes. As I said above, I'm sorry if I've gone over the top in my description. Any ideas or pointers would be greatly appreciated as I'm now going round in circles. Thanks in advance. Rgds Liam From nagle at animats.com Wed Jan 31 02:30:40 2007 From: nagle at animats.com (John Nagle) Date: Wed, 31 Jan 2007 07:30:40 GMT Subject: how to "free" an object/var ? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Tue, 30 Jan 2007 15:48:37 -0800, James Stroud wrote: > > >>Stef Mientki wrote: >> >>>If I create a large array of data or class, >>>how do I destroy it (when not needed anymore) ? If your data structure has no backlinks, it will go away as soon as the last reference to it disappears. If your data structure has backlinks, it will hang around until garbage collection runs. If your backlinks are weak references (see "weakref"), the data structure will be released much sooner. If you generate structures with backlinks, like parse trees, use weak references for all links that point backwards toward the root, and you'll use less memory. In Python, garbage collection is mostly a backup to the reference counting system. If your app really needs periodic GC to run, you're leaking memory. On servers, this sometimes matters. John Nagle From elrondrules at gmail.com Tue Jan 30 15:34:38 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 30 Jan 2007 12:34:38 -0800 Subject: Convert raw data to XML In-Reply-To: References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> <1170184059.739808.244660@s48g2000cws.googlegroups.com> Message-ID: <1170189278.490020.52670@h3g2000cwc.googlegroups.com> On Jan 30, 12:05 pm, John Nagle wrote: > elrondru... at gmail.com wrote: > > On Jan 29, 8:54 pm, "Gabriel Genellina" wrote: > > >>En Mon, 29 Jan 2007 23:42:07 -0300, escribi?: > > the reason I wanted to write it as a file was to parse the file, look > > for a specific attribute and execute a set of commands based on the > > value of the attribute.. also i needed to display the output of the > > http post in a more readable format.. > > That's straightforward. You confused people by asking the > wrong question. You wrote "Convert raw data to XML", but what > you want to do is parse XML and extract data from it. > > This will do what you want: > > http://www.crummy.com/software/BeautifulSoup/ > > For starters, try > > from BeautifulSoup import BeautifulStoneSoup > xmlstring = somexml ## get your XML into here as one big string > soup = BeautifulStoneSoup(xmlstring) # parse XML into tree > print soup.prettify() # print out in indented format > > "soup" is a tree structure representing the XML, and there are > functions to easily find items in the tree by tag name, attribute, > and such. Work on the tree, not a file with the text of the indented > output. > > John Nagle is there any other way to do this without using BeautifulStoneSoup.. using existing minidom or ext.. i dont want to install anything new From ptmcg at austin.rr.com Fri Jan 26 12:53:04 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Jan 2007 09:53:04 -0800 Subject: how to remove c++ comments from a cpp file? In-Reply-To: <1169805244.879280.235660@v45g2000cwv.googlegroups.com> References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> <1169805244.879280.235660@v45g2000cwv.googlegroups.com> Message-ID: <1169833984.384055.51180@j27g2000cwj.googlegroups.com> On Jan 26, 3:54 am, "Frank Potter" wrote: > > I'm very sorry because I was in a hurry when I post this thread. > I'll post again my code here: > [CODE] > import re > > f=open("show_btchina.user.js","r").read() > f=unicode(f,"utf8") > > r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) > f_new=r.sub(ur"",f) > > open("modified.js","w").write(f_new.encode("utf8")) > [/CODE] > Here's a pyparsing version that will stay clear of '//' inside quoted strings. (untested) -- Paul from pyparsing import javaStyleComment, dblQuotedString f=open("show_btchina.user.js","r").read() f=unicode(f,"utf8") commentFilter = Suppress( javaStyleComment ).ignore( dblQuotedString ) f_new= commentFilter.transformString(f) open("modified.js","w").write(f_new.encode("utf8")) From bluejump at mac.com Sat Jan 13 17:49:25 2007 From: bluejump at mac.com (Kajsa Anka) Date: Sat, 13 Jan 2007 23:49:25 +0100 Subject: HTML Calendar code References: <0001HW.C1CED6FB000CC50DF0407648@News.Individual.DE> <1168714324.437746.272060@l53g2000cwa.googlegroups.com> Message-ID: <0001HW.C1CF2085001E0175F0182648@News.Individual.DE> Thanks From tleeuwenburg at gmail.com Thu Jan 11 00:22:29 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 10 Jan 2007 21:22:29 -0800 Subject: The Python Papers: Submit your Quotes Message-ID: <1168492949.830615.131350@o58g2000hsb.googlegroups.com> Volume Two of The Python Papers is on its way, and it would be great to get some more words from the community in there. Submit your own quotes to submissions at pythonpapers.org to get a brief comment included in our next publication. Please include any attribution information you wish... Let's get the ball rolling: "Python? I switched and never looked back." -- Tennessee Leeuwenburg Submissions taken until Jan 23rd, so get 'em in fast! Cheers, -T (Editor-In-Chief) Posted by Tennessee Leeuwenburg on 2007/01/11 From gagsl-py at yahoo.com.ar Tue Jan 16 21:33:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 23:33:17 -0300 Subject: Making a simple script standalone In-Reply-To: <5d1084-5j7.ln1@whisper.very.softly> References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: <7.0.1.0.0.20070116233111.04676d00@yahoo.com.ar> At Tuesday 16/1/2007 19:49, Rikishi 42 wrote: >What I want to do is to compile/bundle/prepare/whatever_term a simple >Python script for deployment on a Windows machine. Installing Python >itself on that machine, is not an option. Ideally I would like to obtain >a single executable file, but a script+runtime is acceptable. distutils + py2exe -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rw at smsnet.pl Fri Jan 12 17:35:03 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 12 Jan 2007 23:35:03 +0100 Subject: How to respond to a confirmation prompt automatically References: <1168632324.226733.130870@a75g2000cwd.googlegroups.com> Message-ID: <87d55j50x4.fsf@smsnet.pl> "Coby" writes: > Just to give you some background about my problem: > > I execute os.system(command), where command is a string. > > On the command line in windows, I get: > > "Continue, and unload these objects? [no]" > > I need to respond 'y' to continue, but I am uncertain on how to output > the 'y' automatically. You need to use pipe. 1. p = os.popen(command, "w") p.write("y\n") http://docs.python.org/lib/os-newstreams.html#os-newstreams 2. from subprocess import Popen, PIPE p = Popen(command, shell=True, stdin=PIPE) p.stdin.write("y\n") http://docs.python.org/lib/module-subprocess.html -- HTH, Rob From casevh at comcast.net Thu Jan 4 10:57:42 2007 From: casevh at comcast.net (casevh at comcast.net) Date: 4 Jan 2007 07:57:42 -0800 Subject: code optimization (calc PI) / New Algorithme for PI In-Reply-To: References: Message-ID: <1167926262.512546.209130@s80g2000cwa.googlegroups.com> > Yes, this "gmpy" sounds good for calc things like that. > But not available on my machine. > ImportError: No module named gmpy What type of machine? The home page for gmpy is http://sourceforge.net/projects/gmpy/ I have Windows versions available at http://home.comcast.net/~casevh/ casevh From george.sakkis at gmail.com Sun Jan 21 12:22:37 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Jan 2007 09:22:37 -0800 Subject: Is any python like linux shell? References: <1169398326.510530.180860@51g2000cwl.googlegroups.com> Message-ID: <1169400157.075307.31340@l53g2000cwa.googlegroups.com> Frank Potter wrote: > I learned some python in windows. > And now I've turned to linux. > I read a book and it teaches how to write shell script with bash, > but I don't feel like the grammar of bash. > Since I know about python, > I want to get a linux shell which use python grammar. > I searched by google and I found pysh, which is not maintained any > more. > There's another script named pyshell, which is not likely what I'm > searching for. > So, will somebody please tell me if there are any python like shells > for linux? IPython is actually more than a simple shell. Give it a try: http://ipython.scipy.org/. George From rds1226 at sh163.net Tue Jan 16 13:51:30 2007 From: rds1226 at sh163.net (Dongsheng Ruan) Date: Tue, 16 Jan 2007 13:51:30 -0500 Subject: How can I create a linked list in Python? Message-ID: with a cell class like this: #!/usr/bin/python import sys class Cell: def __init__( self, data, next=None ): self.data = data self.next = next def __str__( self ): return str( self.data ) def echo( self ): print self.__str__() From paul at boddie.org.uk Thu Jan 11 10:11:23 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Jan 2007 07:11:23 -0800 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> <9ihph.72$fo1.64@newsfe03.lga> <1168518426.111465.290430@o58g2000hsb.googlegroups.com> Message-ID: <1168528282.862978.24730@i39g2000hsf.googlegroups.com> Sean Davis wrote: > > As for the specifics, Oracle data is going to be coming in as a DB-API > 2 cursor in manageable chunks (and at a relatively slow pace). On the > postgres loading side, I wanted to use the pscycopg2 copy_from > function, which expects an open file-like object (that has read and > readline functionality) and is quite fast for loading data. And which seems to use the COPY FROM command in PostgreSQL... > Note the disconnect here--Oracle is coming in in discrete chunks, while > postgresql is looking for a file object. I solved this problem by > creating a temporary file as an intermediary, but why wait for Oracle > to finish dumping data when I can potentially be loading into postgres > at the same time that the data is coming in? My experience along with the PostgreSQL documentation tells me that you shouldn't worry about this problem too much: using COPY FROM is *far* faster than performing many inserts or updates. The only thing you'd need to worry about is data being copied into the database that duplicates existing data, causing constraint violations, but since you're already using this method I imagine that this is not a likely problem. Paul From half.italian at gmail.com Tue Jan 30 06:27:16 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 30 Jan 2007 03:27:16 -0800 Subject: Mounting shares with python In-Reply-To: <51uvh7F1m9svaU1@mid.individual.net> References: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> <51uvh7F1m9svaU1@mid.individual.net> Message-ID: <1170156435.994259.233610@h3g2000cwc.googlegroups.com> On Jan 26, 10:27 am, Bjoern Schliessmann wrote: > Marcpp wrote: > > Hi, when i mount a share with python... > > > os.system ("mount -t smbfs -o username=nobody ...") > > > the problem is that I'll to be root. > > Consider modifying /etc/fstab. > > > Have a comand to send a root password...? > > I've tried > > > os.system ("su") > > os.system ("the password") > > > but it doesn't works. > > Be advised that storing a root password as clear text can be a huge > security risk. Use sudo. > > Regards, > > Bj?rn > > -- > BOFH excuse #9: > > doppler effect I use pexpect. http://pexpect.sourceforge.net/ ~Sean From david at boddie.org.uk Wed Jan 24 08:21:31 2007 From: david at boddie.org.uk (David Boddie) Date: 24 Jan 2007 05:21:31 -0800 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: Message-ID: <1169644891.275035.110760@v33g2000cwv.googlegroups.com> On Jan 24, 12:09 am, "Daniel" wrote: > I've downloaded both the wxPython and the PyQt4 package, and by the > first impression I must say that the PyQt4 system had a very > compelling presentation. From what I can understand from the feedback > I've gotten so far is that the wxPython is a better choice when it > comes to compability (with linux), and it's free even if I want to > create applications and sell them. Can you explain why you think wxPython is a better choice with respect to "compatibility (with linux)"? > So, from what I understand I will have to go with PyQt4 since (from > my understanding): > 1. I will not sell the applications I'm working with since they will > only be used by the internal QA at a computer game company. > 2. There seems to be a lot of documentation available for PyQt4. > 3. PyQt4 seems to be easier to learn. > 4. My programs does not need to support Linux or Unix. Qt is a cross-platform framework, so you would get support for X11-based platforms, anyway. David From bj_666 at gmx.net Mon Jan 29 01:55:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 29 Jan 2007 07:55:18 +0100 Subject: import from future References: <1169969100.946843.111770@p10g2000cwp.googlegroups.com> <1170049392.204148.54430@a34g2000cwb.googlegroups.com> Message-ID: In <1170049392.204148.54430 at a34g2000cwb.googlegroups.com>, Dan Bishop wrote: > Now that nested_scopes and generators are no longer optional, the only > thing left is "from __future__ import division", which makes the "/" > operator on integers give the same result as for floats. >From 2.5 on we have `with_statement`:: >>> __future__.with_statement _Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), 32768) Ciao, Marc 'BlackJack' Rintsch From tiedon_jano at hotmail.com Sun Jan 7 16:42:06 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 07 Jan 2007 21:42:06 GMT Subject: how to find the longst element list of lists In-Reply-To: References: Message-ID: Michael M. kirjoitti: > How to find the longst element list of lists? > > I think, there should be an easier way then this: > > s1 = ["q", "e", "d"] > s2 = ["a", "b"] > s3 = ["a", "b", "c", "d"] > > > > After, the list ist sorted: > > sx1 = ["a", "b", "c", "d"] > sx2 = ["q", "e", "d"] > sx3 = ["a", "b"] > s1 = ["q", "e", "d"] s2 = ["a", "b"] s3 = ["a", "b", "c", "d"] ss = ((len(s1), s1), (len(s2), s2), (len(s3), s3)) sx = [y for (x, y) in sorted(ss)[::-1]] print sx sx1, sx2, sx3 = sx print sx1, sx2, sx3 Cheers, Jussi From ricli576 at student.liu.se Thu Jan 18 19:23:43 2007 From: ricli576 at student.liu.se (Rickard Lindberg) Date: 18 Jan 2007 16:23:43 -0800 Subject: Match 2 words in a line of file References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> Message-ID: <1169166223.073714.109620@51g2000cwl.googlegroups.com> elrondrules at gmail.com wrote: > Hi > > Am pretty new to python and hence this question.. > > I have file with an output of a process. I need to search this file one > line at a time and my pattern is that I am looking for the lines that > has the word 'event' and the word 'new'. > > Note that i need lines that has both the words only and not either one > of them.. > > how do i write a regexp for this.. or better yet shd i even be using > regexp or is there a better way to do this.... > > thanks Maybe something like this would do: import re def lines_with_words(file, word1, word2): """Print all lines in file that have both words in it.""" for line in file: if re.search(r"\b" + word1 + r"\b", line) and \ re.search(r"\b" + word2 + r"\b", line): print line Just call the function with a file object and two strings that represent the words that you want to find in each line. To match a word in regex you write "\bWORD\b". I don't know if there is a better way of doing this, but I believe that this should at least work. From ed at leafe.com Mon Jan 8 12:59:14 2007 From: ed at leafe.com (Ed Leafe) Date: Mon, 8 Jan 2007 12:59:14 -0500 Subject: A Good Intro to wxpython/PostgreSQL Applications? In-Reply-To: <1168276952.498242.78120@v33g2000cwv.googlegroups.com> References: <1168276952.498242.78120@v33g2000cwv.googlegroups.com> Message-ID: <90CCE71C-F814-449B-B3E5-D67D69E8C8D3@leafe.com> On Jan 8, 2007, at 12:22 PM, PAllen wrote: > I am trying to get rid of a few of my old MS Access applications and > move them to PostgreSQL and Python/wxpython. Does anyone have any > suggestions on the easiest way to learn to program small database > applications with python & wxpython? Does anyone have a few small > examples at least? > > I will mainly need forms with/without subforms for viewing and > inserting data into the database. Nothing too complicated to get > started. Dabo is designed to do exactly what you describe. It is a desktop application framework with an emphasis on database apps. Both myself and the other Dabo author, Paul McNett, come from MS Visual FoxPro backgrounds, so we know what people expect in a GUI app tool. Be sure to check out our screencasts, which show you what is involved in creating database applications in Dabo. The screencasts are listed at the top of http://dabodev.com/documentation. We support several backend databases, and PostgreSQL is one of them. We use wxPython as our UI toolkit, but wrap the controls so that they have a consistent, property-based API instead of the C++ style of getter/setter methods with odd names. I will be the first to admit that the how-to documentation is far from complete, but there is a good amount of information on the Wiki (http://dabodev.com/wiki). And we have our own mailing list that is frequented by both the authors and several other helpful folks. You can sign up for the dabo-users list at http://leafe.com/mailman/ listinfo/dabo-users. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From bjourne at gmail.com Thu Jan 25 04:14:10 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 25 Jan 2007 10:14:10 +0100 Subject: Getting to an SSH account over a HTTP proxy In-Reply-To: <1169514995.916358.17030@11g2000cwr.googlegroups.com> References: <1169514995.916358.17030@11g2000cwr.googlegroups.com> Message-ID: <740c3aec0701250114k7c76adcex486f711e034b829a@mail.gmail.com> On 22 Jan 2007 17:16:35 -0800, Nanjundi wrote: > BJ?rn Lindqvist wrote: > > I want to use Python to connect to a SSH account over a HTTP proxy to > > automate some operations. I thought paramiko would be able to do that, > > but it can not (it seems). > > > > Is there some other Python module that can do what I want? > > > > -- > > mvh Bj?rn > > Did you take a look at twisted library? > twistedmatrix.com > http://twistedmatrix.com/projects/core/documentation/howto/clients.html > > > I haven't tried to connect over port 80, but its worth a try. I looked at Twisted, but I did not understand how it could solve my problem. I do not want to create my own SSH client and, AFAICT, there is no SSH client in Twisted. The library also seem to have some problems with handling HTTP proxies in a transparent way: http://twistedmatrix.com/trac/ticket/1774 -- mvh Bj?rn From andre.roberge at gmail.com Sat Jan 27 16:19:26 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 27 Jan 2007 13:19:26 -0800 Subject: Crunchy 0.8 release Message-ID: <1169932766.450129.259840@k78g2000cwa.googlegroups.com> Version 0.8 of Crunchy has been released. It is available on http://code.google.com/p/crunchy/ Crunchy, the Interactive Python Tutorial Maker, is an application that transforms an ordinary html-based Python tutorial into an interactive session within a web browser. Currently, only Firefox is supported. Crunchy is developed and tested on Windows XP and Ubuntu Dapper Drake, but should work on any suitable windows or UNIX system. Three major improvements have been made since version 0.7 had been released. 1. New editor Instead of a simple html textarea, Crunchy now gives the option of using a "real" editor, namely EditArea (http://www.cdolivet.net/editarea/). EditArea support syntax coloring and allows loading and saving local Python files among other features. Within Crunchy, it is set up so that the tab key is translated into 4 spaces. 2. Language support Crunchy now supports English and French, through the use of ".po" files. When running Python code, some error messages have been adapted/translated. EditArea itself support more languages (currently: Danish, Dutch, English, French, German, Italian, Japanese, Polish, Portuguese). 3. Graphical tutorial converter. Crunchy uses some supplementary markup to transform html files into interactive tutorials. Whereas previous versions required a tutorial maker to edit an html file "by hand", version 0.8 includes a tutorial editor: with a few clicks, you can easily add to an html file the chosen interactive elements and options for Crunchy. In addition to the above major improvements, the code has been refactored significantly and a number of small bug fixes have been made. Crunchy will be demonstrated at the upcoming Pycon 2007. Andr? Roberge and Johannes Woolard. From marcpp at gmail.com Tue Jan 23 05:43:49 2007 From: marcpp at gmail.com (Marcpp) Date: 23 Jan 2007 02:43:49 -0800 Subject: Working with shared folders Message-ID: <1169549029.039191.87240@s48g2000cws.googlegroups.com> Any idea to work with windows shared folders? Which library is needed to execute console comands? Thankyou. From borntonetwork at gmail.com Wed Jan 17 21:04:19 2007 From: borntonetwork at gmail.com (borntonetwork) Date: 17 Jan 2007 18:04:19 -0800 Subject: The proper use of QSignalMapper In-Reply-To: <1169049100.393777.269350@v45g2000cwv.googlegroups.com> References: <1169045073.138626.60770@l53g2000cwa.googlegroups.com> <1169049100.393777.269350@v45g2000cwv.googlegroups.com> Message-ID: <1169085859.586698.149400@51g2000cwl.googlegroups.com> Thanks, David, for you help. When I change the slot function to what you show in your second example, I get the same results: nothing. When I change it to what you have in your first example, I get the following: Object::connect: No such slot QApplication::map() Object::connect: (sender name: 'chkProductIngredientsDelete_1') Object::connect: (receiver name: 'main.py') Object::connect: No such slot QApplication::map() Object::connect: (sender name: 'chkProductIngredientsDelete_2') Object::connect: (receiver name: 'main.py') Object::connect: No such slot QApplication::map() Object::connect: (sender name: 'chkProductIngredientsDelete_3') Object::connect: (receiver name: 'main.py') Object::connect: No such slot QApplication::map() Object::connect: (sender name: 'chkProductIngredientsDelete_4') Object::connect: (receiver name: 'main.py') Object::connect: No such slot QApplication::map() Object::connect: (sender name: 'chkProductIngredientsDelete_5') Object::connect: (receiver name: 'main.py') Object::connect: No such slot QApplication::map() Object::connect: (sender name: 'chkProductIngredientsDelete_6') Object::connect: (receiver name: 'main.py') David Boddie wrote: > borntonetwork wrote: > > > I am trying to implement QTCore.QSignalMapper using PyQT. I finally got > > to a point where I don't receive any compile or runtime error messages, > > but I also do not see the final slot function fire off. Here is a > > snippet of the code: > > > > self.signalMapper = QtCore.QSignalMapper(window) > > # Use qsignalmapper to use of one slot function for multiple > > # widgets. The map() function sends the slot an extra param > > # that identifies the sender. > > for idx in range(1, maxIngredients+1): > > wName = 'chkProductIngredientsDelete_'+str(idx) > > w = self.__dict__[wName] > > self.app.connect(w, QtCore.SIGNAL("stateChanged(int)"), > > self.signalMapper, > > QtCore.SLOT("self.signalMapper.map")) > > You need to pass the C++ signature to the SLOT() function. I believe > you want the form that does not accept any arguments: > > self.app.connect(w, QtCore.SIGNAL("stateChanged(int)"), > self.signalMapper, > QtCore.SLOT("map()")) > > Alternatively, you can pass the slot directly to the function: > > self.app.connect(w, QtCore.SIGNAL("stateChanged(int)"), > self.signalMapper.map) > > PyQt accepts Python methods as slots, without requiring that they be > wrapped in calls to SLOT(). > > David From nszabolcs at gmail.com Tue Jan 30 08:44:40 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 30 Jan 2007 05:44:40 -0800 Subject: How can I know both the Key c and Ctrl on the keyboard are pressed? In-Reply-To: <1170147029.261981.322740@a75g2000cwd.googlegroups.com> References: <1170147029.261981.322740@a75g2000cwd.googlegroups.com> Message-ID: <1170164680.123191.206630@p10g2000cwp.googlegroups.com> tidegenerator at tom.com wrote: > Hi; > How can I know the Key c and Ctrl on the keyboard are pressed? Or how > to let the program press the > > key Ctrl+c automatically? I just want to use python to develop a > script program. > gear depends on where you got your input from and what do you exactly want eg: in a gui app you get input events from the gui toolkit (wx, gtk, sdl/ pygame...) in a console app if you use curses lib then you can use getch() oslt if you want a general solution to get input key events in a simple script then you cannot do that. however Ctrl+C is a special key combination: running python in a unix terminal it raises KeyboardInterrupt exception, imho in a windows cmd promt it raises SystemExit so you can emulate those by using: raise KeyboardInterrupt or raise SystemExit hope this helps From zhouchengly at gmail.com Tue Jan 16 04:21:52 2007 From: zhouchengly at gmail.com (shellon) Date: 16 Jan 2007 01:21:52 -0800 Subject: How to convert float to sortable integer in Python Message-ID: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> Hi all: I want to convert the float number to sortable integer, like the function float2rawInt() in java, but I don't know the internal expression of float, appreciate your help! From robert.kern at gmail.com Tue Jan 9 04:00:20 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 03:00:20 -0600 Subject: Module to read svg In-Reply-To: References: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> <45a1f746$0$27874$9b622d9e@news.freenet.de> Message-ID: Tim Roberts wrote: > Robert Kern wrote: > >> Martin v. L?wis wrote: >>> schpok at gmail.com schrieb: >>>> Does anyone know if there's an actual free implementation of this? >>> For the dom module in it, xml.dom.minidom should work. Depending on >>> your processing needs, that might be sufficient. >> I don't think it quite fits what the OP is asking for. SVG defines some non-XML >> structure for some of its contents. For example: >> >> > > Why is that non-XML? Oh, it's valid XML, certainly. However, the data inside the attribute is not just a bunch of arbitrary characters; it needs to be parsed with a non-XML parser to get the actual list of points. And unfortunately, "for space-efficiency" the grammar that describes that data is full of tricks and shortcuts to save a few characters here and there (actually, I think point lists are fine; path definitions, though are nuts). See the SVG spec for the full EBNF grammar. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From smusnmrNOSPAM at yahoo.com Fri Jan 5 04:58:56 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Fri, 5 Jan 2007 10:58:56 +0100 Subject: where to find wx package Message-ID: Hi all, a newbie question: I have a program gui03A.py using wxPython, importing it such: "from wxPython.wx import *" The program works, but I get the warning message: "gui03A.py:4: DeprecationWarning: The wxPython compatibility package is no longer automatically generated or activly maintained. Please switch to the wx package as soon as possible." However, after extensive searching on www.python.org and Googling the web, I do not find any package with "wx" as its only name. Where can I get the wx package (for win32 XP)? Thanks, Siggi From gnewsg at gmail.com Tue Jan 9 05:08:18 2007 From: gnewsg at gmail.com (billie) Date: 9 Jan 2007 02:08:18 -0800 Subject: General Question About Python In-Reply-To: <1168336603.962731.5470@11g2000cwr.googlegroups.com> References: <1168254451.098796.144790@42g2000cwt.googlegroups.com> <1168336603.962731.5470@11g2000cwr.googlegroups.com> Message-ID: <1168337298.574881.121470@i15g2000cwa.googlegroups.com> Torabisu wrote: > Its quite weird, we're looking for Python skills but are battling to > find at the moment... Normally Python on its own will probably not > land you a job, but the last two companies I've worked for are doing > indepth Python development, so hopefully the tables are turning a bit. I can tell the same for Italy. Where are you from? From jstroud at mbi.ucla.edu Sat Jan 27 00:50:33 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 26 Jan 2007 21:50:33 -0800 Subject: strip question In-Reply-To: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> References: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > hi > can someone explain strip() for these : > [code] > >>>>x='www.example.com' >>>>x.strip('cmowz.') > > 'example' > [/code] > > when i did this: > [code] > >>>>x = 'abcd,words.words' >>>>x.strip(',.') > > 'abcd,words.words' > [/code] > > it does not strip off "," and "." .Why is this so? > thanks > strip strips from the ends. py> x = '...,.,abcd,words.words,,,,.,.,.,.,' py> x.strip(',.') 'abcd,words.words' James From steve at REMOVEME.cybersource.com.au Sun Jan 14 23:00:14 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 15 Jan 2007 15:00:14 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: On Mon, 15 Jan 2007 14:43:55 +1100, Steven D'Aprano wrote: >> Of course, none of this really has anything to do with rational >> numbers. There must be many examples of classes for which internal >> calls to __init__, from other methods of the same class, require >> minimal argument processing, while external calls require heavier and >> possibly computationally expensive processing. What's the usual way >> to solve this sort of problem? > > class Rational(object): > def __init__(self, numerator, denominator): > print "lots of heavy processing here..." > # processing ints, floats, strings, special case arguments, > # blah blah blah... > self.numerator = numerator > self.denominator = denominator > def __copy__(self): > cls = self.__class__ > obj = cls.__new__(cls) > obj.numerator = self.numerator > obj.denominator = self.denominator > return obj > def __neg__(self): > obj = self.__copy__() > obj.numerator *= -1 > return obj Here's a variation on that which is perhaps better suited for objects with lots of attributes: def __copy__(self): cls = self.__class__ obj = cls.__new__(cls) obj.__dict__.update(self.__dict__) # copy everything quickly return obj -- Steven D'Aprano From Thomas.Ploch at gmx.net Tue Jan 9 19:51:58 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Wed, 10 Jan 2007 01:51:58 +0100 Subject: Question: Best Practice? (module 'shelve') Message-ID: <45A438AE.10105@gmx.net> Hello fellows, I just wanted to know, if there is any best practice concerning following code: import re, shelve class TextMatcher: def __init__(self, patterns, email=False, dbName='textmatch.db'): self._initPatterns(patterns) self.email = email self.dbName = dbName if self.email: self.emailList = [] self.emailList.append( re.compile(r'[a-zA-Z0-9_.]+@\w+\.\w+')) def match(self, src, url): self.matchDict = {} self.matchDict[url] = {} # The next 2 functions just add stuff to self.matchDict if self.email: self._addEmails(src, url) self._addPatterns(src, url) # Is it good practice to open, write and close the db straight # away? Or is it better to leave it open until the whole program # has finished, and close it then? self.openDB(self.dbName) self.db[url] = self.matchDict[url] self.db.close() # I want to del the matchDict each time so it can't grow big. # Is this good, or should it be left open, too? del self.matchDict def openDB(self, dbName=None, modeflag='c'): if dbName == None: self.db = shelve.open('textmatch.db', flag=modeflag) else: self.db = shelve.open(dbName, flag=modeflag) From arkanes at gmail.com Thu Jan 11 13:19:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 11 Jan 2007 12:19:54 -0600 Subject: Read from database, write to another database, simultaneously In-Reply-To: <33vph.8825$pQ3.2190@newsread4.news.pas.earthlink.net> References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> <1168519760.894380.303990@i39g2000hsf.googlegroups.com> <33vph.8825$pQ3.2190@newsread4.news.pas.earthlink.net> Message-ID: <4866bea60701111019w7d0cd807pdba35f3e2de92604@mail.gmail.com> On 1/11/07, Dennis Lee Bieber wrote: > On 11 Jan 2007 04:49:21 -0800, "Sean Davis" > declaimed the following in comp.lang.python: > > > > > > The machine running the script is distinct from the Oracle machine > > which is distinct from the Postgresql machine. So, CPU usage is low > > Which somewhat cancels the idea of just using pipes to pass data > directly... Unless the command-line clients can be run "locally" and > connect to the remote servers. > > > buffer. A Queue isn't quite right as it stands, as the data is coming > > in as records, but for postgres loading, a file-like stream is what I > > need, so there will need to be either a wrapper around the Queue on the > > "need"? No... the "copy ... from ..." statement "needs" such, but do > you really "need" to use "copy ... from ..." to load the data -- or is > this just a concept that caught your fancy? > > If you can get Oracle to dump the data in the form of SQL insert > statements, maybe with some clean-up done by a script, and feed them to > PostgreSQL the entire job starts to look something like: > > odump theDatabase | python cleanup.py | psql theNewDatabase > > {note: command line tool names are made up for the example} > > "copy ... from ..." appears to be designed to work with formatted > text files... Something that might have been produced as a tabular > report by almost any tool. As such, you are basically bypassing most of > the DB-API capability. If Oracle has a "select" variant that can specify > a start-offset and length (or a server-side cursor in the DB-API so the > full data is not transferred in one "chunk"), and the PostgreSQL DP-API > supports an "executemany" operation, the threading pseudocode I showed > could still be used. Instead of queueing single records, one could queue > a multiple record "chunk" (a "fetchmany" specifying 100, 500, or > whatever, records); the data would be a list of tuples, so no concerns > about parsing fields from a text record. Then an "executemany" would > submit the chunk at one time. > > > get() side. Or is there a better way to go about this detail? What > > seems to make sense to me is to stringify the incoming oracle data into > > some kind of buffer and then read on the postgresql side. > > My view: avoid using any commands that result in formatting the data > as text reports... Use DB-API interfaces to keep the data as fields. > > ocrsr.execute("select * from table") > while True: > batch = ocrsr.fetchmany(100) > if not batch: break > pcrsr.executemany("insert into table", batch) > > {this is a sequential sample -- but using threads just means the ocrsr > operation are in one thread, batch is the data relayed via a queue, and > pcrsr operations are in the other thread} > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ Using db-api for this is the wrong approach. COPY FROM, which is the postgresql equivilent of oracles SQLLoader, is orders of magnitude faster than sequential inserts, and it's really what you want for bulk data loads. What you're trying to do is read & write from the file at the same time, but across a network interface that's just asking for trouble. In particular, I doubt that postgres expects to have something writing to the end of the file it is loading and will probably error out if it hits an unexpected EOF, which is what will happen if the writer lags behind. Just dump the files from oracle, copy them, and load them. It'll probably be faster in the long run when you count all the time you lose re-starting the processing and troubleshooting your "optimization". From nmm1 at cus.cam.ac.uk Wed Jan 10 13:34:27 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 10 Jan 2007 18:34:27 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <7x8xga215f.fsf@ruckus.brouhaha.com> Message-ID: In article <7x8xga215f.fsf at ruckus.brouhaha.com>, Paul Rubin writes: |> |> > Yes, I know that it is a bit Irish for the best way to use a shared |> > memory system to be to not share memory, but that's how it is. |> |> But I thought serious MPI implementations use shared memory if they |> can. That's the beauty of it, you can run your application on SMP |> processors getting the benefit of shared memory, or split it across |> multiple machines using ethernet or infiniband or whatever, without |> having to change the app code. They use it for the communication, but don't expose it to the programmer. It is therefore easy to put the processes on different CPUs, and get the memory consistency right. Regards, Nick Maclaren. From simon at brunningonline.net Fri Jan 5 12:58:42 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 5 Jan 2007 17:58:42 +0000 Subject: Dividing integers...Convert to float first? In-Reply-To: <12pt3f3kc1jmcf8@corp.supernews.com> References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> <12pt3f3kc1jmcf8@corp.supernews.com> Message-ID: <8c7f10c60701050958v7de470f1ob7df27b15cfb4a83@mail.gmail.com> On 1/5/07, Grant Edwards wrote: > >>> from __future__ import LotteryNumbers > File "", line 1 > SyntaxError: future feature LotteryNumbers is not defined > > Damn. > > I guess it's back to work then. Remember the PEP 8 module name standards. >>> from __future__ import lottery_numbers [1, 16, 19, 20, 21, 39] -- Cheers, Simon B simon at brunningonline.net From dfj225 at gmail.com Wed Jan 10 09:38:48 2007 From: dfj225 at gmail.com (dfj225 at gmail.com) Date: 10 Jan 2007 06:38:48 -0800 Subject: dynamic library loading, missing symbols Message-ID: <1168439928.436359.240390@i39g2000hsf.googlegroups.com> > Did you verify, using nm -D, that the symbol is indeed present in > the shared object, not just in the source code? Yes, the symbol is found in the shared object when using nm. > What flags are given to that dlopen call? dlopen(lib, RTLD_NOW | RTLD_GLOBAL); > No. The dynamic linker doesn't search files to resolve symbols; instead, > it searches the process' memory. It first loads the referenced shared > libraries (processing the DT_NEEDED records in each one); that uses > the LD_LIBRARY_PATH. Then, symbol resolution needs to find everything > in the libraries that have already been loaded. Ok, so if the linker is searching the process address space, then I suppose what really comes into play here is how the Python interpreter dynamically loaded my module, a module which is in turn calling code that does the dlopen above. If the Python interpreter is not loading my library as global, does that mean the linker will not find them when subsequent libraries are loaded? > There are various ways to control which subset of in-memory symbols > the dynamic linker considers: the RTLD_GLOBAL/RTLD_LOCAL flags play > a role, the -Bsymbolic flag given to the static linker has an impact, > and so does the symbol visibility (hidden/internal/protected). Ok, any other suggestions for things to try? Since all of the dlopen calls happen in 3rd party code, I won't really be able to modify them. I will try looking into more compile time flags for the linker and see what I can come up with. Keep in mind that this code works when it is all C++. Only when I add the Boost.Python wrapper to my code and then import in Python do I get this symbol error. Thank you for your help, ~Doug From dotancohen at gmail.com Wed Jan 3 13:33:47 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 3 Jan 2007 20:33:47 +0200 Subject: Unsubscribing from the list In-Reply-To: References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> Message-ID: <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> On 03/01/07, Fredrik Lundh wrote: > Robert provided *detailed* instructions, which you ignored. I quoted > the same instructions in my reply, which you also ignored. the sentence > after the one where you stopped reading also tells you what to do. one > might suspect that you don't really want to unsubscribe from this list... > I didn't ignore his instructions. I went to the page, and found what I was looking for. I told him thank you, and explained why I didn't find it the first time. That was public on the mailing list, go check the archives. Specifically, the first three messages in this thread. I haven't yet unsubscribed because I'm waiting for this thread to die. It's actually rather amusing, because I can't decide if some list members are genuinly upset at me, or if it is a orm of humour that I am unfamiliar with. Either way, the thread is entertaining enough that I remain. Dotan Cohen http://lyricslist.com/lyrics/artist_albums/443/seger_bob.html http://technology-sleuth.com/long_answer/how_can_i_be_safe_online.html From steve at REMOVEME.cybersource.com.au Mon Jan 15 22:11:03 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 16 Jan 2007 14:11:03 +1100 Subject: assert versus print [was Re: The curious behavior of integer objects] References: Message-ID: On Mon, 15 Jan 2007 21:38:42 -0500, Calvin Spealman wrote: > On 1/15/07, Steven D'Aprano wrote: >> On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote: >> >> > assert foo(0x10) == 0 # Assertions are much better tests than prints :-) >> >> I dispute that assertion (pun intended). > > Hah! > >> Firstly, print statements work even if you pass the -O (optimize) flag >> to Python. Your asserts don't. > > This is true, but the concept can be adapted to a things like an > assert_() function. Hence defeating the optimization :) So what you're saying is, some custom function that you write yourself is better than print? I suppose I can't argue with that :) >> Secondly, a bare assertion like that gives you very little information: >> it just tells you that it failed: >> >> >>> x = 1 >> >>> assert x == 0 >> Traceback (most recent call last): >> File "", line 1, in ? >> AssertionError >> >> To provide the same information that print provides, you need something >> like this: >> >> assert x == 0, "x == %s not 0" % x > > What information would I need to know if my test passed? Nothing, I say. Maybe. But then it is hard to tell the difference between "my test function printed nothing because it is broken, and my test function printed nothing because it succeeded". There are good arguments both for and against successful tests printing a result. Keep in mind that a successful assert doesn't actually print "nothing" in the interactive interpreter: when it completes, you do get feedback because Python prints a prompt. Getting feedback that the test completed successfully is vital. The only question is whether that feedback should be minimal or verbose. But in any case, you have misunderstood the assertion. The error message is printed *if the assert fails*, not if it passes. > I only want to know when the tests fail, especially as I add more of > them. Having no output is a great way to know nothing puked. Sure -- for unit testing. For interactive exploration, seeing the value of a variable is better than guessing. That's why a bare object reference in the interactive interpreter prints itself, but in a script does nothing. -- Steven D'Aprano From streamservenl at gmail.com Wed Jan 31 10:58:28 2007 From: streamservenl at gmail.com (jvdb) Date: 31 Jan 2007 07:58:28 -0800 Subject: Help needed on config files In-Reply-To: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> References: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> Message-ID: <1170259108.904457.44260@a34g2000cwb.googlegroups.com> Ok, with all your help and very useful hints, i managed to solve it! thanks! Now my program loops through the config file, and deletes the files older than 7 days with a specified extension. Here's my program: #this project removes old log files import os, time from ConfigParser import ConfigParser now=time.time() cfg = ConfigParser() cfg.read("projects.cfg") #loop through the config file for proj in cfg.sections(): print "" #get the path where file files should be path = cfg.items(proj)[1][1] #get the filetype ftype = cfg.items(proj)[0][1] print "project: %s, path to old logfiles: %s" % (proj, path) dirList=os.listdir(path) # Now check if the file is not a dir and then check if the file is older than 7 days for fname in dirList: if fname.endswith(ftype): pad = path+"\\"+fname if os.stat(pad).st_mtime < now - 7 * 86400: if os.path.isfile(pad): os.remove(pad) print "The file %s is deleted" % (fname) =========== #projects.cfg [ebiz_factuur] dir=c:\customer\ebiz_factuur type=.log [test] dir=c:\temp type=.txt From rpdooling at gmail.com Mon Jan 22 09:53:12 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 22 Jan 2007 06:53:12 -0800 Subject: GetBoundingMetrics Message-ID: <1169477592.377844.324590@v45g2000cwv.googlegroups.com> Hi, I have been moving from Windows XP to Debian Etch. Most of my Python scripts work fine with minor modifications. However, I have a script that launches a browser and goes to various sites using the Python module webbrowser.open ("url-goes-here") On Debian Etch, Firefox (or IceWeasel, I guess) opens the sites, but back in the commandline window I get repeated messages that say: GetBoundingMetrics (char *) Anybody know what's causing that? I don't get it if I just launch firefox from the commandline. Only when I use the Python module. Thank you, rd From xyzl at example.com Wed Jan 17 16:14:50 2007 From: xyzl at example.com (xyzl) Date: Wed, 17 Jan 2007 22:14:50 +0100 Subject: *POLL* How many sheeple believe in the 911 fairy tale and willingto accept an Orwellian doublespeak and enslavement world ? In-Reply-To: References: Message-ID: <45ae91b2$0$327$e4fe514c@news.xs4all.nl> http://www.thebestpageintheuniverse.net/c.cgi?u=911_morons From ptmcg at austin.rr.com Sun Jan 21 17:15:33 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 Jan 2007 14:15:33 -0800 Subject: pyparsing Combine without merging sub-expressions In-Reply-To: References: Message-ID: <1169417733.814587.63560@11g2000cwr.googlegroups.com> Steven Bethard wrote: > Within a larger pyparsing grammar, I have something that looks like:: > > wsj/00/wsj_0003.mrg > > When parsing this, I'd like to keep around both the full string, and the > AAA_NNNN substring of it, so I'd like something like:: > > >>> foo.parseString('wsj/00/wsj_0003.mrg') > (['wsj/00/wsj_0003.mrg', 'wsj_0003'], {}) > > How do I go about this? I was using something like:: > > >>> digits = pp.Word(pp.nums) > >>> alphas = pp.Word(pp.alphas) > >>> wsj_name = pp.Combine(alphas + '_' + digits) > >>> wsj_path = pp.Combine(alphas + '/' + digits + '/' + wsj_name + > ... '.mrg') > > But of course then all I get back is the full path:: > > >>> wsj_path.parseString('wsj/00/wsj_0003.mrg') > (['wsj/00/wsj_0003.mrg'], {}) > The tokens are what the tokens are, so if you want to replicate a sub-field, then you'll need a parse action to insert it into the returned tokens. BUT, if all you want is to be able to easily *access* that sub-field, then why not give it a results name? Like this: wsj_name = pp.Combine(alphas + '_' + digits).setResultsName("name") Leave everything else the same, but now you can access the name field independently from the rest of the combined tokens. result = wsj_path.parseString('wsj/00/wsj_0003.mrg') print result.dump() print result.name print result.asList() -- Paul From no-spam at no-spam-no-spam.invalid Tue Jan 16 07:06:03 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Tue, 16 Jan 2007 13:06:03 +0100 Subject: why scipy cause my program slow? In-Reply-To: <1168937877.189713.239360@38g2000cwa.googlegroups.com> References: <1168935124.912419.147250@a75g2000cwd.googlegroups.com> <1168937877.189713.239360@38g2000cwa.googlegroups.com> Message-ID: HYRY wrote: > Thanks, by your hint, I change type(data) to type(data[0]), and I get > > > So, calculate with float is about 5x faster numpy.float64. > approx.. numpy funcs all upcast int to int32 and float to float32 and int32/float to float32 etc. This is probably ill behavior. float32 arrays should only arise if numpy.array(l,dtype=numpy.float32) In your example you'll best go to numpy/scipy types very early (not mixing with the python array type in addition) and do the array computations with scipy left = [abs(x-mean) for x in left] -> data = scipy.array(f.readframes(t[3]),"h") .. left = abs(left-mean) code the test(data) similar - see also scipy.signal.lfilter etc. and cast types down to Python types late like float(mynumfloat) ... The type magic and speed loss will and pickle problems will probably only disapear, when float & int are handled as extra (more conservative) types in numpy - with numpy scalar types only on request. Currently numpy uses Python. Robert From robert.kern at gmail.com Tue Jan 9 18:41:51 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 17:41:51 -0600 Subject: distutils and ctypes In-Reply-To: <45a41b1f$0$19653$9b622d9e@news.freenet.de> References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> <45A3FF17.2070509@v.loewis.de> <45a41b1f$0$19653$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Robert Kern schrieb: >>> Not sure it's stupid, but I wonder why you want to use ctypes. What's >>> wrong with extension modules? >> What's wrong with ctypes? They're both valid, useful approaches to connect to C >> libraries. > > See the original posting. Distutils doesn't support building arbitrary > shared libraries, but does support building extension modules. > > Furthermore, extension modules are more type-safe and more expressive > than loading shared libraries through ctypes. IMO, you may consider > using ctypes as a last resort - if you have the chance for a > well-engineered solution, write a compiled wrapper. To which I say that doing the type-checking and error handling is much easier in Python than using the C API. Add to that the tediousness of the edit-compile-run cycle of C and the finickiness of refcounting. There's nothing *wrong* with either approach. They're just different and have different strengths and weaknesses. Some of those weaknesses are remediable (say by using the bdist_shlib command that the OOF2 project implemented) and some aren't. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From hg at nospam.org Tue Jan 30 09:43:10 2007 From: hg at nospam.org (hg) Date: Tue, 30 Jan 2007 15:43:10 +0100 Subject: Convert raw data to XML References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> <1170184059.739808.244660@s48g2000cws.googlegroups.com> <1170189278.490020.52670@h3g2000cwc.googlegroups.com> Message-ID: elrondrules at gmail.com wrote: > On Jan 30, 12:05 pm, John Nagle wrote: >> elrondru... at gmail.com wrote: >> > On Jan 29, 8:54 pm, "Gabriel Genellina" wrote: >> >> >>En Mon, 29 Jan 2007 23:42:07 -0300, escribi?: >> > the reason I wanted to write it as a file was to parse the file, look >> > for a specific attribute and execute a set of commands based on the >> > value of the attribute.. also i needed to display the output of the >> > http post in a more readable format.. >> >> That's straightforward. You confused people by asking the >> wrong question. You wrote "Convert raw data to XML", but what >> you want to do is parse XML and extract data from it. >> >> This will do what you want: >> >> http://www.crummy.com/software/BeautifulSoup/ >> >> For starters, try >> >> from BeautifulSoup import BeautifulStoneSoup >> xmlstring = somexml ## get your XML into here as one big >> string >> soup = BeautifulStoneSoup(xmlstring) # parse XML into tree >> print soup.prettify() # print out in indented format >> >> "soup" is a tree structure representing the XML, and there are >> functions to easily find items in the tree by tag name, attribute, >> and such. Work on the tree, not a file with the text of the indented >> output. >> >> John Nagle > > is there any other way to do this without using BeautifulStoneSoup.. > using existing minidom or ext.. > i dont want to install anything new yes, write it ;-) From no-spam at no-spam-no-spam.invalid Mon Jan 15 12:32:52 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Mon, 15 Jan 2007 18:32:52 +0100 Subject: catching signals in an object In-Reply-To: <7MOqh.18678$sE7.16830@newsfe21.lga> References: <7MOqh.18678$sE7.16830@newsfe21.lga> Message-ID: hg wrote: > Hi, > > I need to catch a signal "SIGUSR1" in an object ... and I need the signal > def that traps is to access the object context ... is that possible ? > (*nix and windows) > > ex: > > class test: > def __init__(self): > self.Set_Signal() > > def Set_Signal(self): > import signal > signal.signal(..., Func) > def Func(.....): > #I need to get access to self > > > or can signal.signal take a method as param ? > Just do it! Python is a functional language. You have access to self (search for the term "closure") and self.method is bound - thus a 'function' objects are nothing special in Python. Robert From fabiofz at gmail.com Wed Jan 24 06:06:03 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 24 Jan 2007 09:06:03 -0200 Subject: Pydev 1.2.6 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.2.6 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Added refactoring support for rename (still BETA, so, don't forget to review your changes before applying them) - Keybinding: Alt+Shift+R - Supports preview - Integrated in the editor (but not in the package explorer, so, it can rename a module, but only through an import to that module) - Supports undo/redo in the workspace - Rename class - Rename method - Rename attribute - Rename imports - Rename local variable * Menu changes: - Now the debug/navigate actions are all under a 'Pydev' menu - The pydev navigate action is now only initially shown in the pydev/debug perspective - The pydev remote debugging actions are now only initially shown in the debug perspective * Fix: code analysis problem when working with nested list-comprehensions * Fix: go to definition sometimes failed to find module definitions Release Highlights in Pydev: ---------------------------------------------- * Pydev package explorer (Still BETA, so, use it with care -- the navigator is still the preferred way of browsing your project) - Filters for .pyc and .pyo files created - Working set integration added (just available for Eclipse 3.2.1) - Some minor bugs fixed * Patch by Olof Wolgast: The 'create docstrings' assistant has more options (windows > preferences > pydev > code formatter > docstrings) - Option to choose between single and double quotes - Option to create '@type' too and not only '@param' - Option to skip creation of the @type tag for parameters starting with some prefix (if 'Custom' is chosen) * Block comments now have more options (windows > preferences > pydev > code formatter > block comments) - Option to align single-line block comment to the left or right - Option to put class name above class if applied on a class definition * Fix: Multi-line Templates indent correctly * Fix: When a file from a project that was deleted was still opened inside pydev, Eclipse would not start-up correctly * Fix: When a different interpreter is chosen in the run dialog, the pythonpath is correctly gotten * Fix: when Pydev was started, it would re-save the .pydevproject file even if no change was done * Fix: When tab width was set to 0 it could halt the editor (now if 0 is set, 4 is assumed) * Grammar Patch by Ueli Kistler, Dennis Hunziker What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Sun Jan 7 14:29:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 11:29:19 -0800 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: <1168194009.220437.286210@q40g2000cwq.googlegroups.com> Message-ID: <1168198159.798783.168010@i15g2000cwa.googlegroups.com> On 7 ene, 16:20, "W. Watson" wrote: > We seem to be looping. I have the Python interpreter. I would like the > pythonwin editor. The download link doesn't work on SourceForge. Where can I > get it? If not there, where? If it can't be obtained, then I'll go to the > default editor built into python-2.5.msi. It *does* work for me. Try https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063 -- Gabriel Genellina From redefined.horizons at gmail.com Fri Jan 5 12:19:12 2007 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 5 Jan 2007 09:19:12 -0800 Subject: Adding a directory to the Python System Path - Edit the registry? Message-ID: <1168017552.010631.276080@s34g2000cwa.googlegroups.com> I have been trying to find a way to add a directory to Python's sytem path on my MS Windows XP computer. I did some searching online, but the only solution I found involved editing the MS Windows Registry. That seemed a little to hard core. Is there another easier way to do this? Thanks, Scott Huey From michele.simionato at gmail.com Thu Jan 25 00:39:55 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 24 Jan 2007 21:39:55 -0800 Subject: ANN: Dejavu 1.5.0RC1 In-Reply-To: References: Message-ID: <1169703594.951755.180990@m58g2000cwm.googlegroups.com> On Jan 24, 11:57 pm, "Robert Brewer" wrote: > The Dejavu Object-Relational Mapper (version 1.5.0RC1) is now available > and in the public domain. Get it athttp://projects.amor.org/dejavu, > or from PyPI:http://www.python.org/pypi/Dejavu/1.5.0RC1. I am curious ... how this compare to SQLAlchemy? Michele Simionato From steveo at eircom.net Tue Jan 9 11:33:44 2007 From: steveo at eircom.net (Steve O'Hara-Smith) Date: Tue, 9 Jan 2007 16:33:44 +0000 Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: <20070109163344.7f5ff833.steveo@eircom.net> On Tue, 9 Jan 2007 15:25:43 +0000 zoara wrote: > On 9 Jan 2007 06:58:15 -0800, octabox at gmail.com wrote: > > > Hello all, > > > > I represent Octabox, an Internet Start-up developing a wide-scale > Well, that was too tempting to pass up. Amusing answers related to dirty > bastard time-wasting spammers duly entered and submitted. Yes it was - and may they get many more similar responses :) -- C:>WIN | Directable Mirror Arrays The computer obeys and wins. | A better way to focus the sun You lose and Bill collects. | licences available see | http://www.sohara.org/ From http Sun Jan 7 22:21:04 2007 From: http (Paul Rubin) Date: 07 Jan 2007 19:21:04 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> <1168189375.843789.306180@51g2000cwl.googlegroups.com> Message-ID: <7xps9q19wf.fsf@ruckus.brouhaha.com> "Paul Boddie" writes: > > Consider that the above three class definitions might be in separate > > files and you see how clumsy this gets. > > What are you trying to show with the above? The principal benefit of > using private attributes set on either the class or the instance is to > preserve access, via self, to those attributes defined in association > with (or within) a particular class in the inheritance hierarchy, as > opposed to providing access to the "most overriding" definition of an > attribute. This is demonstrated more effectively with a method on class A: Right, the problem is if those methods start changing the "private" variable. I should have been more explicit about that. class A: def __init__(self): self.__x = 3 def foo(self): return self.__x class B(A): pass class A(B): def bar(self): self.__x = 5 # clobbers private variable of earlier class named A From py at th.on Tue Jan 23 12:25:24 2007 From: py at th.on (py) Date: Tue, 23 Jan 2007 17:25:24 GMT Subject: smtplib starttls gmail example Message-ID: <8yrth.1230$JB.276@trnddc05> from smtplib import SMTP from socket import sslerror #if desired server = SMTP('smtp.gmail.com') server.set_debuglevel(0) # or 1 for verbosity server.ehlo('youraddress at gmail.com') server.starttls() server.ehlo('youraddress at gmail.com') # say hello again server.login('youraddress at gmail.com', 'yourpassword') # i have a suspicion that smptlib does not add the required newline dot newline so i do it myself server.sendmail('youraddress at gmail.com', 're at cipient.com', message_text + '\n.\n') # next line generates the ignorable socket.sslerror server.quit() From http Sat Jan 6 20:38:06 2007 From: http (Paul Rubin) Date: 06 Jan 2007 17:38:06 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <7xd55rzke9.fsf@ruckus.brouhaha.com> "BJ?rn Lindqvist" writes: > It is given that emphasizing private data (encapsulation) leads to > more internal complexity and more lines of code because you have to > write getters and setters and stuff. You can have public variables in Java if you choose to. Writing private variables with public setters and getters is just a style choice. > Or do you have anecdotal evidence of where data encapsulation saved > your ass? There are certainly applications that can't live without it, like browser applets. As for it saving my ass, there's no way to know, it's like asking whether garbage collection has saved my ass. Yes I've had plenty of pointer related bugs in C programs that don't happen in GC'd languages, so GC in that sense saves my ass all the time. I've also had bugs in Python programs that would have been prevented by better use of encapsulation (including in the stdlib). Python certainly makes you spend more of your attention worrying about possible attribute name collisions between classes and their superclasses. And Python's name mangling scheme is leaky and bug-prone if you ever re-use class names. Overall, I think Python would gain from having better support for encapsulation and C++-like casting between class instances. From zgolus at gmail.com Mon Jan 15 07:39:21 2007 From: zgolus at gmail.com (zgolus at gmail.com) Date: 15 Jan 2007 04:39:21 -0800 Subject: Conditional validation of documents (ignoring IDREFs) Message-ID: <1168864761.033799.285500@51g2000cwl.googlegroups.com> I'm working with one extra large XML file which consists of many parts. Every part can be considered a stand-alone document with references to other parts (IDs and IDREFs). I would like to be able to validate every such part against a DTD but ignoring errors which arise from broken references. Can I do it with pyxml? Thanks in advance! From gagsl-py at yahoo.com.ar Tue Jan 16 12:07:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 14:07:17 -0300 Subject: Search Queue References: <1168960945.787822.286690@s34g2000cwa.googlegroups.com><1168962673.664083.146220@38g2000cwa.googlegroups.com> <1168964356.125262.45110@v45g2000cwv.googlegroups.com> Message-ID: "abcd" escribi? en el mensaje news:1168964356.125262.45110 at v45g2000cwv.googlegroups.com... > Yea basically I need Queue like functionality with the ability to > search for a particular instance in it. I guess I could just use a > list and search it as needed. Perhaps the Queue class should be called ThreadQueue, or be contained in the threading module, or something like that. The current name is misleading. -- Gabriel Genellina From martin at v.loewis.de Wed Jan 24 02:35:42 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 24 Jan 2007 08:35:42 +0100 Subject: What's the reverse of Py_BuildValue("u#" ? In-Reply-To: <1169605378.718701.229310@d71g2000cwa.googlegroups.com> References: <1169605378.718701.229310@d71g2000cwa.googlegroups.com> Message-ID: <45b70c4e$0$30347$9b622d9e@news.freenet.de> sndive at gmail.com schrieb: > How could I get the pointer to and the length of ucs2 array out of a > PyObject representing a string? Something that works whether PyObject > string is in unicode or not. You can use PyObject_Unicode(o) to convert the object to Unicode first, then use PyUnicode_AsUnicode to convert it to a Py_UNICODE array, and PyUnicode_GetSize to find out what the length is. Notice that this will be UCS-2 only if Py_UNICODE is 16 bits on your platform. If you really want UCS-2 always, you need to convert the string again using PyUnicode_AsEncodedObject, then PyString_AsString to find out what the UCS-2 bytes are. Remember to check for errors for all these functions, and remember to decref the results when you don't need them any longer. > > Also could I replace a sequence > > if(PyBool_Check(obj)) { >... > } > if(PyString_Check(obj)) { // would this be true for any string >type? >... > } > if(PyFloat_Check(obj)) { >... > with a switch? Not easily. Also, PyString_Check is true only for the byte string type (and its subtypes). Regards, Martin From nospam at riddergarn.dk Mon Jan 29 07:12:58 2007 From: nospam at riddergarn.dk (Scripter47) Date: Mon, 29 Jan 2007 13:12:58 +0100 Subject: IP address In-Reply-To: <1170039052.541186.326990@j27g2000cwj.googlegroups.com> References: <1170039052.541186.326990@j27g2000cwj.googlegroups.com> Message-ID: <45BDE4CA.3060800@riddergarn.dk> Beej skrev: > On Jan 28, 2:26 am, Klaus Alexander Seistrup wrote: >> Scripter47 wrote: >>> How do i get my ip address? >>> in cmd.exe i just type "ipconfig" then it prints: >>> ... >>> IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 >>> ... >>> how can i do that in python??#v+ >> python -c 'import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' > > This is extremely unlikely to return 192.168.1.10. :-) > > (It will give you the address of your firewall or whatever is your > gateway to the outside world... which is a cool thing to know, but > I'm not sure it's what the op's after.) > > -Beej > Exactly i wnat my local ip. sorry if i din't tell that ;) From horpner at yahoo.com Tue Jan 9 14:09:43 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 9 Jan 2007 20:09:43 +0100 Subject: A simple lexer Message-ID: I'm a royal n00b to writing translators, but you have to start someplace. In my Python project, I've decided that writing the dispatch code to sit between the Glulx virtual machine and the Glk API will be best done automatically, using the handy prototypes. Below is the prototype of the lexer, and I'd like some comments in case I'm doing something silly already. My particular concern are: The loop checks for each possible lexeme one at a time, and has rather lame error checking. I made regexes for matching a couple of really trivial cases for the sake of consistency. In general, is there a better way to use re module for lexing. Ultimately, I'm going to need to build up an AST from the lines, and use that to generate Python code to dispatch Glk functions. I realize I'm throwing away the id of the lexeme right now; suggestions on the best way to store that information are welcome. I do know of and have experimented with PyParsing, but for now I want to use the standard modules. After I understand what I'm doing, I think a PyParsing solution will be easy to write. import re def match(regex, proto, ix, lexed_line): m = regex.match(proto, ix) if m: lexed_line.append(m.group()) ix = m.end() return ix def parse(proto): """ Return a lexed version of the prototype string. See the Glk specification, 0.7.0, section 11.1.4 >>> parse('0:') ['0', ':'] >>> parse('1:Cu') ['1', ':', 'Cu'] >>> parse('2>> parse('4Iu&#![2SF]>+Iu:Is') ['4', 'Iu', '&#!', '[', '2', 'S', 'F', ']', '>+', 'Iu', ':', 'Is'] """ arg_count = re.compile('\d+') qualifier = re.compile('[&<>][+#!]*') type_name = re.compile('I[us]|C[nus]|[SUF]|Q[a-z]') o_bracket = re.compile('\\[') c_bracket = re.compile('\\]') colon = re.compile(':') ix = 0 lexed_line = [] m = lambda regex, ix: match(regex, proto, ix, lexed_line) while ix < len(proto): old = ix ix = m(arg_count, ix) ix = m(qualifier, ix) ix = m(type_name, ix) ix = m(o_bracket, ix) ix = m(c_bracket, ix) ix = m(colon, ix) if ix == old: print "Parse error at %s of %s" % (proto[ix:], proto) ix = len(proto) return lexed_line if __name__ == "__main__": import doctest doctest.testmod() -- Neil Cerutti We dispense with accuracy --sign at New York drug store From corsairdgr at aol.com Mon Jan 15 12:35:06 2007 From: corsairdgr at aol.com (corsairdgr at aol.com) Date: Mon, 15 Jan 2007 12:35:06 -0500 Subject: can't get import to work! Message-ID: <8C906E2A183C0C2-B34-FE5@WEBMAIL-RA03.sysops.aol.com> I am brand new to jython/python. I want to use my own Java class from within a Jython script. In Java, I created a class called Fubar and put this in a jar file called testit.jar. The Fubar class is in the just.for.fun package and this path shows up in the testit.jar file. I then modified the jython.bat file (I'm using windows) to include the testit.jar file in the classpath. When jython starts from the command line, it notices testit.jar and generates some cache information. Next I want to use the Fubar class in a jython script. I start jython from the command line and type: from just.for.fun import Fubar This doesn't work. The following error is displayed: ImportError: No module named for I also try import just.for.fun.Fubar This gives the same error. I can enter import java.util.HashMap and other such imports and these work. Can someone please tell me what I could be doing wrong ? Thanks, ________________________________________________________________________ Check out the new AOL. Most comprehensive set of free safety and security tools, free access to millions of high-quality videos from across the web, free AOL Mail and more. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gatis.tomsons at gmail.com Wed Jan 10 04:46:41 2007 From: gatis.tomsons at gmail.com (Gacha) Date: 10 Jan 2007 01:46:41 -0800 Subject: pyExcelerator big integer values In-Reply-To: <45a42e7c@news.eftel.com> References: <1168349446.381187.65810@11g2000cwr.googlegroups.com> <45a42e7c@news.eftel.com> Message-ID: <1168422401.594651.278390@i39g2000hsf.googlegroups.com> Thank you, the repr() function helped me a lot. v = unicode(values[(row_idx, col_idx)]) if v.endswith('e+12'): v = repr(values[(row_idx, col_idx)]) From fsckedagain at gmail.com Wed Jan 3 18:53:01 2007 From: fsckedagain at gmail.com (fscked) Date: 3 Jan 2007 15:53:01 -0800 Subject: minidom utf-8 encoding Message-ID: <1167868380.481121.154880@42g2000cwt.googlegroups.com> Hi guys/gals. I am trying to write and xml file from data parsed from a csv. I can get everything to work except that I cannot get minidom to do --> ? which needless to say is driving me nuts. Any suggestions? What it ends up doing is just removing the character from the datastream. From __peter__ at web.de Tue Jan 30 10:47:23 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Jan 2007 16:47:23 +0100 Subject: Help me override append function of list object References: <1170171317.866549.261060@a34g2000cwb.googlegroups.com> Message-ID: jeremito wrote: > I have created a class that inherits from the list object. I want to > override the append function to allow my class to append several > copies at the same time with one function call. I want to do > something like: > > import copy > > class MyList(list): > __init__(self): > pass > > def append(self, object, n=1): > for i in xrange(n): > self.append(copy.copy(object)) > > Now I know this doesn't work because I overwrite append, but want the > original functionality of the list object. Can someone help me? Use list.append(self, obj) or super(MyList, self).append(obj), e. g.: >>> import copy >>> class List(list): ... def append(self, obj, n=1): ... for i in xrange(n): ... super(List, self).append(copy.copy(obj)) ... >>> items = List() >>> items.append(42, 3) >>> items [42, 42, 42] Peter From bruno.desthuilliers at gmail.com Mon Jan 15 07:27:55 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 15 Jan 2007 04:27:55 -0800 Subject: Python web app. (advice sought) In-Reply-To: <45aae51b.0@entanet> References: <45aae51b.0@entanet> Message-ID: <1168864075.878863.172950@38g2000cwa.googlegroups.com> Duncan Smith a ?crit : > Hello, > I find myself in the, for me, unusual (and at the moment unique) > position of having to write a web application. I have quite a lot of > existing Python code that will form part of the business logic. This > relies on 3rd party libraries (such as numpy) which would make porting > to e.g. IronPython difficult (I would imagine). I was thinking LAMP > (the P standing for Python, of course), particularly as I was originally > encouraged to go for open source solutions. > > The application will provide some basic statistical analyses of data > contained in database tables and associated plots (R / matplotlib / > graphviz). There will also be some heavier duty Monte Carlo simulation > and graphical modelling / MCMC. The user(s) will need to be able to set > model parameters; maybe even tinker with model structure, so it will be > very interactive (AJAX?). > > I've had a look at Django, Turbogears and Plone, and at the moment I am > torn between Turbogears and Plone. I get the impression that Turbogears > will require me to write more non-Python code, ??? > but maybe Plone is more > than I need (steeper learning curve?). Maybe Turbogears will lead to a > more loosely coupled app. than Plone? Plone is nice for content management (well, it's a CMS, isn't it ?), but I certainly wouldn't choose it for the kind off application you are describing. A simpler, lighter MVC framework would be far more appropriate IMHO. Turbogears may be a good choice, but you may also want to have a look at web.py and Pylons. > The disconcerting thing is that others on the project (who won't be > developing) have started to talk about a LAMP back end with an IIS front > end, .NET, and the benefits of sharepoint. My my my... > The emphasis is supposed to > be on rapid development, and these technologies are supposed to help. > But I have no real familiarity with them at all; just Python, C and SQL > to any realistic level of competence. Then go for the simplest thing. My 2 cents... From jarausch at skynet.be Tue Jan 2 12:16:28 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 02 Jan 2007 18:16:28 +0100 Subject: python2.5 frameobject - how to upgrade? In-Reply-To: References: <459a6894$0$9322$ba620e4c@news.skynet.be> Message-ID: <459A936C.4090609@skynet.be> skip at pobox.com wrote: > Helmut> I'd like to install a package ('rekall') which uses > Helmut> frame->f_nlocals which is no longer contained in frameobject.h. > > Helmut> What's the recommended way to upgrade such an application? > > I suspect PySequence_Length(frame->f_locals) will do the trick. Yes, thanks, that fixed it, Happy New Year to you. A personal question: Have you converted from Perl to Python, as well? -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From gagsl-py at yahoo.com.ar Fri Jan 19 11:45:44 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 13:45:44 -0300 Subject: PQueue and Python 2.5 References: <1169216890.617239.209170@51g2000cwl.googlegroups.com> Message-ID: "Berteun Damman" escribi? en el mensaje news:1169216890.617239.209170 at 51g2000cwl.googlegroups.com... > Recently I was looking for a Priority Queue module, and I've found > Pqueue by Andrew Snare [1]. That appears to be rather ancient, from 1999. Is it a pure Python implementation or has some C code too? Python got in 2.3 a heapq module in its standard library; I think it is what you want, no need for an additional module. > *** glibc detected *** free(): invalid pointer: 0x00002ad7b5720288 *** > Abort > > And on my PowerBook: > python2.5(8124) malloc: *** Deallocation of a pointer not malloced: > 0x3b4218; This could be a double free(), or free() called with the > middle of an allocated block; > > A memory fault can also be immediately triggered by apply 'del' to a > PQueue-instance. As said, with Python 2.4 it seems to perform without > problems. Ah! then I bet: - There is some C code involved. - It carelessly mixes PyMem_Malloc with PyObject_Free or similar as described in http://docs.python.org/whatsnew/ports.html So do yourself a favor and forget about such old piece of code... -- Gabriel Genellina From scolnik at fibertel.com.ar Fri Jan 12 05:29:57 2007 From: scolnik at fibertel.com.ar (scolnik) Date: Fri, 12 Jan 2007 07:29:57 -0300 Subject: Integer solutions to linear equation? Message-ID: <000601c73634$9bb63f40$0200a8c0@scolnik> The answer to your integer solutions problem can be found in http://www.alpertron.com.ar/QUAD.HTM Best Hugo Scolnik Imagination is more important than knowledge. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Sun Jan 7 15:35:42 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 12:35:42 -0800 Subject: Why less emphasis on private data? In-Reply-To: <9dboh.11767$ZT3.426@newssvr19.news.prodigy.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <9dboh.11767$ZT3.426@newssvr19.news.prodigy.com> Message-ID: <1168202142.393267.65940@i15g2000cwa.googlegroups.com> On 7 ene, 16:13, John Nagle wrote: > Because Python doesn't have explicit declarations, scope of variables is > a touchy issue. If you write "x = 1" within a function, that will > create a local "x" if "x" doesn't exist, or alter a global "x" if "x" was > previously created in the global context. But at least global variables > are local to the namespace; we don't have clashes across files. No, `x=1` always uses a local variable x, unless an (explicit!) global statement was in effect in the same block. This, and the explicit self, make very clear which x you are referring to. -- Gabriel Genellina From ziga.seilnacht at gmail.com Mon Jan 8 13:16:54 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 8 Jan 2007 10:16:54 -0800 Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> <1168277798.302236.184180@s34g2000cwa.googlegroups.com> Message-ID: <1168280213.382178.228020@11g2000cwr.googlegroups.com> Nick Maclaren wrote: > Well, it's not felt necessary to distinguish those at top level, so > why should it be when they are in a sequence? Well, this probably wasn't the best example, see the links below for a better one. > But this whole thing is getting ridiculous. The current implementation > is a bizarre interpretation of the specification, but clearly not an > incorrect one. It isn't important enough to get involved in a religious > war over - I was merely puzzled as to the odd behaviour, because I have > to teach it, and it is the sort of thing that can confuse naive users. There was a recent bug report identical to your complaints, which was closed as invalid. The rationale for closing it was that things like: print ("a, bc", "de f,", "gh), i") would be extremely confusing if the current behaviour was changed. See http://www.python.org/sf/1534769 for details. Ziga From gert.cuykens at gmail.com Sun Jan 21 20:58:31 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Mon, 22 Jan 2007 02:58:31 +0100 Subject: instancemethod In-Reply-To: References: Message-ID: On 1/22/07, Gert Cuykens wrote: > On 1/22/07, Gabriel Genellina wrote: > > "Gert Cuykens" escribi? en el mensaje > > news:ef60af090701211416n5b2eb7edt2ee6d4555bd49c1a at mail.gmail.com... > > > > > class Db: > > > > > > _db=-1 > > > _cursor=-1 > > > > > > @classmethod > > > def __init__(self,server,user,password,database): > > > self._db=MySQLdb.connect(server , user , password , database) > > > self._cursor=self._db.cursor() > > > > > > @classmethod > > > def excecute(self,cmd): > > > self._cursor.execute(cmd) > > > self._db.commit() > > > > > > > > > if __name__ == '__main__': > > > gert=Db('localhost','root','******','gert') > > > gert.excecute('select * from person') > > > for x in range(0,gert.rowcount): > > > print gert.fetchone() > > > gert.close() > > > > Besides your specific question that was already answered, why are you using > > classmethods at all? > > You are constructing a Db instance and using it as if all were normal > > instance methods... Just remove all those @classmethod declarations and use > > it in a standard way. > > > > -- > > Gabriel Genellina > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > i thought @classmethod was the normal method ? > did some reading and i think i know why now :) http://www.faqts.com/knowledge_base/view.phtml/aid/16824 python always seems to amaze me how other languages make a mess of things that suppose to be simple From tjreedy at udel.edu Sat Jan 6 00:29:48 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 Jan 2007 00:29:48 -0500 Subject: I will be proposing this PEP References: <4c0048df0701051459m7abf0662r69060ce9faff6bc4@mail.gmail.com> Message-ID: "Collin Stocks" wrote in message news:4c0048df0701051459m7abf0662r69060ce9faff6bc4 at mail.gmail.com... | Attached is a PEP which I will be proposing soon. If you have any questions, | comments, or suggestions, please email them to me with the subject "Adding | Built-in Class Attributes PEP" I believe that properties were added for new-style classes to address the issues you address. You make no mention of them. Old style classes will disaappear in the future. tjr From pkyoung at gmail.com Wed Jan 24 03:12:35 2007 From: pkyoung at gmail.com (auditory) Date: Wed, 24 Jan 2007 17:12:35 +0900 Subject: numpy or _numpy or Numeric? In-Reply-To: <1169625580.411463.216040@s48g2000cws.googlegroups.com> References: <1169625580.411463.216040@s48g2000cws.googlegroups.com> Message-ID: George Sakkis ? ?: > On Jan 24, 2:24 am, auditory wrote: > >> I am a newbie here >> >> I am trying to read "space separated floating point data" from file >> >> I read about csv module by searching this group, >> but I couldn't read space separated values with csv. >> (which may be matter of course..) >> >> I also read about numpy.fromfile(file, sep=' ') which i can use. >> but on my machine(ubuntu linux) numpy is unknown module, >> which I didn't install by myself. >> >> While trying to install numpy accroding to its homepage. >> (http://numpy.scipy.org/numpydoc/numdoc.htm). >> i am quite confused. >> >> it's talking about the Numerical Python, >> and it says to test whether it is installed or not, >> try import Numeric instead of numpy. >> >> I got Nurmeric modules and >> as a matter of fact i got a file named '_numpy.so' in lib directory. >> >> I can import _numpy but _numpy does not have 'fromfile' method >> >> My question is: >> 1. Do i need to install numpy module? >> 2. Then Is it different from Numeric module? >> 3. Then where can i get it? >> >> 4. Or what is general way to read 'space separated values' from file? >> >> Thanks in advance. > > If *all* you need is to read a space-separated file with floating point > values, installing numpy (or Numeric or numarray..) is an overkill; you > can do it in one line in pure Python: > > matrix = [map(float, line.split()) for line in > open('my_space_separated_file.txt')] > > This stores the values as a list of lists, each list corresponding to a > row in the file. Depending on what you plan to do next with these > numbers, this may or may not be the best way to go about it, but since > you only mentioned the file reading part, we can't assume much. > > George > Thanks a lot for your 'elegant' suggestion. As a next step i wish to do some math with matrix and produce a vector and write it on a file. (in fact math is just averaging now) I hope i can do this with a little more efforts. From jstroud at mbi.ucla.edu Mon Jan 15 17:44:33 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 15 Jan 2007 14:44:33 -0800 Subject: whats wrong with my reg expression ? In-Reply-To: References: Message-ID: Gert Cuykens wrote: > rex2=re.compile('^"(?P[^]*)"$',re.M) > > File "/usr/lib/python2.5/re.py", line 180, in compile > return _compile(pattern, flags) > File "/usr/lib/python2.5/re.py", line 233, in _compile > raise error, v # invalid expression > sre_constants.error: unexpected end of regular expression > > ? You probably want rex2=re.compile('^"(?P[\^]*)"$',re.M) Because [] is a bracketed group and the ^ within a bracketed group is a negation, but you have negated nothing before closing the group. Alternatively: rex2=re.compile('^"(?P\^*)"$',re.M) Would have the same meaning, avoiding the bracketed group altogether. James From cliff at develix.com Sat Jan 13 16:18:24 2007 From: cliff at develix.com (Cliff Wells) Date: Sat, 13 Jan 2007 13:18:24 -0800 Subject: template engine In-Reply-To: References: <8764ba7oqf.fsf@gmail.com> Message-ID: <45A94CA0.3010604@develix.com> piotr wrote: > On Sat, 13 Jan 2007 16:42:16 -0200, Jorge Godoy wrote: > >> Take a look at Kid (http://www.kid-templating.org/) and Genshi >> (http://genshi.edgewall.org/). > > I've already done a short look at kid, but to be honest I don't like it's > XML/Python syntax. I strongly prefer idea from SimpleTAL or HTMLTemplates > where HTML and Python code are separated. > But syntax is for me not so important like functionality so maybe I have > to get back and look at kid again :) > > any other engines? :) Perhaps Breve might interest you: http://breve.twisty-industries.com Regards, Cliff From john.pye at gmail.com Sat Jan 6 17:32:58 2007 From: john.pye at gmail.com (John Pye) Date: 6 Jan 2007 14:32:58 -0800 Subject: Crash on Message-ID: <1168122778.304660.92870@q40g2000cwq.googlegroups.com> Hi all I have a unittest test suite that's testing a fairly large SWIG-wrapped application via Python. All my tests are passing at the moment, but when Python exits, I get the following (shown below). Could anyone please help me to understand what precisely this message means (other than that obviously I have made a mistake with object ownership or INCREF or DECREF somewhere), and what the best way of tracking down the source of the problem might be? Cheers JP ---------------------------------------------------------------------- Ran 63 tests in 3.269s OK python: Modules/gcmodule.c:275: visit_decref: Assertion `gc->gc.gc_refs != 0' failed. process killed by signal 6 program finished with exit code -1 From hayes.tyler at gmail.com Sun Jan 21 23:38:43 2007 From: hayes.tyler at gmail.com (Tyler) Date: 21 Jan 2007 20:38:43 -0800 Subject: Reading Fortran Data In-Reply-To: <1169437907.263295.64840@q2g2000cwa.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> <1169424273.929396.133880@m58g2000cwm.googlegroups.com> <1169429808.910298.10240@11g2000cwr.googlegroups.com> <1169433752.130978.133210@a75g2000cwd.googlegroups.com> <1169436377.634274.172460@s34g2000cwa.googlegroups.com> <1169437907.263295.64840@q2g2000cwa.googlegroups.com> Message-ID: <1169440723.665786.230210@m58g2000cwm.googlegroups.com> Wow! Thanks for the help everyone. I will look into each of your comments in more detail in the morning, but I'll mention a few things I guess. The first is, the list-directed output was not necesarily my choice as some of the code is also used by my supervisor (and her colleagues) and I had to keep the IO similar. However, for "non-legacy" codes (even though is was upgraded to Fortran90), I can ensure you that I will employ a more portable format. Also, I am very interested in the Scientific.IO module mentioned and will look into it further along with f2py. Once again, I thank all of you for your replies, I think I even learnt a few things about Fortran here too.... Cheers, t. From gibo at gentlemail.com Tue Jan 23 18:07:08 2007 From: gibo at gentlemail.com (GiBo) Date: Wed, 24 Jan 2007 12:07:08 +1300 Subject: How to instantiate a different class in a constructor? In-Reply-To: <1169563525.644251.118250@v45g2000cwv.googlegroups.com> References: <1169563525.644251.118250@v45g2000cwv.googlegroups.com> Message-ID: <45B6951C.4030100@gentlemail.com> Paul McGuire wrote: > On Jan 23, 5:09 am, GiBo wrote: >> Hi all, >> >> I have a class URI and a bunch of derived sub-classes for example >> HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is >> module urllib & friends, however my actual problem however maps very >> well to this example). >> >> Now I want to pass a string to constructor of URI() and get an instance >> of one of the subclasses back. For example uri=URI('http://abcd/...') >> will make 'uri' an instance of HttpURI class, not instance of URI. >> >> To achieve this I have a list of all subclasses of URI and try to >> instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI >> to HttpURI constructor it raises ValueError exception and I want to test >> HttpsURI, FtpURI, etc. >> >> For now I have this code: >> >> ===== >> class URI(object): >> def __new__(self, arg): >> for subclass in subclasses: >> try: >> instance = object.__new__(subclass, arg) >> return instance >> except ValueError, e: >> print "Ignoring: %s" % e >> raise ValueError("URI format not recognized" % arg) >> > > > > Call __new__ and subclass.__init__ explicitly: Thanks! That's it :-) BTW When is the subclass.__init__() method invoked if I don't explicitly call it from __new__()? Apparently not from baseclass.__new__() nor from object.__new__(). GiBo From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 3 14:01:26 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 03 Jan 2007 20:01:26 +0100 Subject: list/dictionary as case statement ? References: <71pmp2tq1klma5urhkfiv8bpq6u8sgtj06@4ax.com> <501r8sF1dp76aU1@mid.individual.net> <1167849556.429532.100990@48g2000cwx.googlegroups.com> Message-ID: <502cs6F1d5nvlU1@mid.individual.net> MRAB wrote: > I think that "PC" referred to the CPU's Program Counter. Argh, thanks. :) > The x86 CPUs if typical Windows PCs aren't RISC but Intel also > manufacture X-Scale (ARM core) processors which are. Okay, sorry for lack of precision. I was referring to x86. Regards, Bj?rn -- BOFH excuse #101: Collapsed Backbone From grflanagan at yahoo.co.uk Tue Jan 23 08:46:37 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 23 Jan 2007 05:46:37 -0800 Subject: Python on AIX required files Message-ID: <1169559996.970980.217600@l53g2000cwa.googlegroups.com> Hello Problem: I want to send a Python script to someone running AIX Unix but who can't (or won't) compile or otherwise install the Python interpreter. If I have compiled Python on the same version of AIX, what would I need to provide to the user to enable him to run the script? Thanks Gerard From __peter__ at web.de Thu Jan 11 07:46:08 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 Jan 2007 13:46:08 +0100 Subject: Type casting a base class to a derived one? References: Message-ID: Frederic Rentsch wrote: > If I derive a class from another one because I need a few extra > features, is there a way to promote the base class to the derived one > without having to make copies of all attributes? > > class Derived (Base): > def __init__ (self, base_object): > # ( copy all attributes ) > ... > > This looks expensive. Moreover __init__ () may not be available if it > needs to to something else. base_instance = Base(...) base_instance.__class__ = Derived Peter From macdev at artins.org Tue Jan 2 04:33:16 2007 From: macdev at artins.org (Ben Artin) Date: Tue, 02 Jan 2007 04:33:16 -0500 Subject: doctesting References: Message-ID: In article , belinda thom wrote: > I'd like to write a tester script that I can place in one place (say > ~/bin/python/tester.py) and then have it visible to me at the cmd- > line (by setting the path variable appropriately). I have had no > luck in getting it to work, however. > > It appears like the doctest code itself assumes that all modules to > be imported lie in some directory other than the one I invoked the > tester.py script from. In particular, simple imports in a .txt file > like: > > >>> import foo > > fail even though I've started the script in a directory that contains > file foo.py import foo looks at sys.path which is based on PYTHONPATH in the environment. So, one way to do what you want is to have your script modify sys.path before importing other modules. hth Ben -- If this message helped you, consider buying an item from my wish list: I changed my name: From gagsl-py at yahoo.com.ar Sun Jan 7 13:20:09 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 10:20:09 -0800 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: <1168194009.220437.286210@q40g2000cwq.googlegroups.com> On 7 ene, 13:22, "W. Watson" wrote: > >>>https://sourceforge.net/projects/pywin32/ > As I understand it, there are two files I'm after: 1. python interpreter, > and 2. a python editor. It's #2 that I'm having trouble downloading. The > link is broken. The above link should work. Follow the instructions in a previous post. Note that in the last step, you have to choose a mirror for downloading; that mirrow might be down or out-of-sync so you might get an error there. Choose another mirrorr... Note that you dont *need* PythonWin in order to use Python on Windows. The standard Python distribution works fine. Even includes a Python editor (IDLE) but you can use whichever editor you like to write your code (even Notepad...) -- Gabriel Genellina From gagsl-py at yahoo.com.ar Wed Jan 10 04:31:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Jan 2007 06:31:46 -0300 Subject: Question about compiling. In-Reply-To: References: Message-ID: <7.0.1.0.0.20070110062608.045ed6f0@yahoo.com.ar> At Tuesday 9/1/2007 14:56, Steven W. Orr wrote: >I *just* read the tutorial so please be gentle. I created a file called >fib.py which works very nicely thank you. When I run it it does what it's >supposed to do but I do not get a resulting .pyc file. The tutorial says I >shouldn't do anything special to create it. I have machines that have both >2.4.1 and 2.3.5. Does anyone have an idea what to do? Welcome to Python! When you run a script directly, no .pyc file is generated. Only when a module is imported (See section 6.1.2 on the tutorial). And don't worry about it... -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Thu Jan 11 08:31:07 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Jan 2007 14:31:07 +0100 Subject: sleep in asyncore References: <1168512761.621361.258180@o58g2000hsb.googlegroups.com> Message-ID: "billie" wrote: > I'm writing an authentication server by using asyncore / asynchat > modules. > I'd like to implement a basic brute-force protection by "freezing / > sleeping" the current client session for a period of time (e.g. 2 > seconds) when the user sends a wrong password. > Does someone knows a "trick" to do that with asyncore? this could work: add a timeout variable to your dispatcher instance, and have your "readable" method returns False if timeout is set and the current time is before the given value. then set the timeout value to time.time() + 2 when you see a bad pass- word. From robert.kern at gmail.com Mon Jan 22 15:14:59 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Jan 2007 14:14:59 -0600 Subject: Program eating memory, but only on one machine? (Solved, sort of) In-Reply-To: References: Message-ID: Per B.Sederberg wrote: > Per B.Sederberg princeton.edu> writes: > >> I'll see if I can make a really small example program that eats up memory on >> our cluster. That way we'll have something easy to work with. > > Now this is weird. I figured out the bug and it turned out that every time you > call numpy.setmember1d in the latest stable release of numpy it was using up a > ton of memory and never releasing it. Hmm. With a recent checkout from SVN, I don't see any memory increase. In [15]: from numpy import * In [16]: ar1 = arange(1000000) In [17]: ar2 = arange(3, 7) In [18]: import itertools In [19]: for i in itertools.count(1): ....: if not i % 1000: ....: print i ....: x = setmember1d(ar1, ar2) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nagle at animats.com Thu Jan 18 15:50:40 2007 From: nagle at animats.com (John Nagle) Date: Thu, 18 Jan 2007 20:50:40 GMT Subject: More M2Crypto issues In-Reply-To: References: Message-ID: Upgraded to Python 2.5 on the Linux system, rebuild M2Crypto, and it stil fails, but the last line of the error message changed to: ValueError: invalid literal for long() with base 10: '_40f91a08_p_SSL_CTX' Others have encountered this problem, from a Google search. Is "long" supposed to operate on C objects? John Nagle John Nagle wrote: > I've been running M2Crypto successfully using Python 2.4 on Windows 2000, > and now I'm trying to get it to work on Python 2.3.4 on Linux. > > Attempting to initialize a context results in > > Traceback (most recent call last): > File "/www/htdocs/sitetruth.com/cgi/ratingdetails.cgi", line 46, in ? > DetailsPageBuilder.detailspage(kdbfile,ktemplatefile,url) # check > and display domain or URL as web page > File "./sitetruth/DetailsPageBuilder.py", line 70, in detailspage > sitecert = InfoSSL2.Certificate(siteinfo, kverifylocations, verbose) > File "./sitetruth/InfoSSL2.py", line 147, in __init__ > self.ctx = createsslcontext(trustedcafile, verbose) # Generate > general SSL context > File "./sitetruth/InfoSSL2.py", line 40, in createsslcontext > ctx = SSL.Context('sslv3') # Create > context with SSL params > File "/home/sitetruth/lib/python/M2Crypto/SSL/Context.py", line 43, in > __init__ > map()[long(self.ctx)] = self > ValueError: invalid literal for long(): _480e1008_p_SSL_CTX > > which, when I look at the code and try some test cases, seems > legitimate. The cacheing code is trying to convert a reference to an > object (a C object, in fact) into a "long". Python 2.4 on Windows > will do that. Python 2.3.4 on Linux converts it to a string first, > gets "_480e1008_p_SSL_CTX", and then tries to convert that to an > integer, which fails. > > M2Crypto is supposed to work with Python 2.3, so this should work. > > John Nagle From gagsl-py at yahoo.com.ar Thu Jan 18 12:27:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 14:27:00 -0300 Subject: How to read and write huge binary files References: <1169136850.518228.103360@l53g2000cwa.googlegroups.com> Message-ID: "Lad" escribi? en el mensaje news:1169136850.518228.103360 at l53g2000cwa.googlegroups.com... > What is a good way to read binary data from HUGE file and write it > to another file? Without processing the data read? shutil.copy2 or similar Else, a lot of applications can follow the pattern read-process-write: read a logical block, process, write the output; where "logical block" depends on the application: a record, a frame, a chunk... -- Gabriel Genellina From Thomas.Ploch at gmx.net Tue Jan 9 10:02:51 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Tue, 09 Jan 2007 16:02:51 +0100 Subject: How to write temporary data to file? In-Reply-To: <45A3AD3E.1090500@gmx.net> References: <45A31767.9030404@gmx.net> <45A362EF.1080006@designaproduct.biz> <45A3AD3E.1090500@gmx.net> Message-ID: <45A3AE9B.4040002@gmx.net> Thomas Ploch schrieb: > Laszlo Nagy schrieb: >> Thomas Ploch ?rta: >>> Hi folks, >>> >>> I have a data structure that looks like this: >>> >>> d = { >>> 'url1': { >>> 'emails': ['a', 'b', 'c',...], >>> 'matches': ['d', 'e', 'f',...] >>> }, >>> 'url2': {... >>> } >>> >>> This dictionary will get _very_ big, so I want to write it somehow to a >>> file after it has grown to a certain size. >>> >>> How would I achieve that? >>> >> How about dbm/gdbm? Since urls are strings, you can store this dict in a >> database instance and actually use it from your program as it were a dict? >> >> Laszlo >> > > Well, but how do I save the nested dict values? I don't want to eval > them, so this is no option for me. > > Thomas I just saw shelve is the module to go for. Thomas From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 16:06:24 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 22:06:24 +0100 Subject: Why less emphasis on private data? In-Reply-To: <45a14b57$0$4248$4fafbaef@reader1.news.tin.it> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <45a0b4e3$0$19089$4fafbaef@reader4.news.tin.it> <45a12cb0$0$300$426a74cc@news.free.fr> <45a14b57$0$4248$4fafbaef@reader1.news.tin.it> Message-ID: <45a15a94$0$8403$426a74cc@news.free.fr> Andrea Griffini a ?crit : > Bruno Desthuilliers wrote: > > >> ... and on > >>> the opposite I didn't expect that fighting with object >>> leaking in complex python applications was that difficult >>> (I've heard of zope applications that just gave up and >>> resorted to the "reboot every now and then" solution). >>> >> Zope is a special case here, since it relies on an object database... > > > Just to clarify my post... I found by being punched myself > in the nose what does it mean to have a complex python > application that suffers from object leaking; it's not > something I only read about zope programs. > > But why zope applications would be a special case ? 1/ because of how Zope and the ZODB work 2/ because Zope is an unusually complex Python application. FWIW, I've never had any memory problem with other Python applications and/or frameworks I've used so far (ie: in the past seven years) - most of them being somewhat 'simpler' than if they had been implemented in C or C++... From gagsl-py at yahoo.com.ar Thu Jan 18 23:48:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 01:48:52 -0300 Subject: How to pass arguments to the function embedded in the timeit.Timer() In-Reply-To: References: Message-ID: <7.0.1.0.0.20070119013727.04059408@yahoo.com.ar> At Thursday 18/1/2007 21:31, Dongsheng Ruan wrote: > Does anybody know how to pass multiple arguments to the function >tested in timeit.timer() in >python? > >I googled and found how to pass one argument: > >x=10000 >mytime = timeit.Timer( setup="from Createlst import createlst", stmt= >"createlst(%s)"%(x) ) This is the % operator for strings, and it's general, not related to the timeit module. You can find it explained in almost every tutorial. The "official" tutorial explains it here: and for more detailed usage see here: If you haven't already done it, I strongly recommend reading the Python tutorial (you should find it inside your Python installation, and you can read it online at ) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From arkanes at gmail.com Thu Jan 11 17:01:25 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 11 Jan 2007 16:01:25 -0600 Subject: Python nuube needs Unicode help In-Reply-To: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> References: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> Message-ID: <4866bea60701111401y71810929l88650891fc166375@mail.gmail.com> On 11 Jan 2007 13:28:14 -0800, gheissenberger at gmail.com wrote: > HELP! > Guy who was here before me wrote a script to parse files in Python. > > Includes line: > print u > where u is a line from a file we are parsing. > However, we have started recieving data from Brazil. If I open file to > parse in VI, looks like: > > audio="313-20070102144528.wav" grammarSet="G3" rawText="não" > recValue="{data:CHOICE=NO;}" conf="970" rawText2="" conf2="0" > transcribedText="não" parsableText="não"/ > > Clearly those "nã" are some non-Ascii characters, but how do I get > print to understand that? > > I keep getting: > "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in > position 40: > ordinal not in range(128)" > Find out what encoding the files are in and modify the script to use it. From richie at entrian.com Fri Jan 19 16:18:17 2007 From: richie at entrian.com (Richie Hindle) Date: 19 Jan 2007 13:18:17 -0800 Subject: PyMeld for html templates? References: Message-ID: <1169241497.610167.130580@a75g2000cwd.googlegroups.com> [Sean] > I wonder if anyone has any thoughts on PyMeld as a template > system for churning out general websites? I'm doing that (but then I would be wouldn't I? 8-) http://www.mandant.net is an example - the content of each page comes from a file containing just the content, the layout and sidebar are defined in a template HTML file, and the navigation is built by a Python script. All that is pulled together using PyMeld into a set of HTML files and deployed to the web server (there's no need to it on the fly for that site, but you certainly could). > I want for a URI request to mysite.com/info > to pull in a layout.html template which will in turn be populated by > the info.html template. [...] how about PyMeld, any ideas on how > to do it or whether it will even work as I've described? You'd do something like this: from PyMeld import Meld LAYOUT = """The Title

The real title

Here is the info, which would in the real world be read from a file.

""" page = Meld(LAYOUT) info = Meld(INFO) page.title = info.title._content page.info = info.info._content print page Is that the sort of thing you had in mind? -- Richie Hindle richie at entrian.com From python at rcn.com Wed Jan 3 14:30:53 2007 From: python at rcn.com (Raymond Hettinger) Date: 3 Jan 2007 11:30:53 -0800 Subject: Sorting on multiple values, some ascending, some descending References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> Message-ID: <1167852652.416990.158610@k21g2000cwa.googlegroups.com> dwelden wrote: > I have successfully used the sort lambda construct described in > http://mail.python.org/pipermail/python-list/2006-April/377443.html. > However, how do I take it one step further such that some values can be > sorted ascending and others descending? Easy enough if the sort values > are numeric (just negate the value), but what about text? > > Is the only option to define an external sorting function to loop > through the list and perform the comparisons one value at a time? The simplest way is to take advantage of sort-stability and do successive sorts. For example, to sort by a primary key ascending and a secondary key decending: L.sort(key=lambda r: r.secondary, reverse=True) L.sort(key=lambda r: r.primary) A less general technique is to transform fields in a way that reverses their comparison order: L.sort(key=lambda r: (-r.age, r.height)) # sorts descending age and ascending height Raymond From ldo at geek-central.gen.new_zealand Fri Jan 5 01:30:17 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Jan 2007 19:30:17 +1300 Subject: Anyone persuaded by "merits of Lisp vs Python"? References: <1167324666.002153.27570@a3g2000cwd.googlegroups.com> <1167357838.969945.15190@48g2000cwx.googlegroups.com> Message-ID: In message , Paul Hummer wrote: > I learned PHP for ease of web application development ... PHP is great for easily developing _insecure_ web applications. But if you want them not to leak like a sieve, things get a bit more complicated. From robert.kern at gmail.com Mon Jan 8 06:06:47 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Jan 2007 05:06:47 -0600 Subject: Module to read svg In-Reply-To: <45a1f746$0$27874$9b622d9e@news.freenet.de> References: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> <45a1f746$0$27874$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > schpok at gmail.com schrieb: >> Does anyone know if there's an actual free implementation of this? > > For the dom module in it, xml.dom.minidom should work. Depending on > your processing needs, that might be sufficient. I don't think it quite fits what the OP is asking for. SVG defines some non-XML structure for some of its contents. For example: The OP is asking for a module that would parse the "points" attribute into a list: [(100.0, 200.0), (100.0, 100.0)] -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From S.Mientki-nospam at mailbox.kun.nl Tue Jan 2 17:08:31 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 02 Jan 2007 23:08:31 +0100 Subject: list/dictionary as case statement ? Message-ID: If I'm not mistaken, I read somewhere that you can use function-names/references in lists and/or dictionaries, but now I can't find it anymore. The idea is to build a simulator for some kind of micro controller (just as a general practise, I expect it too be very slow ;-). opcodes ={ 1: ('MOV', function1, ...), 2: ('ADD', function2, ), 3: ('MUL', class3.function3, ) } def function1 # do something complex Is this possible ? thanks, Stef Mientki From jorge.vargas at gmail.com Fri Jan 5 16:13:06 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Fri, 5 Jan 2007 17:13:06 -0400 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: <32822fe60701051313i2a06ede0j516eb092bf6ba4e7@mail.gmail.com> On 1/5/07, Stef Mientki wrote: if I undestand correctly this is what you want >>> class pin3: ... def __init__(self,name): ... self.Name = name ... def __str__(self): ... return self.Name ... >>> pin3() Traceback (most recent call last): File "", line 1, in ? TypeError: __init__() takes exactly 2 arguments (1 given) >>> pin3('aaa') <__main__.pin3 instance at 0xb7dc948c> >>> print pin3('aaa') aaa From could.net at gmail.com Fri Jan 26 04:54:05 2007 From: could.net at gmail.com (Frank Potter) Date: 26 Jan 2007 01:54:05 -0800 Subject: how to remove c++ comments from a cpp file? In-Reply-To: References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> Message-ID: <1169805244.879280.235660@v45g2000cwv.googlegroups.com> On Jan 26, 5:08 pm, Gary Herron wrote: > Frank Potter wrote: > > I only want to remove the comments which begin with "//". > > I did like this, but it doesn't work. > > > r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) > > f=file.open("mycpp.cpp","r") > > f=unicode(f,"utf8") > > r.sub(ur"",f) > > > Will somebody show me the right way? > > Thanks~~If you expect help with a problem, it would be nice if you told us what > the problem is. What error did you get? > > But even without that I see lots of errors: > > You must import re before you use it: > import re > > Open a file with open((..) not file.open(...). > > Once you open the file you must *read* the contents and operate on that: > data = f.read() > > Then you ought to close the file: > f.close() > > Now you can do your sub on the string in data -- but note, THIS WON'T > CHANGE data, but rather returns a new string which you must assign to > something: > > new_data = r.sub(ur"", data) > > Then do something with the new string. > > Also I fear your regular expression is incorrect. > > Cheers, > Gary Herron Thank you. I'm very sorry because I was in a hurry when I post this thread. I'll post again my code here: [CODE] import re f=open("show_btchina.user.js","r").read() f=unicode(f,"utf8") r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) f_new=r.sub(ur"",f) open("modified.js","w").write(f_new.encode("utf8")) [/CODE] And, the problem is, it seems that only the last comment is removed. How can I remove all of the comments, please? From noway at ask.me Sat Jan 20 07:57:27 2007 From: noway at ask.me (Giovanni Bajo) Date: Sat, 20 Jan 2007 13:57:27 +0100 Subject: PQueue and Python 2.5 In-Reply-To: <45B1EF03.9020406@v.loewis.de> References: <1169216890.617239.209170@51g2000cwl.googlegroups.com> <45B1EF03.9020406@v.loewis.de> Message-ID: On 20/01/2007 11.29, Martin v. L?wis wrote: >> I haven't got a clue how to investigate this, but I would be willing to >> help if someone has any ideas. > > There are a number of problems in this code; the most significant one is > the incorrect usage of memory management API. In pqueue_dealloc, the > call PyMem_DEL(pqp) should read PyObject_DEL(pqp), as the object was > allocated with PyObject_NEW. Because this was a common error once, > Python up to 2.4 detected that error and silently corrected it (at some > runtime cost); Python 2.5 now has removed this work-around. And by the way, this is also a FAQ: http://effbot.org/pyfaq/why-does-my-c-extension-suddenly-crash-under-2.5.htm and even explained in the Misc/NEWS of Python 2.5. -- Giovanni Bajo From rasmussen.bryan at gmail.com Thu Jan 4 02:39:09 2007 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Thu, 4 Jan 2007 08:39:09 +0100 Subject: MI5 Persecution: Counter-surveillance sweep by Nationwide Investigations Group In-Reply-To: References: Message-ID: <3bb44c6e0701032339o5752ff9ewadd4e8070277bd19@mail.gmail.com> >As I said above, I don't know very much > about these things, so I can't comment on the capabilities or otherwise of this equipment. >But clearly the "watchers" are using > technology which in 1994 was beyond the detection capabilities of a good private detective >agency. > Lisp did that 20 years ago. Cheers, Bryan Rasmussen From hg at nospam.org Tue Jan 16 10:47:50 2007 From: hg at nospam.org (hg) Date: Tue, 16 Jan 2007 16:47:50 +0100 Subject: Queue and signals References: Message-ID: hg wrote: > Hi, > > Is it legal to use Queue.put in a signal handle and Queue.get in the main > process (no thread) > > Thanks, > > hg PS: and if not is there a way to share data between a "main" and its signal in a safe way (write in signal and read in main) Thanks, hg From klaus at seistrup.dk Sat Jan 6 14:18:15 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 6 Jan 2007 19:18:15 +0000 (UTC) Subject: nntplib downloads content with extra linebreaks References: <1168110213.436860@sj-nntpcache-1.cisco.com> Message-ID: Rweth wrote: > I am using nntplib to download archived xml messages from our > internal newsgroup. This is working fine except the download > of files to the connected server, has extra embedded lines in > them (all over the place), from the > s.body(id,afile) # body method The 'linebreaks' are probably '\r\n' pairs, so you could do a buf.replace('\r\n', '\n') to convert all such pairs to single LFs (buf being the buffer or string that holds the text with 'linebreaks'). Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From ldo at geek-central.gen.new_zealand Fri Jan 5 01:28:21 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Jan 2007 19:28:21 +1300 Subject: Anyone persuaded by "merits of Lisp vs Python"? References: <1167324666.002153.27570@a3g2000cwd.googlegroups.com> <1167459454.002991.64260@48g2000cwx.googlegroups.com> Message-ID: In message <1167459454.002991.64260 at 48g2000cwx.googlegroups.com>, xscottg at gmail.com wrote: > [3] I thought it was particularly cool how Tcl could bolt on a class > based object oriented system as a library. The word "class" isn't > built into the language, but that kind of evaluator lets you add it. I have written about two notrivial scripts in Tcl. I don't think I will ever bother to write another, particularly since I now know Python. Dealing with arrays is an absolute pain, because the language doesn't have references and arrays as first-class objects. From rmcore at gmail.com Tue Jan 23 17:20:52 2007 From: rmcore at gmail.com (Michael Bentley) Date: Tue, 23 Jan 2007 16:20:52 -0600 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: Message-ID: On Jan 23, 2007, at 4:01 PM, Daniel Jonsson wrote: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! > > Daniel Don't forget PyGTK (http://www.pygtk.org), and Tkinter! You should really try them all out and make your own decision, IMHO. I'm actually using pyobjc for my work, but if I had to support other environments, I'd be using PyGTK. (Although I *was* happy with PyQt (3) when I was using it). From Thomas.Ploch at gmx.net Mon Jan 8 23:17:43 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Tue, 09 Jan 2007 05:17:43 +0100 Subject: How to write temporary data to file? Message-ID: <45A31767.9030404@gmx.net> Hi folks, I have a data structure that looks like this: d = { 'url1': { 'emails': ['a', 'b', 'c',...], 'matches': ['d', 'e', 'f',...] }, 'url2': {... } This dictionary will get _very_ big, so I want to write it somehow to a file after it has grown to a certain size. How would I achieve that? Thanks, Thomas From horpner at yahoo.com Tue Jan 16 09:40:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Jan 2007 15:40:55 +0100 Subject: Regular expressions question References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> <1168957361.204348.30080@s34g2000cwa.googlegroups.com> Message-ID: On 2007-01-16, Victor Polukcht wrote: > Actually, i'm trying to get the values of first field (Global) , fourth > (200, 4), and fifth (100%) and sixth (100%). > > Everything except fourth is simple. >>> g = "Global etsi3 * 4 ok 30 100% 100% Outgoing" >>> import re >>> r = re.search('\*\s+(\d+)', g) >>> r.group() '* 4' >>> r.group(1) '4' -- Neil Cerutti We're not afraid of challenges. It's like we always say: If you want to go out in the rain, be prepared to get burned. --Brazillian soccer player From hancock at anansispaceworks.com Fri Jan 26 12:23:19 2007 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 26 Jan 2007 11:23:19 -0600 Subject: Thoughts on using isinstance In-Reply-To: <45b7b7ba$0$391$426a74cc@news.free.fr> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> <45b7b7ba$0$391$426a74cc@news.free.fr> Message-ID: <45BA3907.1000306@anansispaceworks.com> Bruno Desthuilliers wrote: > abcd a ?crit : > >>Well my example function was simply taking a string and printing, but >>most of my cases would be expecting a list, dictionary or some other >>custom object. Still propose not to validate the type of data being >>passed in? > > > Yes - unless you have a *very* compelling reason to do otherwise. Some compelling reasons: 1) Some action of the function is irreversible (for example, deletion of data) 2) The function will get many wrong parameters in normal use, and the function's action is expensive (disk accesses, re-writing flash memory, fetching things from remote servers, whatever) 3) The inputs are from a web form or other insecure source, and you want to reduce the number of unexpected cases you have to deal with. (proof against error is not the same as proof against deliberate malice) 4) The function DOESN'T fail with a certain wrong parameter, but instead does something it shouldn't. Catch the failing case and deal with it, or if there are many, insist on the successful case. Even when you do have to validate, it usually promotes flexibility of the code to check for functionality (e.g. presence of necessary methods) rather than specific inheritence. Using "isinstance" is one of those practices that can really help in quick testbed code or in a prototype, but you usually want to take it out later. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From toby at tobiah.org Mon Jan 22 20:52:32 2007 From: toby at tobiah.org (Tobiah) Date: Mon, 22 Jan 2007 17:52:32 -0800 Subject: AES and Credit card number encryption In-Reply-To: <7xy7nu4ubj.fsf@ruckus.brouhaha.com> References: <45b5159e$0$24377$88260bb3@free.teranews.com> <7xy7nu4ubj.fsf@ruckus.brouhaha.com> Message-ID: <45b55d8b$0$24450$88260bb3@free.teranews.com> Paul Rubin wrote: > Tobiah writes: >> I browsed this subject and thought I might use the 'AES' cypher >> scheme to do this. Would this be a good choice? > > There's more to it than that, but yes, AES is a good underlying > algorithm. Looking at the problem further, I am getting the idea that PGP, or GPG (Asymetric encryption) would be better, because then all of the software that has to *write* CC numbers, would not have to access the 'secret' key. You see we have to write the number often, but almost always only have to access (read) a masked number (4232********3435). PGP sounds great, but it seems like a huge subject to cover in a day or two. Is there a nice module for python that would let me do the most usual operations easily? I just want to make a key, hide it, and the use the public key to encrypt all future and past credit card numbers. -- Posted via a free Usenet account from http://www.teranews.com From enleverlesX.XmcX at XmclaveauX.com Wed Jan 17 09:29:25 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Wed, 17 Jan 2007 15:29:25 +0100 Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: <45ae32d0$0$27387$ba4acef3@news.orange.fr> Hi! r=iter(range(9)) print zip(r,r,r) But, it's few like Peter... -- Michel Claveau From wccppp at gmail.com Thu Jan 4 12:27:09 2007 From: wccppp at gmail.com (wcc) Date: 4 Jan 2007 09:27:09 -0800 Subject: question on creating class In-Reply-To: <1167895677.041759.230190@42g2000cwt.googlegroups.com> References: <1167895677.041759.230190@42g2000cwt.googlegroups.com> Message-ID: <1167931629.303805.158810@s34g2000cwa.googlegroups.com> Thanks for all replies. I'll just to have to figure our which suggested method I should use. To answer Jussi's question, this is why I asked the question. I have the book by Mark: Python Programming on Win32. In Charpter 12: Advanced Python and COM there is a sample code named: DynamicPolicy.py. It can be used to expose all methods from a python module to a COM server which can be accessed later from other languages, say VBA. It works great. There are quite a few modules that I want to implement a COM server for. One of the step to create the COM server is to define a class. Instead of revising this code for each module, I wondered if I can create mutilple COM servers in one program. I'll pass a module name and the corresponding class name to some function (to be written), and the class will be created. Btw, I'm novice to all this, hopefully my explanation isn't way off. Thank to all again. -- wcc From cibonac at gmail.com Thu Jan 11 09:17:30 2007 From: cibonac at gmail.com (new) Date: 11 Jan 2007 06:17:30 -0800 Subject: What about this? Message-ID: <1168525050.536736.74590@i39g2000hsf.googlegroups.com> www.magicoz.com amazing From gagsl-py at yahoo.com.ar Wed Jan 10 23:27:38 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 01:27:38 -0300 Subject: Universal Feed Parser - How do I keep attributes? In-Reply-To: <1168450723.340213.235690@o58g2000hsb.googlegroups.com> References: <1168450723.340213.235690@o58g2000hsb.googlegroups.com> Message-ID: <7.0.1.0.0.20070111012646.03f5bdb8@yahoo.com.ar> At Wednesday 10/1/2007 14:38, snewman18 at gmail.com wrote: > >>> d = feedparser.parse('http://weather.yahooapis.com/forecastrss?p=94089') > >>> d.feed.yweather_location >u'' You have to feed it the *contents* of the page, not its URL. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From codecraig at gmail.com Wed Jan 24 07:38:30 2007 From: codecraig at gmail.com (abcd) Date: 24 Jan 2007 04:38:30 -0800 Subject: Thoughts on using isinstance Message-ID: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> In my code I am debating whether or not to validate the types of data being passed to my functions. For example def sayHello(self, name): if not name: rasie "name can't be null" if not isinstance(name, str): raise "name must be a string" print "Hello " + name Is the use of isinstance a "bad" way of doing things? is it a "heavy" operation? for example, if I use this in each function validate input will it slow things down a lot? just curious how you might handle this type of situation (other than not validating at all). thanks From grante at visi.com Fri Jan 5 10:48:14 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 15:48:14 -0000 Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <12psqqk75ij5ta5@corp.supernews.com> <1168011416.291950.286500@s80g2000cwa.googlegroups.com> Message-ID: <12psspukvim83bb@corp.supernews.com> On 2007-01-05, king kikapu wrote: >> Under Windows, I ususally use py2exe+inno-setup. > > Xmmm...i have downloaded this and try a (very) simple project > and it is working great. Of your experience, does it also > working great when you have more complex solutions, > e.x. many 3rd party modules like wxWidgets and so ?? Yes. I use it to deply wxPython apps that use a lot of third party packages like pyserial, numpy, scipy, scientific python, pygnuplot, plotlib. The resulting setup.exe files seem awfully large to somebody who cut his teeth on Unix Version 7 on a PDP-11 with 256KB of RAM and a 20MB hard drive (and who still writes programs for platforms with 256 bytes of RAM). But, by windows standards they're not all that large. Nobody cares anymore that a program won't fit on a floppy disk... -- Grant Edwards grante Yow! I think my CAREER at is RUINED!! visi.com From roopesh.raj at gmail.com Wed Jan 17 09:13:22 2007 From: roopesh.raj at gmail.com (Roopesh) Date: 17 Jan 2007 06:13:22 -0800 Subject: IMAP SEARCH Error Message-ID: <1169043202.521317.226910@q2g2000cwa.googlegroups.com> I am using the imaplib to fetch mails. There is an error thrown in the search function, which I am not able to comprehend. My program is as follows : ==================== import imaplib M = imaplib.IMAP4("10.1.1.1",1143) M.login("roopesh", "roopesh12") type, data = M.select("INBOX", 1) print type, data print M.status("INBOX", '(MESSAGES UNSEEN RECENT)') typ, data = M.search(None, '(ALL)') print typ, data for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data[0][1]) M.close() M.logout() And the OUTPUT in the console is as follows : ================================== OK ['24'] ('OK', ['INBOX ( MESSAGES 24 UNSEEN 0 RECENT 0)']) Traceback (most recent call last): File "imap_test1.py", line 10, in ? typ, data = M.search(None, '(ALL)') File "c:\python24\lib\imaplib.py", line 602, in search typ, dat = self._simple_command(name, *criteria) File "c:\python24\lib\imaplib.py", line 1028, in _simple_command return self._command_complete(name, self._command(name, *args)) File "c:\python24\lib\imaplib.py", line 860, in _command_complete raise self.abort('command: %s => %s' % (name, val)) imaplib.abort: command: SEARCH => unexpected response: '*' Can anyone tell me why this happens ? Regards Roopesh From libintr at gmail.com Sat Jan 13 21:49:16 2007 From: libintr at gmail.com (lee) Date: 13 Jan 2007 18:49:16 -0800 Subject: indentation in python Message-ID: <1168742956.828457.287610@m58g2000cwm.googlegroups.com> Can anyone tell me the basics about indentation in python......how we use it in loops and constructs..etc.... From jura.grozni at gmail.com Mon Jan 29 16:50:03 2007 From: jura.grozni at gmail.com (azrael) Date: 29 Jan 2007 13:50:03 -0800 Subject: Data structure and algorithms In-Reply-To: <1170095416.261460.157660@a34g2000cwb.googlegroups.com> References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> <1170095416.261460.157660@a34g2000cwb.googlegroups.com> Message-ID: <1170107403.836795.211280@k78g2000cwa.googlegroups.com> thanks guys. i see that there is no way then to go back to C to satisfy my prof and get a grade From steve at REMOVE.THIS.cybersource.com.au Sat Jan 6 02:57:44 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 06 Jan 2007 18:57:44 +1100 Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> <1168012877.398078.59120@s80g2000cwa.googlegroups.com> Message-ID: On Fri, 05 Jan 2007 08:01:17 -0800, Michele Simionato wrote: > king kikapu wrote: >> > > Are they embarassed by their code? >> >> hehehe...no, just worried about stealing their ideas... > > I believe that shipping just the bytecode is a pretty effective way to > stop 99% of programmers from > reading your code. Yes, in theory they could decompile it, but in > practice, programmers are lazy. 99% of programmers won't read the code if you ship the source. > Look, I am so lazy that usually I don't read the source code, even if > it is there in plain! Exactly. -- Steven. From stever at cruzio.com Thu Jan 25 20:13:25 2007 From: stever at cruzio.com (Steve) Date: 25 Jan 2007 17:13:25 -0800 Subject: Pyparsing - Dealing with a Blank Value Message-ID: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> Hi All, I've picked up the PyParsing module and am trying to figure out how to do a simple parsing of some HTML source code. My specific problem is dealing with an element that is blank. from pyparsing import * import sys integer = Word("0123456789") trStart = Literal("").suppress() trEnd = Literal("").suppress() tdStart = Literal("").suppress() tdEnd = Literal("").suppress() #dataItem = Word(alphas) BlankItem = Word('') dataItem = Word(alphanums + " " + "," + ":") # works with spaces in data MultiItem = Optional(OneOrMore(dataItem)) TestLine = ['GroupYearCity', 'AAA1992Los Angeles', 'BBB2007Santa Cruz', '2001Santa Cruz'] htmlLine = trStart + tdStart + MultiItem.setResultsName('status') + tdEnd + tdStart + MultiItem.setResultsName('year') + tdEnd + tdStart + MultiItem.setResultsName('title') + tdEnd + trEnd for CurrentLine in TestLine: print 'Line = ', CurrentLine for srvrtokens,startloc,endloc in htmlLine.scanString( CurrentLine ): print 'tokens = %s %d %d \n' % (srvrtokens, startloc,endloc) Output : Line = GroupYearCity tokens = ['Group', 'Year', 'City'] 0 49 Line = AAA1992Los Angeles tokens = ['AAA', '1992', 'Los Angeles'] 0 54 Line = BBB2007Santa Cruz tokens = ['BBB', '2007', 'Santa Cruz'] 0 53 *** Blank 1st element - only shows 2 elements - need 3 elements to be consistent *** Line = 2001Santa Cruz tokens = ['2001', 'Santa Cruz'] 0 50 Any assistance would be greatly appreciated! Steve From alexisbrion at gmail.com Fri Jan 5 09:55:52 2007 From: alexisbrion at gmail.com (alex) Date: 5 Jan 2007 06:55:52 -0800 Subject: How to get file name on a remote server with ftplib? Message-ID: <1168008952.020516.130890@s80g2000cwa.googlegroups.com> Hello, My script is trying to get a file from a remote server, every day it ftps from a directory. My code works perfect if I know the name of the file in the remote directory. ftp.retrbinary('RETR ' + filename, handleDownload) The problem is that in the future the name of the file is going to be aleatory. How can I get the file's name (only one file is in that directory) and store it in a variable before executing ftp.retrbinary? Thanks a lot for your help, Alex From martin at v.loewis.de Sat Jan 6 03:30:12 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 06 Jan 2007 09:30:12 +0100 Subject: Newbie XML SAX Parsing: How do I ignore an invalid token? In-Reply-To: <1168054226.290465.325910@s34g2000cwa.googlegroups.com> References: <1168033818.692201.183790@11g2000cwr.googlegroups.com> <1168054226.290465.325910@s34g2000cwa.googlegroups.com> Message-ID: <459f5e14$0$17107$9b622d9e@news.freenet.de> scott at crybabymaternity.com schrieb: > My original posting has a funky line break character (it appears as an > ascii square) that blows up my program, but it may or may not show up > when you view my message. Looking at your document, it seems that this "funky line break character" is character \x1E, which, in latin-1, means "record separator". It's indeed ill-formed to use it in XML. > Is there a way to account for the invalid token in the error handler? Not with a standard XML parser, no. The error you describe is a "fatal error", and that's not something parsing can recover from. I recommend that you filter this character out before passing it to the XML parser. You can use the IncrementalParser interface to do so. Regards, Martin From could.net at gmail.com Sat Jan 27 06:18:47 2007 From: could.net at gmail.com (Frank Potter) Date: 27 Jan 2007 03:18:47 -0800 Subject: extracting from web pages but got disordered words sometimes Message-ID: <1169896727.567159.239160@a34g2000cwb.googlegroups.com> There are ten web pages I want to deal with. from http://www.af.shejis.com/new_lw/html/125926.shtml to http://www.af.shejis.com/new_lw/html/125936.shtml Each of them uses the charset of Chinese "gb2312", and firefox displays all of them in the right form, that's readable Chinese. My job is, I get every page and extract the html title of it and dispaly the title on linux shell Termial. And, my problem is, to some page, I get human readable title(that's in Chinese), but to other pages, I got disordered word. Since each page has the same charset, I don't know why I can't get every title in the same way. Here's my python code, get_title.py : [CODE] #!/usr/bin/python import urllib2 from BeautifulSoup import BeautifulSoup min_page=125926 max_page=125936 def make_page_url(page_index): return ur"".join([ur"http://www.af.shejis.com/new_lw/ html/",str(page_index),ur".shtml"]) def get_page_title(page_index): url=make_page_url(page_index) print "now getting: ", url user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers={'User-Agent':user_agent} req=urllib2.Request(url,None,headers) response=urllib2.urlopen(req) #print response.info() page=response.read() #extract tile by beautiful soup soup=BeautifulSoup(page) full_title=str(soup.html.head.title.string) #title is in the format of "title --title" #use this code to delete the "--" and the duplicate title title=full_title[full_title.rfind('-')+1::] return title for i in xrange(min_page,max_page): print get_page_title(i) [/CODE] Will somebody please help me out? Thanks in advance. From horpner at yahoo.com Wed Jan 3 13:27:01 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 3 Jan 2007 19:27:01 +0100 Subject: array of class / code optimization References: <6UPmh.6785$hr3.92@newsfe24.lga> <4MQmh.145$jr6.14@read3.inet.fi> Message-ID: On 2007-01-03, Jussi Salmela wrote: > hg kirjoitti: >> mm wrote: >> >>> Yes, it was the (), equivalent to thiks like new() create new object >>> from class xy. >>>> s1.append(Word) >>> s1.append(Word()) >>> >>> But I was looking for a "struct" equivalent like in c/c++. >>> And/or "union". I can't find it. >>> >>> Maybe you know a source (URL) "Python for c/c++ programmers" or things >>> like that. >>> >>> >>> Yes, I konw whats an object is... >> >> >> A struct in C is unrelated to a struct in C++ as a struct in C++ _is_ a >> class. >> >> >> hg > > What does your sentence mean, exactly? If I take a C file xyz.c > containing a struct definition S, say, rename it to be xyz.cpp > and feed it to a C++ compiler, the S sure remains a struct and > the C++ compiler has no difficulty in handling it as a struct, > so ?!? That's true. But it's also true that struct foo { int x, y; }; is exactly equivalent to: class foo { public: int x, y; }; The only difference between struct and class in C++ is the default access specification of its members. -- Neil Cerutti For those of you who have children and don't know it, we have a nursery downstairs. --Church Bulletin Blooper From omniflex at mail.ru Sat Jan 20 08:05:31 2007 From: omniflex at mail.ru (Alex) Date: Sat, 20 Jan 2007 15:05:31 +0200 Subject: Match 2 words in a line of file In-Reply-To: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> Message-ID: <1212885112.20070120150531@mail.ru> egc> how do i write a regexp for this.. or better yet shd i even be using egc> regexp or is there a better way to do this.... "A team of engineers were faced with a problem; they decided to handle it with regular expressions. Now they had two problems" Regular expressions are not always the best solution. Others have pointed out how it can work with "if word in line", this approach will do if you're dealing with simple cases. Take a look at this discussion, it is very informative: http://blogs.msdn.com/oldnewthing/archive/2006/05/22/603788.aspx From joshua at eeinternet.com Sat Jan 20 14:24:52 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Sat, 20 Jan 2007 10:24:52 -0900 Subject: how to mimik a main() function to start a program with entry point? References: Message-ID: <45b25fda$0$24352$88260bb3@free.teranews.com> krishnakant Mane wrote: > hello all. > I have one simple query and may be that's to stupid to answer but I am > not finding the answer any ways. > I have a set of modules in my package and out if which one is my > actual starting point to my entire program. say for example I have an > entire database application ready and I want a main (as in java or c) > to initiate the program and may be bring up a login screen and then > pass the control on to the main window. > if I am giving raw source code that is easy because I will tell user > to run the command ./xyz.py which has that function. > but if I freze it into an executable with py2exe for example , how do > I solve this problem? > thanks. > Krishnakant. See http://www.artima.com/weblogs/viewpost.jsp?thread=4829 by GvR himself. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From robert.kern at gmail.com Tue Jan 9 14:44:34 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 13:44:34 -0600 Subject: distutils and ctypes In-Reply-To: References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> Message-ID: Robert Kern wrote: > jtravs at gmail.com wrote: > >> So finally, my question is, is there a way to get distutils to simply >> build a shared library on windows so that I can use ctypes with them??? > > Not out-of-box, no. The OOF2 project has added a bdist_shlib command which > should do most of what you want, though. It's somewhat UNIX-oriented, and I > think it tries to install the shared library to a standard location (e.g. > /usr/local/lib). You might want to modify it to install the shared library in > the package so it is easy to locate at runtime. > > http://www.ctcms.nist.gov/oof/oof2/ > http://www.ctcms.nist.gov/oof/oof2/source/oof2-2.0.1.tar.gz > > The code is in the shlib/ subdirectory. And if you do so, please let us know about it! This would be quite useful for many other ctypes-using projects. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py at yahoo.com.ar Thu Jan 25 22:10:20 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Jan 2007 00:10:20 -0300 Subject: Http listener In-Reply-To: <1169778746.893177.20730@v33g2000cwv.googlegroups.com> References: <1169778746.893177.20730@v33g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070126000855.047c1930@yahoo.com.ar> At Thursday 25/1/2007 23:32, elrondrules at gmail.com wrote: >Am trying to find any resources that helps me to do write the Http >Listener.. Use SimpleHTTPServer; see its source code for an example. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From wolfson at gmail.com Wed Jan 24 00:24:52 2007 From: wolfson at gmail.com (Ben Wolfson) Date: Tue, 23 Jan 2007 21:24:52 -0800 Subject: sqlite user-defined functions & unicode issue Message-ID: <6282abf10701232124k7e0d5d80j3bda7e71bfe89d64@mail.gmail.com> I've got a db some of whose elements have been created automatically from filesystem data (whose encoding is iso-8859-1). If I try to select one of those elements using a standard SQL construct, things work fine: >>> sqlite.register_converter("text", unicode) >>> db = sqlite.connect(".mdb/database", detect_types=sqlite.PARSE_COLNAMES) >>> cursor = db.cursor() >>> cursor.execute("SELECT * FROM artists WHERE name LIKE ?", ("John Butcher%",)).fetchall() [(1653, u'John Butcher & Eddie Pr\xe9vost')] >>> But if I use the pysqlite recipe for searching with a regexp, things don't work: >>> db.create_function("regexp", 2, regexp) >>> cursor.execute("SELECT * FROM artists WHERE REGEXP(?, name)", ('John Butcher',)).fetchall() Traceback (most recent call last): File "", line 1, in -toplevel- cursor.execute("SELECT * FROM artists WHERE REGEXP(?, name)", ('John Butcher',)).fetchall() OperationalError: user-defined function raised exception >>> Testing reveals that "item" is passed as None: >>> def regexp(expr, item): if item is None: return False r = re.compile(expr, re.I) return r.search(item) is not None >>> db = sqlite.connect(".mdb/database", detect_types=sqlite.PARSE_COLNAMES) >>> db.create_function("regexp", 2, regexp) >>> cursor.execute("SELECT * FROM artists WHERE REGEXP(?, name)", ('John Butcher',)).fetchall() [] >>> How can I get around this? I really want to be able to search by regexp, and not just the standard SQL %-pattern. -- Ben Wolfson "However, identifying what we call 'time' or even 'space', which I shall mention soon, is a very difficult problem, and a philosopher would say that it is an extremely annoying subject." (Soseki Natsume, "The Philosophical Foundations of Literature") From tim.one at comcast.net Wed Jan 10 22:44:54 2007 From: tim.one at comcast.net (Tim Peters) Date: Wed, 10 Jan 2007 21:44:54 -0600 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: [Tim Peters] ... >> Huh. I don't read it that way. If it said "numbers can be ..." I >> might, but reading that way seems to requires effort to overlook the >> "decimal" in "decimal numbers can be ...". [Nick Maclaren] > I wouldn't expect YOU to read it that way, Of course I meant "putting myself in others' shoes, I don't ...". > but I can assure you from experience that many people do. Sure. Possibly even most. Short of writing a long & gentle tutorial, can that be improved? Alas, most people wouldn't read that either <0.5 wink>. > What it MEANS is "Numbers with a short representation in decimal "short" is a red herring here: Python's Decimal constructor ignores the precision setting, retaining all the digits you give. For example, if you pass a string with a million decimal digits, you'll end up with a very fat Decimal instance -- no info is lost. > can be represented exactly in decimal arithmetic", which is > tautologous. What they READ it to mean is "One advantage of > representing numbers in decimal is that they can be represented > exactly", and they then assume that also applies to pi, sqrt(2), > 1/3 .... > > The point is that the "decimal" could apply equally well to the > external or internal representation and, if you aren't fairly > clued-up in this area, it is easy to choose the wrong one. Worse, I expect most people have no real idea of that there's a possible difference between internal and external representations. This is often given as a selling point for decimal arithmetic: it's WYSIWYG in ways binary fp can't be (short of inventing power-of-2 fp representations for I/O, which few people would use). [attribution lost] >>>>> and how is decimal no better than binary? [Tim] >>>> Basically, they both lose info when rounding does occur. For >>>> example, [Nick] >>> Yes, but there are two ways in which binary is superior. Let's >>> skip the superior 'smoothness', as being too arcane an issue for >>> this group, >> With 28 decimal digits used by default, few apps would care about >> this anyway. > Were you in the computer arithmetic area during the "base wars" of the > 1960s and 1970s that culminated with binary winning out? Yes, although I came in on the tail end of that and never actually used a non-binary machine. > A lot of very well-respected numerical analysts said that larger bases > led to a faster build-up of error (independent of the precision). My > limited investigations indicated that there was SOME truth in that, > but it wasn't a major matter; I never say the matter settled > definitively. My point was that 28 decimal digits of precision is far greater than supplied even by 64-bit binary floats today (let alone the smaller sizes in most-common use back in the 60s and 70s). "Pollution" of low-order bits is far less of a real concern when there are some number of low- order bits you don't care about at all. >>> and deal with the other. In binary, calculating the mid-point >>> of two numbers (a very common operation) is guaranteed to be within >>> the range defined by those numbers, or to over/under-flow. >>> >>> Neither (x+y)/2.0 nor (x/2.0+y/2.0) are necessarily within the range >>> (x,y) in decimal, even for the most respectable values of x and y. >>> This was a MAJOR "gotcha" in the days before binary became standard, >>> and will clearly return with decimal. >> I view this as being an instance of "lose info when rounding does >> occur". For example, > No, absolutely NOT! Of course it is. If there were no rounding errors, the computed result would be exactly right -- that's darned near tautological too. You snipped the examples I gave showing exactly where and how rounding error created the problems in (x+y)/2 and x/2+y/2 for some specific values of x and y using decimal arithmetic. If you don't like those examples, supply your own, and if you get a similarly surprising result you'll find rounding error(s) occur(s) in yours too. It so happens that rounding errors in binary fp can't lead to the same counterintuitive /outcome/, essentially because x+x == y+y implies x == y in base 2 fp, which is indeed a bit of magic specific to base 2. The fact that there /do/ exist fp x and y such that x != y yet x+x == y+y in bases > 2 is entirely due to fp rounding error losing info. > This is an orthogonal matter, Disagree. > and is about the loss of an important invariant when using any base > above 2. It is that. > Back in the days when there were multiple bases, virtually every > programmer who wrote large numerical code got caught by it at least > once, and many got caught several times (it has multiple guises). > For example, take the following algorithm for binary chop: > > while 1 : > c = (a+b)/2 > if f(x) < y : > if c == b : > break > b = c > else : > if c == a : > break > a = c > > That works in binary, but in no base above 2 (assuming that I haven't > made a stupid error writing it down). In THAT case, it is easy to fix > for decimal, but there are ways that it can show up that can be quite > tricky to fix. If you know a < b, doing c = a + (b-a)/2 instead of c = (a+b)/2 at least guarantees (ignoring possible overflow) a <= c <= b. As shown last time, it's not even always the case that (x+x)/2 == x in decimal fp (or in any fp base > 2, for that matter). From steve at holdenweb.com Thu Jan 11 17:53:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Jan 2007 22:53:23 +0000 Subject: How much slower is dict indexing vs. list indexing? In-Reply-To: <1168555253.601611.258600@k58g2000hse.googlegroups.com> References: <1168555253.601611.258600@k58g2000hse.googlegroups.com> Message-ID: Emin wrote: > Dear Experts, > > How much slower is dict indexing vs. list indexing (or indexing into a > numpy array)? I realize that looking up a value in a dict should be > constant time, but does anyone have a sense of what the overhead will > be in doing a dict lookup vs. indexing into a list? Some ad hoc tests > I've done indicate that the overhead is less than 15% (i.e., dict > lookups seem to take no more than 15% longer than indexing into a list > and there doesn't seem to be much difference in indexing into a list > vs. a numpy array). > > The reason I ask is because I'm wondering how hard I should work to > compute and store an index into a list to avoid repeated hash table > lookups. From my tests, it looks like the answer is basically "don't > bother". Does anyone have information, thoughts, or comments on this? > I think "don't bother" is a good conclusion. Tim Peters has led the charge to (as he might put it) "optimize the snot" out of the dict implementation. Anything you do in Python to speed up access is likely to add more to execution time than you might save by not exercising the C-based dict lookup code. What technique were you thinking of to look up the cached index values in Python, just as a matter of curiosity? Storing them in a dict? It would be hard to think of a faster way ... ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From phd at phd.pp.ru Mon Jan 22 13:22:42 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Mon, 22 Jan 2007 21:22:42 +0300 Subject: SQLObject 0.8.0b2 Message-ID: <20070122182242.GF8012@phd.pp.ru> Hello! I'm pleased to announce the 0.8.0b2 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.0b2 News and changes: http://sqlobject.org/devel/News.html What's New ========== News since 0.8.0b1 ------------------ * Another round of bugfixes for MySQL errors 2006 and 2013 (SERVER_GONE, SERVER_LOST). * Fixed a bug in MSSQLConnection caused by column names being unicode. * Fixed a bug in FirebirdConnection caused by column names having trailing spaces. * Remove a leading slash in FirebirdConnection. For a more complete list, please see the news: http://sqlobject.org/devel/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From bearophileHUGS at lycos.com Tue Jan 16 16:25:06 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Jan 2007 13:25:06 -0800 Subject: A note on heapq module In-Reply-To: <45ad0f6c$1@nntp0.pdx.net> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <45ad0f6c$1@nntp0.pdx.net> Message-ID: <1168982702.903306.152940@m58g2000cwm.googlegroups.com> Scott David Daniels: > I'd suggest some changes. It is nice to have Heaps with equal > contents equal no matter what order the inserts have been done. > Consider how you want Heap([1, 2, 3]) and Heap([3, 1, 2]) to behave. > Similarly, it is nice to have str and repr produce canonical > representations (I would skip the __str__ code, myself, though). > Also, subclasses should get their identities tweaked as so: My version was a *raw* one, just an idea, this is a bit better: http://rafb.net/p/nLPPjo35.html I like your changes. In the beginning I didn't want to put __eq__ __ne__ methods at all, because they are too much slow, but being them O(n ln n) I think your solution is acceptable. Some methods may have a name different from the heap functions: def smallest(self): def push(self, item): def pop(self): def replace(self, item): Two things left I can see: I think the __init__ may have a boolean inplace parameter to avoid copying the given list, so this class is about as fast as the original heapify function (but maybe such thing is too much dirty for a Python stdlib): def __init__(self, sequence=None, inplace=False): if sequence is None: self._heap = [] elif isinstance(sequence, self.__class__): self._heap = sequence._heap[:] else: if inplace and isinstance(sequence, list): self._heap = sequence else: self._heap = list(sequence) heapify(self._heap) The second thing, I don't like much the __iter__ because it yields unsorted items: def __iter__(self): return self._heap.__iter__() Is this good? I think this can be accepted. Thank you, bye, bearophile From mikael at isy.liu.se Wed Jan 10 10:14:38 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 10 Jan 2007 16:14:38 +0100 Subject: Yield In-Reply-To: <45a3e096$0$8024$3b214f66@tunews.univie.ac.at> References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> <455c15ca$1@news.eftel.com> <455c1ddf@news.eftel.com> <1163691173.737911.130410@i42g2000cwa.googlegroups.com> <45a3e096$0$8024$3b214f66@tunews.univie.ac.at> Message-ID: <45A502DE.9000901@isy.liu.se> Mathias Panzenboeck wrote: > def primes(): > yield 1 > yield 2 > [snip rest of code] > Hmm... 1 is not a prime. See for instance http://en.wikipedia.org/wiki/Prime_number The definition given there is "In mathematics , a *prime number* (or a *prime*) is a natural number that has exactly two (distinct) natural number divisors ." The important part of the statement is "exactly two...divisors", which rules out the number 1. /MiO From gagsl-py at yahoo.com.ar Mon Jan 8 11:56:31 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 13:56:31 -0300 Subject: AES256 in PyCrypto In-Reply-To: <1168205009.554907.181120@v33g2000cwv.googlegroups.com> References: <1168134542.337448.261510@s34g2000cwa.googlegroups.com> <1168184060.548851.11540@i15g2000cwa.googlegroups.com> <1168205009.554907.181120@v33g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070108134626.03deb760@yahoo.com.ar> At Sunday 7/1/2007 18:23, mirandacascade at yahoo.com wrote: >Is a docstring is the text between the three consecutive quote >characters in a .py file? The reason for the question is that I looked See section 4.6 in the Python Tutorial - I strongly suggest you read it (or any other introductory text like diveintopython) >Can docstrings be embedded within the .pyd extension modules as well? Yes - if the original module writer has provided it. > >>> x = AES.new( >As soon as I type the '(' character, the IDE displays: >new(key, [mode], [IV]): Return a new AES encryption object [...] >I'm guessing that what the IDE is displaying is the first line of what >may be multiple-line docstring that is embedded within the .pyd >extension module? Might there be more lines in the docstring? I don't know which IDE are you using, but try typing "help(AES.new)" or simply "help" (without quotes) in the interpreter. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From paul at subsignal.org Thu Jan 4 15:47:38 2007 From: paul at subsignal.org (paul) Date: Thu, 04 Jan 2007 21:47:38 +0100 Subject: Draw rectangle on a Window DC In-Reply-To: <459cd1e4.0232d77c.0893.ffff821d@mx.google.com> References: <459cd1e4.0232d77c.0893.ffff821d@mx.google.com> Message-ID: Raymond schrieb: > Hi? > > I want to Draw rectangle on Dc when gived a position. Can you teach me? Let > me view your code? Well, you haven't given us much background but I'd suggest if your boss asks you to draw a rectangle on your corporate domain controller and the position allows this, you better do so or you'll get fired. Use chalk so you can wipe it off the case if your boss changes his/her mind. Disclaimer: I haven't tested this and the DC might get unstable or crash... scnr Paul From tiedon_jano at hotmail.com Sat Jan 6 09:34:35 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sat, 06 Jan 2007 14:34:35 GMT Subject: howto overload with a NOP (empty statement) In-Reply-To: <459f8b36$0$316$426a74cc@news.free.fr> References: <459f8b36$0$316$426a74cc@news.free.fr> Message-ID: <%rOnh.183$_B1.123@read3.inet.fi> Bruno Desthuilliers kirjoitti: > Stef Mientki a ?crit : >> How should I overload / disable a method ? >> In the example below I have defined the class "Power_Supply", derived >> from baseclass "device". > > > Naming conventions are to use CamelCase for class names. So it would be > better to name your classes 'PowerSupply' (no '_') and 'Device'. You're > of course free to use whatever naming convention you want, including no > convention at all, but Python relies *a lot* on naming conventions... > Continuing with the style and idioms issues... 1. Don't leave a space between a function/method/class name and the opening parenthesis, i.e. instead of: def execute (self): use: def execute(self): 2. It seems to me that you indent your code with 2 spaces. If I'm wrong, please ignore me. Otherwise: always use 4 spaces when indenting with spaces. Following these and the numerous other guidelines (see htpp://www.python.org/dev/peps/pep-0008/ for example) on Python style you'll be making yourself and others a favor. When these coding guidelines become your habit, it will be easier for you to read the code of other Pythoners. This is important because a large part of learning consists of reading the code of others. And also vice versa: when you show your code to others, it will be easier for them to concentrate on your problem when the idiosyncrasy of your code is not there to hinder. Cheers, Jussi From tim at tdw.net Mon Jan 8 13:40:00 2007 From: tim at tdw.net (Tim Williams) Date: Mon, 8 Jan 2007 18:40:00 +0000 Subject: recursive function In-Reply-To: References: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> Message-ID: <9afea2ac0701081040i69023554od4414330ac6e53f9@mail.gmail.com> On 8 Jan 2007 16:03:53 +0100, Neil Cerutti wrote: > > len(dict.keys()). > Or len(dict) :) From ptmcg at austin.rr.com Wed Jan 24 14:07:49 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Jan 2007 11:07:49 -0800 Subject: Regex for URL extracting In-Reply-To: <1169655624.981833.29730@j27g2000cwj.googlegroups.com> References: <1169655624.981833.29730@j27g2000cwj.googlegroups.com> Message-ID: <1169665668.999341.183480@a75g2000cwd.googlegroups.com> On Jan 24, 10:20 am, "Johny" wrote: > Does anyone know about a good regular expression for URL extracting? > > J. Google turns this up: http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx But I've seen other re's for this problem that are hundreds of characters long. -- Paul From bj_666 at gmx.net Wed Jan 3 03:47:44 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 03 Jan 2007 09:47:44 +0100 Subject: Synchronization methodology References: Message-ID: In , Chris Ashurst wrote: > Hi, I'm coming in from a despised Java background, and I'm having some > trouble wrapping my head around sharing an object between multiple > instances of a single class (in simpler terms, I would say imagine a > simple chat server that has to share a list of connected users to each > instance of a connected user). > > Usually, I would have a synchronized list instantiated inside each > instance of a client class, which would do the trick, but since there's > no synchronization in Python, I'm stuck staring at little tests > involving a standalone non-threaded class instance that holds the list > of users, and each connected user being passed this instance to be > "synchronized". There's no ``synchronized`` keyword, but of course you can synchronize methods. You have to attach an `threading.RLock` to the objects you want to synchronize on and use its `aquire()` and `release()` methods in places where you used ``synchronized (someObject) { ... }`` in Java. synchronized foo() { /* code */ } is the same as foo() { synchronized (this) { /* code */ } } in Java. And that's basically: def foo(self): self.lock.aquire() # code self.lock.release() You may want to make sure the lock will be released in case of an exception: def foo(self): self.lock.aquire() try: pass # code finally: self.lock.release() Ciao, Marc 'BlackJack' Rintsch From nmm1 at cus.cam.ac.uk Wed Jan 10 16:32:13 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 10 Jan 2007 21:32:13 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> In article , "Carl J. Van Arsdall" writes: |> |> Just as something to note, but many HPC applications will use a |> combination of both MPI and threading (OpenMP usually, as for the |> underlying thread implementation i don't have much to say). Its |> interesting to see on this message board this huge "anti-threading" |> mindset, but the HPC community seems to be happy using a little of both |> depending on their application and the topology of their parallel |> machine. Although if I was doing HPC applications, I probably would not |> choose to use Python but I would write things in C or FORTRAN. That is a commonly quoted myth. Some of the ASCI community did that, but even they have backed off to a great extent. Such code is damn near impossible to debug, let alone tune. To the best of my knowledge, no non-ASCI application has ever done that, except for virtuosity. I have several times asked claimants to name some examples of code that does that and is used in the general research community, and have so far never had a response. I managed the second-largest HPC system in UK academia for a decade, ending less than a year ago, incidentally, and was and am fairly well in touch with what is going on in HPC world-wide. Regards, Nick Maclaren. From subscriber100 at rjs.org Tue Jan 9 02:02:46 2007 From: subscriber100 at rjs.org (Ray Schumacher) Date: Mon, 08 Jan 2007 23:02:46 -0800 Subject: multi-threaded webcam with SimpleAsyncHTTPServer.py (updated) Message-ID: <6.2.3.4.2.20070108225547.02de5c40@rjs.org> Better asyncore.loop use. Also fixes a late bug in my first post of code: PILFile.seek(0) needed since PIL.save does not reset the pointer. class ImageServer(RequestHandler): def __init__(self, conn, addr, server): asynchat.async_chat.__init__(self,conn) self.client_address = addr self.connection = conn self.server = server self.set_terminator ('\r\n\r\n') self.incoming = deque() self.outgoing = deque() self.rfile = None self.wfile = writewrapper(self.outgoing, -self.use_buffer or self.blocksize) self.found_terminator = self.handle_request_line self.request_version = "HTTP/1.1" self.code = None def send_head(self): buff, width, height = cam.dev.getbuffer() imPIL = (Image.frombuffer("RGB", (width, height), buff, "raw", "BGR", 0, -1) ) PILFile.seek(0) imPIL.save(PILFile, "JPEG") self.send_response(200) self.send_header("Content-type", "image/jpeg") self.send_header("Content-Length: ", str(PILFile.len)) self.end_headers() self.wfile.write(PILFile.getvalue()) return ... parser.add_option('-3', dest='server', help='Run the server for cam images', action='store_const', const=3) options, args = parser.parse_args() if options.server==3: from StringIO import StringIO from PIL import Image if sys.platform == 'win32': import VideoCapture try: del(cam) gc.collect() print "deleted old cam instance" except: pass cam = VideoCapture.Device(devnum=options.devNum, showVideoWindow=0) print cam buff, width, height = cam.dev.getbuffer() PILFile = StringIO() else: pass # try http://laurent.pointal.org/python/projets/pyvideograb/index.pih # or fg #import fg #cam = fg.Grabber() #cam.set_source(options.devNum) # or video4linux.video_capture / v4lctl else: if options.root is None: parser.error("Need root path to start server") if not os.path.isdir(options.root): parser.error("Root path does not exist") os.chdir(options.root) req_handler = which[options.server] s=Server('',options.port,req_handler) print req_handler.__name__, "running on port", options.port, "with root path", options.root while True: try: asyncore.loop(timeout=1, count=1) except KeyboardInter From john.pye at gmail.com Wed Jan 24 22:37:23 2007 From: john.pye at gmail.com (John Pye) Date: 24 Jan 2007 19:37:23 -0800 Subject: Catching floating point errors from linked C code Message-ID: <1169696243.262973.188540@s48g2000cws.googlegroups.com> Hi all I have some C code that is giving me some 'nan' values in some calculations. The C code is wrapped using SWIG to give me a Python module that I am then exercising through a unittest suite. It seems that I should expect the C code to throw floating point exceptions (SIGFPE) and either the whole thing to abort, or for Python to catch the errors and report them. Instead I'm getting neither. I want to be able to track down the exact location of problems in my C code. Is there something that Python does to turn on/off the catching of divide-by-zero errors, eg by manipulating signal handlers and/or settings? Cheers JP From facundo at taniquetil.com.ar Fri Jan 26 11:34:42 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 26 Jan 2007 16:34:42 +0000 (UTC) Subject: Are there sprintf in Python??? References: <1169496238.925052.311660@l53g2000cwa.googlegroups.com> Message-ID: questions? wrote: > Are there similar function to sprintf in C? Meaning to print in a buffer? It's not necessary... Remember that all the ways that prints on files, actually does not need to print into *actual* files, but they can print into file-like objects (see StringIO, or mmap, for example). Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From wd.jonsson at gmail.com Tue Jan 23 04:59:37 2007 From: wd.jonsson at gmail.com (wd.jonsson at gmail.com) Date: 23 Jan 2007 01:59:37 -0800 Subject: Noob Question: Force input to be int? Message-ID: <1169546377.017596.43840@k78g2000cwa.googlegroups.com> Hello everyone! I have a piece of code that looks like this: if len(BuildList) > 0: print "The script found %d game directories:" % len(BuildList) print num = 0 for i in BuildList: print str(num) +" " + i num = num + 1 print print "Select a build number from 0 to " + str(len(BuildList) - 1) buildNum = int(raw_input('Select build #> ')) while buildNum > (len(BuildList) -1) or buildNum <= -1: print print "Error: Invalid build number!" print "Select a build number from 0 to " + str(len(BuildList) - 1) print buildNum = int(raw_input('Select build: ')) The problem is with the while buildNum-loop. If the user enters a non-numeric value in the buildNum input, the scripts throws an exception. I need to constrict the user to ONLY use integers in the input box. How can I solve this issue? From george.sakkis at gmail.com Sat Jan 27 01:18:20 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 26 Jan 2007 22:18:20 -0800 Subject: dict.keys() ? In-Reply-To: <1169867048.004256.279240@v33g2000cwv.googlegroups.com> References: <1169867048.004256.279240@v33g2000cwv.googlegroups.com> Message-ID: <1169878700.198497.173550@v45g2000cwv.googlegroups.com> On Jan 26, 10:04 pm, bearophileH... at lycos.com wrote: > The PEP 3100:http://www.python.org/dev/peps/pep-3100/ > says: > > Return iterators instead of lists where appropriate for atomic type > methods (e.g. dict.keys(), dict.values(), dict.items(), etc.); iter* > methods will be removed. Better: make keys(), etc. return views ala > Java collections??? > ... > To be removed: > dict.setdefault()? [15] > dict.has_key() method [done] > > I may be sleepy now, but maybe the keys() method too can be removed; > otherwise the following two become really the same: > > print list(adict) > for k in adict: ... > > print list(adict.keys()) > for k in adict.keys(): ... Alas, the consensus has moved away from simple iterators to less lightweight "views": http://svn.python.org/view/peps/trunk/pep-3106.txt?rev=53096&view=markup "The objects returned by the .keys() and .items() methods behave like sets with limited mutability; the allow removing elements, but not adding them.(...) The object returned by the values() method behaves like a multiset." I for one am not convinced that adding three new types is worth the complexity and the error-proneness of having two new similar-but-not-quite-the-same APIs with sets. Not only iteration is arguably the most common operation on a view, but the cost (in extra keystrokes and runtime performance) of populating any container that the user may need from an iterator is pretty low. George From gagsl-py at yahoo.com.ar Wed Jan 3 18:43:16 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Jan 2007 20:43:16 -0300 Subject: Unsubscribing from the list In-Reply-To: <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com > References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> Message-ID: <7.0.1.0.0.20070103204007.05697008@yahoo.com.ar> At Wednesday 3/1/2007 13:21, Dotan Cohen wrote: >The first sentance under the heading "Python-list Subscribers" is: >The subscribers list is only available to the list administrator. >Admin address: Password: > >As I'm not an admin, I read no further. That page uses the default MailMan administrative interfase. Send a RFE to the MailMan developers. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From robert.kern at gmail.com Tue Jan 16 03:33:57 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 16 Jan 2007 02:33:57 -0600 Subject: why scipy cause my program slow? In-Reply-To: <1168935124.912419.147250@a75g2000cwd.googlegroups.com> References: <1168935124.912419.147250@a75g2000cwd.googlegroups.com> Message-ID: HYRY wrote: > Why the exec time of test(readdata()) and test(randomdata()) of > following program is different? > my test file 150Hz10dB.wav has 2586024 samples, so I set randomdata > function > to return a list with 2586024 samples. > the exec result is: > 2586024 > > 10.8603842736 > 2586024 > > 2.16525233979 > test(randomdata()) is 5x faster than test(readdata()) > if I remove "from scipy import *" then I get the following result: > 2586024 > > 2.21851601473 > 2586024 > > 2.13885042216 > > So, what the problem with scipy? You're importing (through scipy) numpy's sum() function. The result type of that function is a numpy scalar type. The set of scalar types was introduced for a number of reasons, mostly having to do with being able to represent the full range of numerical datatypes that Python does not have builtin types for. Unfortunately, the code paths that get executed when arithmetic is performed sith such scalars are still suboptimal; I believe they are still going through the full ufunc machinery. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From duncan.booth at invalid.invalid Sat Jan 6 17:33:26 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Jan 2007 22:33:26 GMT Subject: Recommended way to force a thread context switch? References: <1168103258.602286.146100@42g2000cwt.googlegroups.com> <1168104008.910681.46800@38g2000cwa.googlegroups.com> Message-ID: Lloyd Zusman wrote: >> Why do you think that just letting the threads run won't have the >> effect you desire? Leave it to the system to schedule the threads. > > I can already see that they don't have the effect I desire. They are > long numerical calculations in tight loops. I have to periodically > put explicit time.sleep(0.001) calls in place to force the context > switching, and I was wondering if that's the recommended method. > Not really. If the context isn't switching enough for you then try calling sys.setcheckinterval(n) with varying values of n until you find one which is suitable. Calling it with a lower value of n will increase the frequency that you switch thread contexts, although of course it will also increase the overall runtime for your program. Alternatively you could try splitting your processing into smaller chunks and ensure each thread does a small chunk at a time instead of a large one. Why does it matter whether individual threads are being 'starved'? Surely you want them all to complete in any case, so does it matter if they run sequentially or in parallel? From tinaweb at bestemselv.com Tue Jan 23 08:28:07 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 23 Jan 2007 14:28:07 +0100 Subject: PyQt4 strangeness In-Reply-To: References: Message-ID: Phil Thompson wrote: > The module structure of PyQt reflects the library structure of Qt. Qt4 has > different libraries to Qt3 so PyQt4 has different modules to PyQt3. > > The top level PyQt4 module ensures that PyQt3, PyQt4 (and eventually PyQt5) > can all be installed side by side in the same site-packages directory. > > The style of import statement you use is up to you. All of the PyQt4 examples > adopt the style you describe, but you can achieve the equivalent of your > current practice by doing the following instead... > > from PyQt4.Qt import * > > Phil Ah, I see :) Thanks for the explanation. Tina From mccredie at gmail.com Tue Jan 2 12:47:55 2007 From: mccredie at gmail.com (Matimus) Date: 2 Jan 2007 09:47:55 -0800 Subject: how to use execfile with argument under windows In-Reply-To: <1167757591.465076.314700@h40g2000cwb.googlegroups.com> References: <1167757591.465076.314700@h40g2000cwb.googlegroups.com> Message-ID: <1167760075.911634.173090@48g2000cwx.googlegroups.com> > > error output > IOError: [Errno 2] No such file or directory:"filename.exe -type png > -source sourcearg -file filename.png" Use 'os.system' not 'execfile'. 'execfile' is for executing other python scripts, not arbitrary command line. Try this: import os ... ... os.system("filename.exe -type png -source sourcearg -file filename.png") > try > execfile("d:\pathto\filename.exe -type png -source sourcearg -file > filename.png") > > error output > IOError: [Errno 2] No such file or directory:"d:\pathto\filename.exe > filename.exe -type png -source sourcearg -file filename.png" be careful with your '\'s they tend to get interpreted as escape characters. You can prefix the string with an 'r', double them up or use forward slashes. One of the following should work: r"d:\pathto\filename.exe -type png -source sourcearg -file filename.png" "d:\\pathto\\filename.exe -type png -source sourcearg -file filename.png" "d:/pathto/filename.exe -type png -source sourcearg -file filename.png" From wolf_tracks at invalid.com Mon Jan 8 00:48:32 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 08 Jan 2007 05:48:32 GMT Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: <1168198159.798783.168010@i15g2000cwa.googlegroups.com> References: <1168194009.220437.286210@q40g2000cwq.googlegroups.com> <1168198159.798783.168010@i15g2000cwa.googlegroups.com> Message-ID: Gabriel Genellina wrote: > On 7 ene, 16:20, "W. Watson" wrote: > >> We seem to be looping. I have the Python interpreter. I would like the >> pythonwin editor. The download link doesn't work on SourceForge. Where can I >> get it? If not there, where? If it can't be obtained, then I'll go to the >> default editor built into python-2.5.msi. > > It *does* work for me. Try > https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063 > I can easily see the page you refer to, but where's the pythonwin editor? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet A road sign along many highways reads, "$1000 fine for littering" I have yet to find any $1000 bills. WTW -- Web Page: From horpner at yahoo.com Tue Jan 16 07:29:51 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Jan 2007 13:29:51 +0100 Subject: Anyone has a nice "view_var" procedure ? References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> Message-ID: On 2007-01-15, Gabriel Genellina wrote: > At Monday 15/1/2007 17:45, Stef Mientki wrote: > >>Is there some handy/ nice manner to view the properties of some variable ? >>As a newbie, I often want to see want all the properties of a var, >>and also some corner values (large arrays) etc. > > You can try dir(x), vars(x). If you want a "nice print", see > the pprint module. > > py> import csv > py> x = csv.DictReader('') # a bogus object > py> x > > py> dir(x) > ['__doc__', '__init__', '__iter__', '__module__', 'fieldnames', > 'next', 'reader' > , 'restkey', 'restval'] > py> vars(x) > {'restkey': None, 'restval': None, 'fieldnames': None, 'reader': ><_csv.reader ob > ject at 0x00BC98B8>} > py> from pprint import pprint > py> pprint(vars(x)) > {'fieldnames': None, > 'reader': <_csv.reader object at 0x00BC98B8>, > 'restkey': None, > 'restval': None} > py> It's an unfortunately limited sort of introspection. To rehash a recent experience: >>> import re >>> import pprint >>> r = re.match("(x+)|(y+)", "xxx") >>> pprint.pprint(dir(r)) ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start'] >>> r.lastindex 1 The documentation is deliberately vague: dir( [object]) [...] The list is not necessarily complete. If the object is a module object, the list contains the names of the module's attributes. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases. Otherwise, the list contains the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes. The resulting list is sorted alphabetically. [...] It's unclear to me what attributes an object could have that aren't included in the above list. Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. In other words, dir is just for fun, like monkey bars. ;) -- Neil Cerutti The eighth-graders will be presenting Shakespeare's Hamlet in the church basement on Friday at 7 p.m. The congregation is invited to attend this tragedy. --Church Bulletin Blooper From nszabolcs at gmail.com Mon Jan 29 10:01:23 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 07:01:23 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <7x3b5uwfa2.fsf@ruckus.brouhaha.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <7x3b5uwfa2.fsf@ruckus.brouhaha.com> Message-ID: <1170082883.393745.244840@a34g2000cwb.googlegroups.com> > If you don't mind possibly getting a few nonalphanumeric characters: > > import os,binascii > print binascii.b2a_base64(os.urandom(6)) what about file('/dev/urandom').read(6).encode('base64') (oneliner and without import sa op requested) From robert.kern at gmail.com Mon Jan 22 01:33:12 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Jan 2007 00:33:12 -0600 Subject: pylab, matplotlib ... roots function question In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > Hello NG, > > given this call to roots funtion from pylab It's actually from numpy and numpy questions are best asked (and best answered!) on numpy-discussion. http://www.scipy.org/Mailing_Lists > In [342]: roots([0,2,2]) > Out[342]: array([-1.]) > > as far as I understand it [a0,a1,a2] stands for a0+a1*x+a2*x^2 > in the above case it yields 2x^2+2x = 2x(1+x) > and the roots are 0 and -1 > I am wondering why roots function gives me only the -1 No, it's the other way around. In [1]: from numpy import * In [2]: roots? Type: function Base Class: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/numpy-1.0.2.dev3507-py2.5-macosx-10.4-i386.egg/numpy/lib/polynomial.py Definition: roots(p) Docstring: Return the roots of the polynomial coefficients in p. The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] So you were really solving 2*x + 2 = 0, the single root of which is -1. > second try > > In [343]: roots([1,0,0]) > Out[343]: array([], dtype=float64) > > ok, as it should be No, that's actually wrong. What version of numpy are you using? With a recent SVN checkout of numpy, I get the correct answer: In [3]: roots([1,0,0]) Out[3]: array([ 0., 0.]) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ironfroggy at gmail.com Sat Jan 13 14:49:19 2007 From: ironfroggy at gmail.com (ironfroggy at gmail.com) Date: Sat, 13 Jan 2007 19:49:19 +0000 (GMT) Subject: python-dev Summary for 2006-12-01 through 2006-12-15 Message-ID: <20070113194921.112A41E4004@bag.python.org> python-dev Summary for 2006-12-01 through 2006-12-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-12-01_2006-12-15] ============= Announcements ============= Some of you may know that Steven Bethard, having taken over the summaries from Brett Cannon some time ago, is no longer able to keep up with them. After much holiday stress and busy days, I've come to take over this honor and archive all the goings on here. I hope I can do a good job, and allow the summaries to continue being a useful and transparent fixture. Also, after catching up with my backlog of summary work, I plan to begin the first summaries of python-3000 (and, possibly, but not likely, the python- ideas list), as more and more actual work, rather than debating and theory-talk, is going on there. Sincerly, Your new summary writer, Calvin Spealman ========= Summaries ========= ------------------------- Indexing of Match Objects ------------------------- Subscripting re match objects directly was proposed and the debate the waged mostly on how to deal with slicing and m.group(0) to be the entire match. The consensus seemed to be that returning a match object would break, largely because m[1:2][0] != m[1], which breaks intuition with slices. Returning a list as a slice also breaks the intuitions about the type of a slice. Contributing thread: - `a feature i'd like to see in python #2: indexing of match objects `__ ---------------------------------------- Python and the Linux Standard Base (LSB) ---------------------------------------- Discussions about how to properly document the expected Python environment for all LSB compliant distributions continued shortly. Focus was on how distros have a need to split the standard library up, even if the entire thing is eventually installed, and issues such as Tkinter requiring X leading to standard modules being ommitted for flexable packages. Contributing thread: - `Python and the Linux Standard Base (LSB) `__ ------------------------------------- Number of Windows Installer Downloads ------------------------------------- Guido was impressed with out download numbers on Windows, but most people just attributed it to other platforms including and mirroring Python. Even taking that to consideration, the ratio of Windows to source downloads has shifted in Windows favor a good bit. The use of Python in introductory courses at MIT was mentioned as something to push these numbers further in the near future. Contributing thread: - `[Python-checkins] MSI being downloaded 10x more than all other files?! `__ -------------------------- Deletion Through Iterators -------------------------- The request was made to allow direct deletion of items from iterables through the iterator, but the idea was deemed unscalable to iterables in general and broken with dictionaries. The solutions to work around the problem were given and generally agreed to be sufficient (such as copying all the items you want to keep, instead). Contributing thread: - `a feature i'd like to see in python #1: better iteration control `__ ------------------------- LSB: Binary compatibility ------------------------- The other side of the LSB issue was discussed, related to the CPython ABI, the .pyc bytecode and the marshall formats, and exactly which versions of Python may or may not gain a standard ABI, as well as how to carry this forward to future (already existing and evolving) version of Python. Some mention was made of the difficulties and conflicts being brought on by the idea of LSB standards for Python, while the benefits of this were challenged. Contributing thread: - `LSB: Binary compatibility `__ ---------------------------------------- Adding resume (206) support to urllib(2) ---------------------------------------- Daniel Watkins asked about adapting his HTTP resuming support into urllib, but suggestions directly moved this to urllib2 and then to httplib. The conversation quickly drifted into talking about how abstract and minimal the urllib(2) should be, while the httplib module may grow increasing complex and feature supporting. The original poster made no final comment on his intentions to follow through with the patch. Contributing thread: - `Adding resume (206) support to urllib(2) `__ ------------------- __str__ and unicode ------------------- The details of what an object's __str__() method must return were inquired. Must the string returned by a str or any basestring? It was announced to allow unicode objects, with no restriction on content. However, the caution that the return is likely to be encoded into the default encoding was given. Contributing thread: - `__str__ and unicode `__ ---------------------------------- LSB: Selection of a Python version ---------------------------------- Martin v. Lowis announced that LSB will likely move forward with Python 2.4 as the first LSB standard Python version. How to handle future bug patches, as well as the comfort of the distributions for being required to support an outdated package (2.4 is already "retired") was considered. The consensus settled on a documented support for 2.4 moving forward with security patches, and likely even 2.3, as security patches are rare enough to not cause too many cycles to be spent on them. Contributing thread: - `LSB: Selection of a Python version `__ ------------------------------ Threading, atexit, and logging ------------------------------ A bug (#1566280) was previously reported, related to the ordering of the atexit handlers for the logging and threading modules. Participants in the thread had a general agreement that the threading module using such a user visiable mechanism for cleanup and lifetime was a bad design in the first place to be remedied. Contributing thread: - `Threading, atexit, and logging `__ ----------------------------------- Creating dicts from dict subclasses ----------------------------------- The built-in types can now be subclassed, but C code doesn't always realize this, and relies too heavily on the internals of the base class. In this case, PyDict_Merge was assuming too much; replacing the PyDict_Check test with PyDict_CheckExact fixed the bug, but slowed things down a lot. Walter Dorwald suggested adding a not-quite-as-fast path for sensible mappings (including dict subclasses). Unfortunately, there was a bit of disagreement over what constituted "sensible". Should the middle-speed path use iteration over items (the exact content it needed), over keys (a bit faster in the current implemententation), or not even exist (to avoid limiting future implementations)? As of Jan 8, 2007, SVN has not been updated; there is no middle-speed path, and the bug is still possible. (Summary contributed by Jim Jewett) Contributing thread: - `Creating dicts from dict subclasses `__ ----------------------------------------------------------------------------- OT: World's oldest ritual discovered. Worshipped the python 70, 000 years ago ----------------------------------------------------------------------------- This was a quick and off-topic post about other instances of python symbolism in ancient humanity, including a definition of our word "pythonic" to mean "prophetic", which seems fitting enough. Contributing thread: - `OT: World's oldest ritual discovered. Worshipped the python 70, 000 years ago `__ ------------------ LSB: pyc stability ------------------ The LSB meetings brought up the issue of standardized bytecode formats, again. This has always been something discouraged from Python. Keeping the bytecode format free and the implementation open to ignoring old versions, has always been helpful for maintanence and development. The common reasoning of protecting IP was used, although most in-the-know consider this to be a false sense of security. Reguardless, it might be useful in legal ways, as trade secrets do require a reasonable attempt at hidding them in order to be recognized as such. The possible solution of importing encypted zip packages with a custom import hook was proposed and seems logical. Contributing thread: - `LSB: pyc stability `__ ------------------------------- Interpolated Strings (ala perl) ------------------------------- Perl/PHP style string interpolation was brought up, but is found unreasonable for various reasons. Cons include the use of format strings in scopes outside where they are defined, the dangers of eval, and possibly the general resisting of any idea coming from Perl. This seems a highly unlikely proposal. Contributing thread: - `features i'd like [Python 3000?] ... #4: interpolated strings ala perl `__ --------------------------- Polling with Pending Calls? --------------------------- Issues with the RPM library blocking interupts for long periods of time were brought up with proposed fixes by patching the rpmlib bindings to "automagically" poll for any pending calls. An existing patch was suggested but did not seem to fit the case at hand. Contributing thread: - `Polling with Pending Calls? `__ --------------------- Cross-compile Patches --------------------- Patch 1597850 is being actively worked, and will improve the experience when compiling python for freeBSD from a linux environment. Contributing thread: - `cross-compile patches `__ ------------------------------------ Open CPython VM for type information ------------------------------------ Would it make sense to modify the CPython virtual machine (bytecode) so that it was easier for other programs to produce bytecode? Answer: No -- those programs should produce either C (which gets called as a function) or python (which gets interpreted by the python interpreter -- there are already interpreters that don't use CPython bytecode. Contributing thread: - `Open CPython VM for type information `__ =============== Skipped Threads =============== - `Weekly Python Patch/Bug Summary `__ - `Windows SDK `__ - `help for a noob - version for a sharp ARM `__ - `fileinput module tests `__ - `fpectl: does a better implementation make sense? `__ - `Small tweak to tokenize.py? `__ - `features i'd like [Python 3000] ... #3: fix super() `__ - `Makefile.pre.in Patch `__ - `Python and LSB: Meeting Report `__ - `Virtual Python (was Re: Python and the Linux Standard Base (LSB)) `__ - `DRAFT: python-dev summary for 2006-11-16 through 2006-11-30 `__ - `Looking for new Python-Dev Summarizers `__ - `Adding C99 bool to struct module `__ - `Spam and semi-spam and neo-spam `__ - `Next PyPy sprint: Leysin 8-14th January 2007 `__ - `Distribution tools: What I would like to see `__ - `RealClearPolitics - Articles - Exit Rumsfeld, Smiling `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from December 01, 2006 through December 15, 2006. 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 python-dev summary is the 1st written by Calvin Spealman. To contact me, please send email: - Calvin Spealman (ironfroggy at gmail dot com) Do *not* post to comp.lang.python if you wish to reach me. 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 cent counts 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 ------------------------- 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. We 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. .. _python-dev: http://www.python.org/dev/ .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _Python Software Foundation: http://python.org/psf/ .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From hpk at trillke.net Mon Jan 22 11:14:43 2007 From: hpk at trillke.net (holger krekel) Date: Mon, 22 Jan 2007 17:14:43 +0100 Subject: PyPy trillke sprints (Feb/March 2007) Message-ID: <20070122161443.GV16915@solar.trillke> ========================================================================= PyPy Trillke "EU and beyond!" sprints (25-28th Feb, 1-5th March 2006) ========================================================================= .. image:: http://www.trillke.net/images/HausPanorama0304_113kb.jpg Some two years and some thousands of commits later, the EU project period of the PyPy (http://codespeak.net/pypy) project is about to close ... and a new period to begin: we are going for a sprint of three days of focusing on EU reports and administrative issues, and another three day sprint of happy hacking on the numerous interesting open ends of PyPy, the source code. We also intend to discuss and state our view on the time after the EU period (March 2007 is the last EU funded month), because clearly the project will not stop after our successful (knock knock!) completion of the EU project. It's already clear that some of us seriously plan for a relaxation time, i.e. one without having many obligations. But that should not keep us from thinking and envisioning the development from April on. So to the Sprint: we have two parts of the sprint, first the EU and second the public all-invited part:: 26th Feb - 28th Feb EU reports and adminstrative sprint 1st March break day / arrival for coding sprint 2nd March - 4th March public coding "beyond EU" sprint days All days are meant as full days, so please arrive 25th Feb / 1st March and leave 5th March if you can (this help us with pairing, introductions and logistical planning). --------------------------------------------- Possible Topics for the coding sprint --------------------------------------------- * working on .NET, Java and other backends * working on the Javascript, Prolog or a new frontend * Tuning the JIT, refining approaches `[1]`_ * Fixing PyPy-1.0 problems / improving it (PyPy-1.0 is scheduled for Mid February, btw) * improving the py lib/py.test, build environments, preparing for server administration efforts from April on * Work on/with prototypes that use the new features that PyPy enables: distribution `[2]`_ (based on transparent proxying `[3]`_), security `[4]`_, persistence `[5]`_, etc. `[6]`_. * discussion about the time after March, and how to organize/co-ordinate ourselves * all topics that are of interest otherwise (including maybe working on some particular EU related topics still!) .. _[1]: http://codespeak.net/pypy/dist/pypy/doc/jit.html .. _[2]: http://codespeak.net/svn/pypy/dist/pypy/lib/distributed/ .. _[3]: http://codespeak.net/pypy/dist/pypy/doc/proxy.html .. _[4]: http://codespeak.net/pypy/dist/pypy/doc/project-ideas.html#security .. _[5]: http://codespeak.net/pypy/dist/pypy/doc/project-ideas.html#persistence .. _[6]: http://codespeak.net/pypy/dist/pypy/doc/project-ideas.html ----------------------- Location ----------------------- The sprint takes place at the Trillke Gut Steinbergstr. 42 Hildesheim, Germany http://www.trillke.net If you come to Hildesheim main station, take the Bus Number 3 (Hildesheimer Wald) and get out at "Waldquelle". Walking back a 100 meters gets you to a small street on the right leading to a big white building, the Trillke Gut. We'll have at least one larger room for sprinting, and a kitchen for our use. ----------------------- Accomodation ----------------------- We can probably arrange for some cheap or no-cost private accomodation, in private rooms located up in the house (and being part of "living groups" of 5-10 people). There also is a nice Guest house that has been used during recent events: http://www.gaestehaus-klocke.de/ and a four-star hotel 500 meters away from the Trillke: http://www.berghoelzchen.de/ ----------------------- Registration ----------------------- please subscribe to the pypy-sprint mailing list http://codespeak.net/mailman/listinfo/pypy-sprint and register by subversion: http://codespeak.net/svn/pypy/extradoc/sprintinfo/trillke-2007/people.txt or - if you have no checkin-rights - post to the pypy-sprint list above. -- merlinux GmbH Steinbergstr. 42 31139 Hildesheim http://merlinux.de tel +49 5121 20800 75 (fax 77) From smusnmrNOSPAM at yahoo.com Thu Jan 4 11:00:33 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Thu, 4 Jan 2007 17:00:33 +0100 Subject: pow() works but sqrt() not!? References: <459d0a1c_6@news.bluewin.ch> Message-ID: Thanks for that, too! Would be interesting to learn how these different algorithms influence the precision of the result!? "Boris Borcic" schrieb im Newsbeitrag news:459d0a1c_6 at news.bluewin.ch... > siggi wrote: >> Hi all, >> >> this is a newbie question on : >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] >> on >> win32 >> PC with WinXP >> >> In >> http://www.python.org/doc/2.3.5/lib/module-math.html >> I read: >> >> "sqrt( x) Return the square root of x." >> >> Now the test for module math with function pow(): >> --------------------------------------------------- >>>>> pow(9,9) >> 387420489 >> >> Fine, but sqrt() fails: >> ------------------- > > BTW note that (of course) you can write pow(x,.5) or x**.5 for sqrt(x) > without any preliminary import statement From eastera at gmail.com Mon Jan 1 05:43:07 2007 From: eastera at gmail.com (JTree) Date: 1 Jan 2007 02:43:07 -0800 Subject: A question about unicode() function In-Reply-To: <1167571210.084436.311610@48g2000cwx.googlegroups.com> References: <1167571210.084436.311610@48g2000cwx.googlegroups.com> Message-ID: <1167648187.190860.123680@k21g2000cwa.googlegroups.com> Thanks everyone! Sorry for my ambiguous question. I changed the codes and now it works fine. JTree wrote: > Hi,all > I encountered a problem when using unicode() function to fetch a > webpage, I don't know why this happenned. > My codes and error messages are: > > > Code: > #!/usr/bin/python > #Filename: test.py > #Modified: 2006-12-31 > > import cPickle as p > import urllib > import htmllib > import re > import sys > > def funUrlFetch(url): > lambda url:urllib.urlopen(url).read() > > objUrl = raw_input('Enter the Url:') > content = funUrlFetch(objUrl) > content = unicode(content,"gbk") > print content > content.close() > > > error message: > > C:\WINDOWS\system32\cmd.exe /c python test.py > Enter the Url:http://www.msn.com > Traceback (most recent call last): > File "test.py", line 16, in ? > content = unicode(content,"gbk") > TypeError: coercing to Unicode: need string or buffer, NoneType found > shell returned 1 > Hit any key to close this window... > > Any suggestions would be appreciated! > > Thanks! From bdesth.quelquechose at free.quelquepart.fr Mon Jan 8 15:34:44 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Jan 2007 21:34:44 +0100 Subject: Working with Excel inside Python In-Reply-To: References: <1168205727.130771.257030@51g2000cwl.googlegroups.com> Message-ID: <45a2a49c$0$291$426a74cc@news.free.fr> gblais at cox.net a ?crit : > Or, you might want to look at two packages: > > xlrd > > pyExcelerator > > The first can "read" .xls files, and the second can write them. I've had > great results with both. That's fine, but since the OP is mainly using Excel for reformating a csv file and saving it as a dbf file, I fail to see how these packages would help... From bdesth.quelquechose at free.quelquepart.fr Fri Jan 5 08:26:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Jan 2007 14:26:07 +0100 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> Message-ID: <459e4bbf$0$289$426a74cc@news.free.fr> jeremito a ?crit : > I am writing a class that is intended to be subclassed. What is the > proper way to indicate that a sub class must override a method? class Base(object): def method_to_override(self, *args, **kw): raise NotImplementedError("You need to override this method") From Robert.Katic at gmail.com Tue Jan 16 17:54:29 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 16 Jan 2007 14:54:29 -0800 Subject: arguments of a function/metaclass In-Reply-To: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> References: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> Message-ID: <1168988065.361547.141670@38g2000cwa.googlegroups.com> rubbishemail at web.de je napisao/la: > Hello, > > > I have a member function with many (20) named arguments > > def __init__(self,a=1,b=2): > self.a=a > self.b=b > > I would like to get rid of the many redundant lines like self.a=a and > set the members automatically. > The list of default arguments could be given like > > def __init__(**kwargs): > arglist={"a":1,"b":2] > > if this makes things easier > > Of course there has to be a check that raises an error in case of an > unknown argument not mentioned in this list. > > > I am sure there is an elegant way how to do this, could you give me any > hints??? > > > Many thanks > > > > Daniel def changeattrs(obj, __dict, **kwargs): for name, value in __dict.iteritems(): if hasattr(obj, name): setattr(obj, name, value) else: raise AttributeError for name in kwargs: if hasattr(obj, name): setattr(obj, name, kwargs[name]) else: raise AttributeError def locals2self(depth=0): import sys ns = sys._getframe(depth+1).f_locals obj = ns['self'] for name, value in ns.iteritems(): if name != 'self': setattr(obj, name, value) class C1(object): def __init__(self, a=1, b=2, c=3, d=4): locals2self() class C2(object): a = 1 b = 2 c = 3 d = 4 def __init__(self, **kwargs): changeattrs(self, kwargs) From nagle at animats.com Fri Jan 12 00:54:42 2007 From: nagle at animats.com (John Nagle) Date: Fri, 12 Jan 2007 05:54:42 GMT Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error In-Reply-To: References: <1168543799.097737.127930@i56g2000hsf.googlegroups.com> Message-ID: Heikki Toivonen wrote: > nagle at animats.com wrote: > >> That's a problem for me. I need short timeouts; I'm accessing sites >>that might or might not have SSL support, and I need to quickly time >>out when there's no SSL server. > > > You should be able to do short timeouts, just not using the global > setdefaulttimeout. Have you tried Connection.set_socket_read/write_timeout? Yes. That does not affect the connect timeout; it's only effective once the connection has been opened. And adjusting the session timeout just recreates the blocking/non blocking problem. Incidentally, "get_socket_read_timeout()" doesn't work. Generates "EXCEPTION at socket level: unpack str size does not match format", every time, at least with Python 2.4 on Windows. The lower level function returns one number as a string, like "7200", and the unpack function tries to unpack it as "ll", which fails. > Also like I mentioned before, if you use the Twisted wrapper and let > Twisted handle network stuff you should be fine. That would mean struggling with Twisted and dealing with its bugs. (For example, has the MySQLdb mess been resolved for Twisted's API?) This isn't a long-running application; it usually runs as a CGI program. So Twisted is inappropriate. > M2Crypto and pyOpenSSL (and pyOpenSSL-extended, which you might want to > take a look at as well) are implemented pretty differently, so merging > seems unlikely. They are pretty small code wise, though, so it is not an > impossible task. That seened good idea, and so I downloaded the source and tried to build it on a Windows machine to run with Python 2.4. But that build needs (exactly) Visual Studio 7.1, which I don't have. It also wants a specific version of OpenSSL, and has a build file which seems to assume a 1998 version of Visual C++. The last change was in 1995, and it's still at an 0.x version, so it's effectively abandonware. I have some doubts that it really works any more. I saw some Python 2.2/2.3 specific code in there. I could try building on a Linux system, but it's useful to me if Python works on both Windows and Linux. > > Personally I think I'd prefer if Python stdlib contained a better SSL > module that did at least all the checks required for safe SSL > connection. (Yeah, yeah, maybe I need to write it myself if nobody else > gets to it;) What I need is proper SSL operation, certificate chain validation, useful exception info when a connection fails (including why), and read acess to the certificate itself in some reasonably sane form. And I need to time out an SSL connection if it can't connect and verify within 4 seconds. It's embarassing that this doesn't work, despite four different wrappers for OpenSSL. I'm willing to spend a few hundred dollars towards making this happen. John Nagle From ricli576 at student.liu.se Thu Jan 18 21:54:59 2007 From: ricli576 at student.liu.se (Rickard Lindberg) Date: 18 Jan 2007 18:54:59 -0800 Subject: Match 2 words in a line of file References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> <1169172954.107365.133950@51g2000cwl.googlegroups.com> Message-ID: <1169175299.490994.244700@51g2000cwl.googlegroups.com> I see two potential problems with the non regex solutions. 1) Consider a line: "foo (bar)". When you split it you will only get two strings, as split by default only splits the string on white space characters. Thus "'bar' in words" will return false, even though bar is a word in that line. 2) If you have a line something like this: "foobar hello" then "'foo' in line" will return true, even though foo is not a word (it is part of a word). From sxn02 at yahoo.com Thu Jan 11 10:45:56 2007 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Thu, 11 Jan 2007 07:45:56 -0800 (PST) Subject: Python 2.5 install on Gentoo Linux: failed dmb and _tkinter Message-ID: <305847.86110.qm@web56012.mail.re3.yahoo.com> > Did you add /usr/local/lib to /etc/ld.so.conf? It's there Sorin ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com From steven.bethard at gmail.com Sun Jan 21 23:27:39 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 21 Jan 2007 21:27:39 -0700 Subject: pyparsing Combine without merging sub-expressions In-Reply-To: <1169417733.814587.63560@11g2000cwr.googlegroups.com> References: <1169417733.814587.63560@11g2000cwr.googlegroups.com> Message-ID: Paul McGuire wrote: > Steven Bethard wrote: >> Within a larger pyparsing grammar, I have something that looks like:: >> >> wsj/00/wsj_0003.mrg >> >> When parsing this, I'd like to keep around both the full string, and the >> AAA_NNNN substring of it, so I'd like something like:: >> >> >>> foo.parseString('wsj/00/wsj_0003.mrg') >> (['wsj/00/wsj_0003.mrg', 'wsj_0003'], {}) >> >> How do I go about this? I was using something like:: >> >> >>> digits = pp.Word(pp.nums) >> >>> alphas = pp.Word(pp.alphas) >> >>> wsj_name = pp.Combine(alphas + '_' + digits) >> >>> wsj_path = pp.Combine(alphas + '/' + digits + '/' + wsj_name + >> ... '.mrg') [snip] > BUT, if all you want is to be able to easily *access* > that sub-field, then why not give it a results name? Like this: > > wsj_name = pp.Combine(alphas + '_' + digits).setResultsName("name") > > Leave everything else the same, but now you can access the name field > independently from the rest of the combined tokens. Works great. Thanks! STeVe From paul at boddie.org.uk Fri Jan 12 05:42:06 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Jan 2007 02:42:06 -0800 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> <1168519760.894380.303990@i39g2000hsf.googlegroups.com> <33vph.8825$pQ3.2190@newsread4.news.pas.earthlink.net> <1168540582.125402.78850@p59g2000hsd.googlegroups.com> Message-ID: <1168598526.500293.186850@a75g2000cwd.googlegroups.com> Dennis Lee Bieber wrote: > The problem though, is that the original poster claimed the Oracle > data was being emitted in multiple chunks, not as a single output -- and > they want to avoid collecting the data in a temporary file... I think he wanted to know whether concurrent reads from Oracle and writes to PostgreSQL would be faster or more efficient. I'd argue that the temporary file approach is likely to be faster and more efficient (disk space usage for temporary files disregarded). Sure, if you can have two concurrent processes with minimal contention, one reading from Oracle, one writing to PostgreSQL, where the PostgreSQL one never lags behind and thus completes shortly after the Oracle data has been completely downloaded, then that might be the ideal solution, but I'm inclined to believe that unless the stream of data from Oracle were arriving really slowly, it wouldn't work out that way. Anyway, that's what my experiences with PostgreSQL suggest so far. Further commentary on the topic is, as noted, available in the manual. Paul From bborcic at gmail.com Thu Jan 4 09:06:42 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 04 Jan 2007 15:06:42 +0100 Subject: pow() works but sqrt() not!? In-Reply-To: References: Message-ID: <459d0a1c_6@news.bluewin.ch> siggi wrote: > Hi all, > > this is a newbie question on : > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on > win32 > PC with WinXP > > In > http://www.python.org/doc/2.3.5/lib/module-math.html > I read: > > "sqrt( x) Return the square root of x." > > Now the test for module math with function pow(): > --------------------------------------------------- >>>> pow(9,9) > 387420489 > > Fine, but sqrt() fails: > ------------------- BTW note that (of course) you can write pow(x,.5) or x**.5 for sqrt(x) without any preliminary import statement From etatoby at gmail.com Sat Jan 27 10:52:12 2007 From: etatoby at gmail.com (Toby) Date: 27 Jan 2007 15:52:12 GMT Subject: Commandline wrapper: help needed Message-ID: <45bb7527$0$20806$5fc30a8@news.tiscali.it> I'm trying to write a simple commandline wrapper: a script that runs another program as a child and relays unbuffered stdin and stdout to/from the child process, possibly filtering it. The usefulness of such a program lies in the filtering stage, in a possible integration with readline, or in other interface enhancements. Still, I'd like to discuss with you the unfiltered, unembellished version, because I'm not satisfied with it and because I'm having some minor problems. Here's the script: #!/usr/bin/python import sys, os, thread def stdin_handler(child_stdin): while True: d = sys.stdin.read(1) if not d: break child_stdin.write(d) child_stdin.flush() child_stdin.close() def stdout_handler(child_stdout): while True: try: d = child_stdout.read(1) if not d: break sys.stdout.write(d) sys.stdout.flush() except KeyboardInterrupt: pass def wrap(cmd): child_stdin, child_stdout = os.popen2(cmd) thread.start_new_thread(stdin_handler, (child_stdin,)) stdout_handler(child_stdout) if __name__ == '__main__': wrap(sys.argv[1]) You invoke it passing a program name as the first argument (such as bash, python itself, sbcl, whatever) and then you interact with the child process as if this wrapper wasn't there. Ctrl-C and Ctrl-D work as expected, sending SIGINT (that the child program can catch) and closing stdin respectively. Problems: 1. I don't like the read(1) loops. I'd like to be able to read bigger chunks at a time, but I haven't found a way to do that while keeping the functionality intact. I have tried fidgeting with select() but I didn't get far. What I (think I) need is a non-blocking read(), but I'm not sure how to achieve that, at least with Python 2.4 on Linux. 2. Even this version sometimes has problems. For example, if you launch the wrapper around sbcl (a free Lisp interpreter/compiler) it mostly works (entering 1 gives 1, entering (+ 2 3) gives 5...) until you get to the debugger, for example by entering an undefined name. Now, when the debugger says "0: [ABORT] Exit debugger...", entering 0 should get you back to the "*" prompt--and indeed does, unless you are using my wrapper, in which case everything hangs, and the only solution is to terminate everything with Ctrl-\ or such. Any idea how to improve the script and solve this problem? Toby From nospam at riddergarn.dk Sun Jan 28 04:54:28 2007 From: nospam at riddergarn.dk (Scripter47) Date: Sun, 28 Jan 2007 10:54:28 +0100 Subject: Ip address Message-ID: <45BC72D4.9030905@riddergarn.dk> How do i get my ip address? in cmd.exe i just type "ipconfig" then it prints: ... IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 ... how can i do that in python?? From robert.kern at gmail.com Mon Jan 22 18:11:40 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Jan 2007 17:11:40 -0600 Subject: arrow keys don't work In-Reply-To: <1169506381.452422.179070@11g2000cwr.googlegroups.com> References: <1169506381.452422.179070@11g2000cwr.googlegroups.com> Message-ID: tac-tics wrote: > I've noticed that in Python 2.5, the interactive prompt does not > support intelligent use of arrow keys like 2.4 did (up/down for > previous/next statement, left/right for moving the cursor). What > exactly is the reason for this and is there an easier fix than > downgradinig to 2.4? Thanks. Your installation of 2.4 probably had the readline module installed while your installation of 2.5 doesn't. What platform are you on? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Eugene.Antimirov at portaone.com Mon Jan 22 05:24:16 2007 From: Eugene.Antimirov at portaone.com (Eugene Antimirov) Date: Mon, 22 Jan 2007 12:24:16 +0200 Subject: newbie question In-Reply-To: <618640.79082.qm@web7806.mail.in.yahoo.com> References: <618640.79082.qm@web7806.mail.in.yahoo.com> Message-ID: <45B490D0.8020809@portaone.com> kavitha thankaian wrote: > Hi, > > i wrote a simple script (which follows) to insert a table in the > database.i could execute this query and get the result in python > shell.but when i open "my sql enterprise manager" i couldnt find the > table"animals".it would be so kind of you if someone could help me,,, > > > import dbi > import odbc > conn=odbc.odbc("DSN=mydatabase;UID=xxx;PWD=yyy") > cursor=conn.cursor() > cursor.execute("Create table animals(parent char(50),child char(50))") > cursor.execute("insert into animals values('lion','cub')") > cursor.execute("insert into animals values('goat','lamb')") > cursor.execute("select * from animals") > print cursor.fetchall() > > > Rgds > Kavitha > > ------------------------------------------------------------------------ You've probably missed cursor.commit() ;) -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer support at portaone.com * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ From gonzlobo at gmail.com Sun Jan 21 19:46:46 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Sun, 21 Jan 2007 17:46:46 -0700 Subject: Python Windows Editors In-Reply-To: <79e7c$45b3facb$d443bb3a$7251@news.speedlinq.nl> References: <79e7c$45b3facb$d443bb3a$7251@news.speedlinq.nl> Message-ID: I prefer PyScripter too, but would like to know if I can have 'indentation guides' enabled like PythonWin allows. On 1/21/07, Stef Mientki wrote: > I tried 2 of them, and only was stable enough: PyScripter > http://mmm-experts.com/Products.aspx?ProductID=4 From gandalf at designaproduct.biz Tue Jan 2 14:16:12 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 02 Jan 2007 20:16:12 +0100 Subject: wsdl2py question Message-ID: <459AAF7C.4000606@designaproduct.biz> Hi All! I just installed ZSI and tried to generate client code for a wsdl. Here is the exception I got: Traceback (most recent call last): File "/usr/local/bin/wsdl2py", line 9, in ? wsdl2py() File "/usr/local/lib/python2.4/site-packages/ZSI/generate/commands.py", line 222, in wsdl2py wsm.writeClient(fd) File "/usr/local/lib/python2.4/site-packages/ZSI/generate/wsdl2python.py", line 211, in writeClient sd.fromWsdl(service, **kw) File "/usr/local/lib/python2.4/site-packages/ZSI/generate/wsdl2python.py", line 294, in fromWsdl mw.setUp(soc, port, input=False) File "/usr/local/lib/python2.4/site-packages/ZSI/generate/wsdl2python.py", line 348, in setUp rpc,literal = soc.isRPC(), soc.isLiteral(input) File "/usr/local/lib/python2.4/site-packages/ZSI/generate/containers.py", line 441, in isLiteral return IsLiteral(msgrole) File "/usr/local/lib/python2.4/site-packages/ZSI/generate/containers.py", line 65, in IsLiteral raise ValueError, 'Missing soap:body binding.' ValueError: Missing soap:body binding. What does it mean? The wsdl is good for sure, I know other people using it from Java and .NET. I do not know too much about SOAP, this is why I wanted to generate the python code for my client, but now I'm stuck. Thanks, Laszlo From octabox at gmail.com Tue Jan 9 09:58:15 2007 From: octabox at gmail.com (octabox at gmail.com) Date: 9 Jan 2007 06:58:15 -0800 Subject: Internet Survey Message-ID: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Hello all, I represent Octabox, an Internet Start-up developing a wide-scale platform for Internet services. We are very interested to know your thoughts on Internet productivity and how it might be improved, and to that end we have set up a short survey at our website - http://www.octabox.com/productivity_poll.php We would very much appreciate if you would take a couple of minutes to fill it up and influence our direction and empahsis. Thanks in advance, Octabox Development Team From gagsl-py at yahoo.com.ar Thu Jan 11 22:43:48 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Jan 2007 00:43:48 -0300 Subject: Universal Feed Parser - How do I keep attributes? In-Reply-To: References: <1168450723.340213.235690@o58g2000hsb.googlegroups.com> <7.0.1.0.0.20070111012646.03f5bdb8@yahoo.com.ar> Message-ID: <7.0.1.0.0.20070112003236.0599f8f0@yahoo.com.ar> At Thursday 11/1/2007 12:01, Max Erickson wrote: >Gabriel Genellina wrote: > > > At Wednesday 10/1/2007 14:38, snewman18 at gmail.com wrote: > > > >> >>> d = > >> >>> feedparser.parse('http://weather.yahooapis.com/forecastrss?p= > > 94089') > >> >>> d.feed.yweather_location > >>u'' > > > > You have to feed it the *contents* of the page, not its URL. > >The online documentation disagrees with you: > >http://feedparser.org/docs/introduction.html You're right, sorry. Anyway this parser can't cope with attributes in custom elements - they're just ignored. Only the contents are retained. For the yweather namespace it's useless then, since attributes are used to store all the information: You may try a different library. A generic XML approach like ElementTree http://effbot.org/zone/element-index.htm should be fine. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From carsten at uniqsys.com Wed Jan 3 14:43:01 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 03 Jan 2007 14:43:01 -0500 Subject: Sorting on multiple values, some ascending, some descending In-Reply-To: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> Message-ID: <1167853381.3391.29.camel@dot.uniqsys.com> On Wed, 2007-01-03 at 10:48 -0800, dwelden wrote: > I have successfully used the sort lambda construct described in > http://mail.python.org/pipermail/python-list/2006-April/377443.html. > However, how do I take it one step further such that some values can be > sorted ascending and others descending? Easy enough if the sort values > are numeric (just negate the value), but what about text? > > Is the only option to define an external sorting function to loop > through the list and perform the comparisons one value at a time? If by "external sorting function" you mean a custom comparison function to pass to sort as the cmp argument, then that's one option, but not the only one. If you know in advance which columns contain strings, you could write a function that operates on strings and is strictly monotonically decreasing, i.e. it behaves such that f(x) < f(y) if and only if x > y. This function could then be used in the sort key for sorting on a string column in descending order. The following function does the trick: def antistring(x): return [256-ord(c) for c in x]+[257] (Proof by vigorous handwaving.) Lastly, if your array is small enough that you can tolerate the performance hit of multiple passes, you could exploit the fact that sort() is guaranteed to be stable in sufficiently recent releases of CPython. Split your sort on n columns into n separate sorts on a single column each, and use the 'reverse' parameter to specify whether to sort forward or backwards. Hope this helps, Carsten. From danielkleinad at gmail.com Mon Jan 8 14:43:09 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Mon, 08 Jan 2007 19:43:09 GMT Subject: newbieee References: <1168280831.323496.277020@38g2000cwa.googlegroups.com> <1168282763.275854.145430@v33g2000cwv.googlegroups.com> Message-ID: On 8 Jan 2007 10:59:23 -0800, "Thomas Nelson" wrote: >O'reilly has a book called Programming Python that covers much of the >standard library and how to use it for complex tasks. It may be out of >date by now, though. Programming Python (by Mark Lutz) is now in it's 3rd edition and is quite up to date. Dan From webraviteja at gmail.com Tue Jan 2 10:36:01 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 2 Jan 2007 07:36:01 -0800 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> Message-ID: <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Ivan Voras wrote: > Ramdas wrote: > > Well, > > > > I need to add users from a web interface for a web server, which runs > > only Python. I need to add users, set quotas and in future even look at > > managing ip tables to limit bandwidth. > > > > I know os.system(), but this has to be done through a form entry > > through a web interface. > > > > Anyways thanks, do advise if there more pythonic solutions > > What you're looking for is actually a pretty complex thing. You *could* > in theory manage /etc/passwd (and its "shadow" file) - you can find > crypto primitives like MD5 and DES on the 'net, but note that you must > run your script under the 'root' account in order to write (and even > read!) the passwd database. The same goes for using os.system and the > built-in OS utility. Be aware of security implications if you're running > your web server under the root account. How about invoking scripts with SUID root set? From could.net at gmail.com Fri Jan 26 06:02:33 2007 From: could.net at gmail.com (Frank Potter) Date: 26 Jan 2007 03:02:33 -0800 Subject: how to remove c++ comments from a cpp file? In-Reply-To: References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> <1169805244.879280.235660@v45g2000cwv.googlegroups.com> Message-ID: <1169809353.681105.183260@j27g2000cwj.googlegroups.com> Thank you! On Jan 26, 6:34 pm, Gabriel Genellina wrote: > At Friday 26/1/2007 06:54, Frank Potter wrote: > > >[CODE] > >import re > > >f=open("show_btchina.user.js","r").read() > >f=unicode(f,"utf8") > > >r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) > >f_new=r.sub(ur"",f) > > >open("modified.js","w").write(f_new.encode("utf8")) > >[/CODE] > > >And, the problem is, it seems that only the last comment is removed. > >How can I remove all of the comments, please?Note that it's not as easy as simply deleting from // to end of line, > because those characters might be inside a string literal. But if you > can afford the risk, this is a simple way without re: > > f = open("show_btchina.user.js","r") > modf = open("modified.js","w") > for line in f: > uline=unicode(line,"utf8") > idx = uline.find("//") > if idx==0: > continue > elif idx>0: > uline = uline[:idx]+'\n' > modf.write(uline.encode("utf8")) > modf.close() > f.close() > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya!http://www.yahoo.com.ar/respuestas From bdesth.quelquechose at free.quelquepart.fr Tue Jan 2 07:54:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Jan 2007 13:54:23 +0100 Subject: Difference between __init__ (again) and nothing ... In-Reply-To: References: Message-ID: <459a4fe5$0$322$426a34cc@news.free.fr> Stef Mientki a ?crit : > Marc 'BlackJack' Rintsch wrote: > >> In , Stef Mientki wrote: >> >>> What's the difference between using __init__ and using nothing, >>> as the examples below. >>> >>> class cpu: >>> PC = 4 >> >> >> This is a *class attribute*. It's the same for all instances of `cpu`. >> >>> class cpu: >>> def __init__: def __init__(self): >>> self.PC = 4 By convention, ALL_UPPER names have a 'symbolic constant' semantic. Since Python is a very 'free' language (no attribute access restriction, no symbolic constants etc), it *strongly* relies on conventions. >> >> This is an *instance attribute* which is set in every instance of `cpu`. >> > thanks Marc, > > Oh so obvious, why didn't I discovered that myself ;-) Perhaps because it may not be that obvious at first sight ?-) (that is, until you really understand Python's object model, which is really different from most mainstream OOPLs object models...) From http Sat Jan 27 13:26:41 2007 From: http (Paul Rubin) Date: 27 Jan 2007 10:26:41 -0800 Subject: IP address of webserver References: <1169918690.690636.42690@a75g2000cwd.googlegroups.com> Message-ID: <7xlkjofhr2.fsf@ruckus.brouhaha.com> "Johny" writes: > So I know that www.google.com has 209.85.129.147 IP address. > But how can I find it directly from Python script? >>> import socket >>> print socket.gethostbyname('www.google.com') 66.102.7.147 >>> From ptmcg at austin.rr.com Wed Jan 24 00:40:21 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jan 2007 21:40:21 -0800 Subject: Simple Matrix class In-Reply-To: References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> Message-ID: <1169617221.481444.135820@v45g2000cwv.googlegroups.com> > The points should be aligned on a log-log plot to be a power function. > As Robert Kern stated before, this problem should be not worse than > O(n**3) - how have you implemented it? > Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05 X 3**n. As for the implementation, it's pretty much brute force. Here is the code itself - the cacheValue decorator memoizes the calculated inverse for the given Matrix. @cacheValue def det(self): "Function to return the determinant of the matrix." if self.isSquare(): if self.numRows() > 2: multiplier = 1 firstRow = self[1] tmp = self._rows[1:] rangelentmp = range(len(tmp)) col = 0 detsum = 0 for val in firstRow: if val: #~ tmp2 = Matrix([ RowVector(t[0:col]+t[col+1:]) for t in tmp ]) tmp2 = self.getCachedMatrix([ RowVector(t[0:col]+t[col+1:]) for t in tmp ]) detsum += ( multiplier * val * tmp2.det() ) multiplier = -multiplier col += 1 return detsum if self.numRows() == 2: return self[1][1]*self[2][2]-self[1][2]*self[2][1] if self.numRows() == 1: return self[1][1] if self.numRows() == 0: return 0 else: raise MatrixException("can only compute det for square matrices") def cofactor(self,i,j): i-=1 j-=1 #~ tmp = Matrix([ RowVector(r[:i]+r[i+1:]) for r in (self._rows[:j]+self._rows[j+1:]) ]) tmp = self.getCachedMatrix([ RowVector(r[:i]+r[i+1:]) for r in (self._rows[:j]+self._rows[j+1:]) ]) if (i+j)%2: return -tmp.det() else: return tmp.det() #~ return (-1) ** (i+j) * tmp.det() @cacheValue def inverse(self): if self.isSquare(): if self.det() != 0: ret = Matrix( [ RowVector( [ self.cofactor(i,j) for j in self.colrange() ] ) for i in self.rowrange() ] ) ret *= (1.0/self.det()) return ret else: raise MatrixException("cannot compute inverse for singular matrices") else: raise MatrixException("can only compute inverse for square matrices") From sjmachin at lexicon.net Mon Jan 29 18:29:12 2007 From: sjmachin at lexicon.net (John Machin) Date: 29 Jan 2007 15:29:12 -0800 Subject: Conversion of string to integer In-Reply-To: <1170100085.505577.211470@v33g2000cwv.googlegroups.com> References: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> <1170100085.505577.211470@v33g2000cwv.googlegroups.com> Message-ID: <1170113352.231928.151960@p10g2000cwp.googlegroups.com> On Jan 30, 6:48 am, "witte... at hotmail.com" wrote: > On Jan 29, 2:55 pm, "jupiter" wrote: > > > > > Hi guys, > > > I have a problem. I have a list which contains strings and numeric. > > What I want is to compare them in loop, ignore string and create > > another list of numeric values. > > > I tried int() and decimal() but without success. > > > eq of problem is > > > #hs=string.split(hs) > > hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"] > > > j=0 > > for o in range(len(hs)): > > print hs[o],o > > p=Decimal(hs[o]) > > if p > 200: j+=j > > print "-"*5,j > > print "*"*25 > > > I could be the best way to solve this ......? > > > @nilfunction isinstance can help you to determine the type/class of an > object: > > py>hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"] > py> > py>for i in hs: > py> if isinstance(i, str): > py> print str(i) > py> elif isinstance(i, float): > py> print float(i) > py> elif isinstance(i, int): > py> print int(i) > py> else: > py> print 'dunno type of this element: %s' % str(i) > popopopopop > 254.25 > pojdjdkjdhhjdccc > 25452.25 Call me crazy, but I can't understand what the above code is meant to demonstrate. (1) All of the elements in "hs" are *known* to be of type str. The above code never reaches the first elif. The OP's problem appears to be to distinguish which elements can be *converted* to a numeric type. (2) if isinstance(i, some_type) is true, then (usually) some_type(i) does exactly nothing that is useful Awaiting enlightenment ... John From jgodoy at gmail.com Sat Jan 6 10:36:14 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 06 Jan 2007 13:36:14 -0200 Subject: Python re expr from Perl to Python References: Message-ID: <877iw0dv69.fsf@gmail.com> "Michael M." writes: > In Perl, it was: > > > ## Example: "Abc | def | ghi | jkl" > ## -> "Abc ghi jkl" > ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st pipe). > $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; > > ## -- remove [ and ] in text > $na =~ s/\[//g; > $na =~ s/\]//g; > # print "DEB: \"$na\"\n"; > > > # input string > na="Abc | def | ghi | jkl [gugu]" > # output > na="Abc ghi jkl gugu" > > > How is it done in Python? The simplest form: >>> na="Abc | def | ghi | jkl [gugu]" >>> na_out = na.replace('def', '').replace(' | ', ' ').replace(' ', ' ').replace('[', '').replace(']', '').strip() >>> na_out 'Abc ghi jkl gugu' >>> Another form: >>> na_out = ' '.join(na.split(' | ')).replace('[', '').replace(']', '').replace(' def', '') >>> na_out 'Abc ghi jkl gugu' >>> There is the regular expression approach as well as several other alternatives. I could list other (simpler, more advanced, etc.) alternatives, but you can also play with Python by yourself. If you have a more concrete specification, send it to the group. -- Jorge Godoy From steve at holdenweb.com Tue Jan 30 00:14:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Jan 2007 05:14:33 +0000 Subject: The reliability of python threads In-Reply-To: <45B90118.5010408@mvista.com> References: <45B90118.5010408@mvista.com> Message-ID: Carl J. Van Arsdall wrote: > Aahz wrote: >> [snip] >> >> My response is that you're asking the wrong questions here. Our database >> server locked up hard Sunday morning, and we still have no idea why (the >> machine itself, not just the database app). I think it's more important >> to focus on whether you have done all that is reasonable to make your >> application reliable -- and then put your efforts into making your app >> recoverable. >> > Well, I assume that I have done all I can to make it reliable. This > list is usually my last resort, or a place where I come hoping to find > ideas that aren't coming to me naturally. The only other thing I > thought to come up with was that there might be network errors. But > i've gone back and forth on that, because TCP should handle that for me > and I shouldn't have to deal with it directly in pyro, although I've > added (and continue to add) checks in places that appear appropriate > (and in some cases, checks because I prefer to be paranoid about errors). > > >> I'm particularly making this comment in the context of your later point >> about the bug showing up only every three or four months. >> >> Side note: without knowing what error messages you're getting, there's >> not much anybody can say about your programs or the reliability of >> threads for your application. >> > Right, I wasn't coming here to get someone to debug my app, I'm just > looking for ideas. I constantly am trying to find new ways to improve > my software and new ways to reduce bugs, and when i get really stuck, > new ways to track bugs down. The exception won't mean much, but I can > say that the error appears to me as bad data. I do checks prior to > performing actions on any data, if the data doesn't look like what it > should look like, then the system flags an exception. > > The problem I'm having is determining how the data went bad. In > tracking down the problem a couple guys mentioned that problems like > that usually are a race condition. From here I examined my code, > checked out all the locking stuff, made sure it was good, and wasn't > able to find anything. Being that there's one lock and the critical > sections are well defined, I'm having difficulty. One idea I have to > try and get a better understanding might be to check data before its > stored. Again, I still don't know how it would get messed up nor can I > reproduce the error on my own. > > Do any of you think that would be a good practice for trying to track > this down? (Check the data after reading it, check the data before > saving it) > Are you using memory with built-in error detection and correction? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From leonel.gayard at gmail.com Wed Jan 3 12:48:08 2007 From: leonel.gayard at gmail.com (leonel.gayard at gmail.com) Date: 3 Jan 2007 09:48:08 -0800 Subject: A python library to convert RTF into PDF ? Message-ID: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> Hi, Does anyone know a good python library to convert a RTF file into PDF ? This should be done automaticaly: I have a web page that takes some values and inserts them into a RTF template, resulting in an RTF file. However, I cannot send the output back to the user in RTF, it must be sent in PDF instead, so I need to convert the result. So, what library can I use to convert from RTF to PDF ? GPL / BSD Libraries are welcome. Thanks Leonel From mhellwig at xs4all.nl Thu Jan 18 10:15:34 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 18 Jan 2007 16:15:34 +0100 Subject: Would a Dutch speaker please check this wiki page please? In-Reply-To: References: Message-ID: <45af8edf$0$336$e4fe514c@news.xs4all.nl> Stef Mientki wrote: > skip at pobox.com wrote: >> Got a note about a new page on the Python Wiki: >> >>>>>>> "Wade" == Wade McDaniel writes: >> >> http://wiki.python.org/moin/Selcuk_Altun >> >> I suspect it's junk since it doesn't seem to mention Python and the >> website >> it mentions doesn't seem to exist. Still, just in case... > The only (incorrect) Dutch sentence on the whole site is: > "Welkom op me site www.keriwar.nl", > which should have been > "Welkom op mijn site www.keriwar.nl" Well actually in the next sentence "De site is online als je vragen hebt lees eerst te F.A.Q." is incorrect too, "te F.A.Q." is grammatical and logical incorrect, should be "de F.A.Q.". Indeed it's not Afrikaans but just incorrect use of Dutch and not related to python. -- mph From bruno.desthuilliers at websiteburo.com Thu Jan 11 11:59:22 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Thu, 11 Jan 2007 17:59:22 +0100 Subject: globals accros modules In-Reply-To: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> Message-ID: <45a66cea$0$289$426a34cc@news.free.fr> stef a ?crit : > >> >> Change a=1 to amodule.a=1 >> If you find yourself doing tricks with the module globals, think about >> redesigning your application. >> > Of course I completely agree with you. > > But ... > if you're moving from MatLab to Python, > and want to show your collegaes, > with how little effort they can reuse all their existing MatLab routines > in Python, > then the global issue is a real pain !! > > You can explain your collegaes, that > - the startindex of arrays changes from 1 to 0 > - slices are upto, instead of including the final border > - indention is th? key > And tell them about all beautiful things in Python, > but tell them that they are going to loose all their globals ??? It's a feature. Globals are definitively a BadThing(tm). > cheers, > Stef Mientki > From tony at PageDNA.com Mon Jan 1 18:01:00 2007 From: tony at PageDNA.com (Tony Lownds) Date: Mon, 1 Jan 2007 15:01:00 -0800 Subject: PEP 3107 Function Annotations for review and comment In-Reply-To: <1167688435.399538.318990@48g2000cwx.googlegroups.com> References: <1167492896.292605.15040@48g2000cwx.googlegroups.com> <1167580455.349588.234610@v33g2000cwv.googlegroups.com> <1167688435.399538.318990@48g2000cwx.googlegroups.com> Message-ID: <0F352C8B-A752-4B9E-A30E-906FB0440DF3@PageDNA.com> On Jan 1, 2007, at 1:53 PM, Paul Boddie wrote: > It's true that for the area to be explored, which I know you've been > doing, one first has to introduce an annotation scheme that can > then be > used by things like pylint. I'd like to see assertions about the > usefulness of such annotations verified by modified versions of tools > like pylint before changes to the language are made, mostly because > such assertions seem to be more conjecture than prediction. In other > words, the changes should be advocated, implemented and tested in a > closed system before being introduced as wider language changes, > especially given that Python has already seen a number of speculative > changes which were made in anticipation of certain needs that > subsequently appeared to be less significant than first thought. > I can understand reluctance to change the language, keep in mind this is Python-3000 not Python 2.x, and even accepted features do get removed sometimes, like the access statement. I'm sure that feature qualifies as a speculative change -- I'd be curious to what other ones you were thinking about. At least one such modified tool exists: pydoc. That will display annotations. Does that count? It's not easy to develop syntax in a closed system that ISN'T python itself, especially when part of the point is to consolidate the ways in which function arguments and return types get annotated, and to do so as readably as possible. > Another thing I find worrying about function annotations is the > ambivalence around their purpose: the feature is supposedly great for > static typing, but when confronted over the consequences of having > developers spray type declarations everywhere, we're told that they > aren't really meant for such things and that type declarations are > only > an example of what annotations could do. Here, the sales department > and > the engineering department really have to get together and get their > story straight. Can you point out any specific text from the PEP you derived this from? Then "sales" can work from something specific :) Thanks -Tony From pink at odahoda.de Mon Jan 22 11:18:38 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 22 Jan 2007 17:18:38 +0100 Subject: Is there a better way to implement this: References: Message-ID: Michael Yanowitz wrote: > Hello: > > I wrote the code below (much irrelevant code removed). > This doesn't quite work. What I wanted it to do was > a) Execute function ftimed, which takes a function and a timeout > in seconds. > b) This will also execute function abort() as a thread. > This function just runs for the specified > number of seconds and returns. > However, before it returns, throws an exception. > c) If test() is still running when abort() is > finished, ftimed() should catch the exception and > return. > > It is catching the exception, however it continues running the function. > Why does it continue and not return? The exception is raised in the thread that executes the abort() function. The exception does not get caught and terminates this thread. The other (main) thread is unaffected - exceptions are local to a thread and there is currently no (portable) way to raise an exception in another thread. > What am I missing, or is there a better way to > implement this (having ftimed() return when the > abort-timer time is exceeded? You may use the signal.alarm() function, if you are on a UNIXoid system and you have only a signle time-out at a time (e.g. not nested). > import time, thread, sys > > thread_finished = "MAX RUN TIME EXCEEDED!" > > def abort (seconds): > start_time = time.time() > while ((time.time() - start_time) < seconds): > time.sleep(0.01) any reason for not using time.sleep(seconds) here? > print "script run time exceeded max_run_time of", seconds, "seconds." > raise thread_finished > return > > > def test(): > i = 0 > while (True): > time.sleep(1) > print "HELLO", i > i+=1 > > > def ftimed (func, seconds): > thread.start_new_thread (abort, (seconds,)) > > try: > func() > except thread_finished: > print "Timeout" > return > > ftimed (test, 30) > print "Script finished" -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From kavithapython at yahoo.co.in Mon Jan 22 03:31:37 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Mon, 22 Jan 2007 08:31:37 +0000 (GMT) Subject: newbie question Message-ID: <618640.79082.qm@web7806.mail.in.yahoo.com> Hi, i wrote a simple script (which follows) to insert a table in the database.i could execute this query and get the result in python shell.but when i open "my sql enterprise manager" i couldnt find the table"animals".it would be so kind of you if someone could help me,,, import dbi import odbc conn=odbc.odbc("DSN=mydatabase;UID=xxx;PWD=yyy") cursor=conn.cursor() cursor.execute("Create table animals(parent char(50),child char(50))") cursor.execute("insert into animals values('lion','cub')") cursor.execute("insert into animals values('goat','lamb')") cursor.execute("select * from animals") print cursor.fetchall() Rgds Kavitha --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Wed Jan 24 13:57:11 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 12:57:11 -0600 Subject: Type casting a base class to a derived one? In-Reply-To: <1169664145.4910.22.camel@portable-evil> References: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> <1169664145.4910.22.camel@portable-evil> Message-ID: <4866bea60701241057t13776d34ya516c2c24e7119bb@mail.gmail.com> On 1/24/07, Cliff Wells wrote: > On Thu, 2007-01-11 at 08:41 -0600, Chris Mellon wrote: > > On 11 Jan 2007 15:01:48 +0100, Neil Cerutti wrote: > > > On 2007-01-11, Frederic Rentsch wrote: > > > > If I derive a class from another one because I need a few extra > > > > features, is there a way to promote the base class to the > > > > derived one without having to make copies of all attributes? > > > > > > > > class Derived (Base): > > > > def __init__ (self, base_object): > > > > # ( copy all attributes ) > > > > ... > > > > > > > > This looks expensive. Moreover __init__ () may not be available > > > > if it needs to to something else. > > > > > > > > Thanks for suggestions > > > > > > How does it make sense to cast a base to a derived in your > > > application? > > > > > > > I can't figure out any circumstance when you'd need to do this in > > Python. Upcasting like this is something you do in statically typed > > languages. I suspect that the OP doesn't really believe dynamic > > casting works and doesn't want to pass a derived class for some > > reason. > > I actually encountered a need to do so (and I recalled seeing this > thread which is why I'm replying to it now). I've got a dispatch system > based on object type. Objects come from an external source (an ORM), so > I can't efficiently set their types at the point of creation (nor would > I necessarily want to). However, in different contexts, I may want them > to be dispatched differently (i.e as if they are a different type). In > fact, often the same object will be handled differently within two or > more contexts during the lifetime of that object. It would be nice to > be able to cast them to a derived class (which actually adds no new > methods or attributes, just changes the type) at that exact moment to > cause the dispatcher to handle them differently. > In Python, you can do this simply by re-assigning the __class__. I'm not convinced that your type system makes sense, here though. Any reasonable ORM should be able to persist and reload an object without losing the type information. Perhaps it's just a blind spot in the way I think about types. Assuming that the limitations of your ORM are external and out of your control, I would still ensure that whatever generic objects are being loaded from the ORM are converted into "real" objects of the correct type as soon as possible. For example, if you're persisting a file, you might just save the filename, and your ORM might return a string of the filename. I would want to convert that back into a file object ASAP, rather than writing all my code to accept either a FLO or a string and converting then. If you know what to upcast something to, then you know what type it is. If you know what type it is, then (in Python) you can simply assume it is of that type. What you're describing is a disjoint between your actual type system (that is, the one you have in code) and your theoretical type system (the one that you model your code around). To me, this is a huge red warning flag. > Now, that being said, it's quite possible the system *could* have been > designed to not dispatch based on type, but quite frankly it works quite > elegantly and naturally for everything but this one case. > Dispatch on type is perfectly natural. I'm not arguing against that, I'm arguing against the idea that it makes sense, in Python, to upcast. > Just pointing out that just because we don't see a need for something > doesn't invalidate it. It just makes it something we had thought of ;-) > I agree, but without a use case it's hard to understand the limits and needs of a requirement. So if you can't think of a need for a feature, it becomes difficult to understand how you might implement that feature. From luca.masini at i.eee.org Wed Jan 24 09:00:02 2007 From: luca.masini at i.eee.org (Luca Masini) Date: Wed, 24 Jan 2007 15:00:02 +0100 Subject: AFP library for Python Message-ID: Hi, googled for a Python library that support AFP but found only a PERL module: http://search.cpan.org/src/AUTRIJUS/Parse-AFP-0.24/ Maybe someone know of a similar library for Python ? PS: in alternative if there are some interested people we can implement it... :-)) Thanks Luca. From cliff at develix.com Wed Jan 24 13:42:24 2007 From: cliff at develix.com (Cliff Wells) Date: Wed, 24 Jan 2007 10:42:24 -0800 Subject: Type casting a base class to a derived one? In-Reply-To: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> References: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> Message-ID: <1169664145.4910.22.camel@portable-evil> On Thu, 2007-01-11 at 08:41 -0600, Chris Mellon wrote: > On 11 Jan 2007 15:01:48 +0100, Neil Cerutti wrote: > > On 2007-01-11, Frederic Rentsch wrote: > > > If I derive a class from another one because I need a few extra > > > features, is there a way to promote the base class to the > > > derived one without having to make copies of all attributes? > > > > > > class Derived (Base): > > > def __init__ (self, base_object): > > > # ( copy all attributes ) > > > ... > > > > > > This looks expensive. Moreover __init__ () may not be available > > > if it needs to to something else. > > > > > > Thanks for suggestions > > > > How does it make sense to cast a base to a derived in your > > application? > > > > I can't figure out any circumstance when you'd need to do this in > Python. Upcasting like this is something you do in statically typed > languages. I suspect that the OP doesn't really believe dynamic > casting works and doesn't want to pass a derived class for some > reason. I actually encountered a need to do so (and I recalled seeing this thread which is why I'm replying to it now). I've got a dispatch system based on object type. Objects come from an external source (an ORM), so I can't efficiently set their types at the point of creation (nor would I necessarily want to). However, in different contexts, I may want them to be dispatched differently (i.e as if they are a different type). In fact, often the same object will be handled differently within two or more contexts during the lifetime of that object. It would be nice to be able to cast them to a derived class (which actually adds no new methods or attributes, just changes the type) at that exact moment to cause the dispatcher to handle them differently. Now, that being said, it's quite possible the system *could* have been designed to not dispatch based on type, but quite frankly it works quite elegantly and naturally for everything but this one case. Just pointing out that just because we don't see a need for something doesn't invalidate it. It just makes it something we had thought of ;-) Regards, Cliff From dtgeadamo at yahoo.com Fri Jan 12 06:00:07 2007 From: dtgeadamo at yahoo.com (Viewer T.) Date: 12 Jan 2007 03:00:07 -0800 Subject: How to run external program? In-Reply-To: <1168594577.397453.320380@a75g2000cwd.googlegroups.com> References: <1168594577.397453.320380@a75g2000cwd.googlegroups.com> Message-ID: <1168599607.353569.295520@s34g2000cwa.googlegroups.com> Lad wrote: > How can I run external program from Python? > I use Python with XP > Thank you for help A possible way to do this is the following: Let's say we want to run a program called program.exe from the path C/Program/Program.exe. We would first need to import the os module and type the following: import os #import the os module path = 'C:/Program/Program.exe' #give the pathname of the external program as a string os.system(path) #execute the program from python using the os module There are many other ways, but this should work for short pathnames without spaces. From eurleif at ecritters.biz Tue Jan 9 04:29:55 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 09 Jan 2007 04:29:55 -0500 Subject: Colons, indentation and reformatting. In-Reply-To: <1168323145.393149.299540@v33g2000cwv.googlegroups.com> References: <1168323145.393149.299540@v33g2000cwv.googlegroups.com> Message-ID: <45a36074$0$15146$4d3efbfe@news.sover.net> Paddy wrote: > Thinking about it a little, it seems that a colon followed by > non-indented code that has just been pasted in could also be used by a > Python-aware editor as a flag to re-indent the pasted code. How would it reindent this code? if foo: print "Foo!" if bar: print "Bar!" Like this? if foo: print "Foo!" if bar: print "Bar!" Or like this? if foo: print "Foo!" if bar: print "Bar!" From stumblecrab at gmail.com Fri Jan 26 11:28:04 2007 From: stumblecrab at gmail.com (stumblecrab at gmail.com) Date: 26 Jan 2007 08:28:04 -0800 Subject: Activepython gcc and swig Message-ID: <1169828884.147638.254130@v33g2000cwv.googlegroups.com> Hello, I've looked at the swig example in the back of "programming python" (Lutz). Using gcc to compile a swig wrapper I'm getting lots of errors. Instead of using the cygwin python, I'm trying to point swig to my activepython installation. I'm doing this because my modules are all win32 installed, and not cygwin installed. Can anyone help me? I'm pointing to C:/python24/include and C:/python24/Libs. ************* Here are the errors ******************* $ gcc -c example.c example_wrap.c -Ic:/python24/include -Ic:/python24/Lib In file included from c:/python24/include/Python.h:82, from example_wrap.c:112: c:/python24/include/intobject.h:41: error: parse error before "PyInt_AsUnsignedL ongLongMask" c:/python24/include/intobject.h:41: warning: data definition has no type or stor age class In file included from c:/python24/include/Python.h:84, from example_wrap.c:112: c:/python24/include/longobject.h:37: warning: parameter names (without types) in function declaration c:/python24/include/longobject.h:39: error: parse error before "PyLong_AsLongLon g" c:/python24/include/longobject.h:39: warning: data definition has no type or sto rage class c:/python24/include/longobject.h:40: error: parse error before "PyLong_AsUnsigne dLongLong" c:/python24/include/longobject.h:40: warning: data definition has no type or sto rage class c:/python24/include/longobject.h:41: error: parse error before "PyLong_AsUnsigne dLongLongMask" c:/python24/include/longobject.h:41: warning: data definition has no type or sto rage class ************************************************************************************************** From steve at holdenweb.com Tue Jan 30 00:22:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Jan 2007 05:22:45 +0000 Subject: pdf to text In-Reply-To: References: <86714$45b9254c$54d1d767$3741@news.chello.no> Message-ID: tubby wrote: > Dieter Deyke wrote: >>> sout = os.popen('pdftotext "%s" - ' %f) > >> Your program above should read: >> >> sout = os.popen('pdftotext "%s" - ' % (f,)) > > What is the significance of doing it this way? It's actually just nit-picking - as long as you know f is never going to be a tuple then it's perfectly acceptable to use a single value as the right-hand operand. Of course, if f ever *is* a tuple (with more than one element) then you will get an error: >>> for f in ['string', ('one-element tuple', ), ("two-element", "tuple")]: ... print 'Nit: pdftotext "%s" - ' % (f,) ... print 'You: pdftotext "%s" - ' %f ... Nit: pdftotext "string" - You: pdftotext "string" - Nit: pdftotext "('one-element tuple',)" - You: pdftotext "one-element tuple" - Nit: pdftotext "('two-element', 'tuple')" - Traceback (most recent call last): File "", line 3, in TypeError: not all arguments converted during string formatting >>> So there is potentially some value to it. But we often don't bother. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From wanjunfeng at gmail.com Wed Jan 17 04:33:42 2007 From: wanjunfeng at gmail.com (Kevin Wan) Date: 17 Jan 2007 01:33:42 -0800 Subject: I wrote a C++ code generator in Python, would anyone please help me to review the code? :) In-Reply-To: <1168991250.445208.159020@v45g2000cwv.googlegroups.com> References: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> <1168991250.445208.159020@v45g2000cwv.googlegroups.com> Message-ID: <1169026422.364202.115170@v45g2000cwv.googlegroups.com> I've added a document for fgen. Please check it. Thanks, Kevin mensanator at aol.com wrote: > Kevin Wan wrote: > > fgen is a free command line tool that facilitates cross platform c++ > > development, including header generation, cpp file generation, makefile > > generation, unit test framework generation, etc. > > > > http://sf.net/projects/fgen > > > > I'm not very familiar with Python. Any feedback are appreciated! > > No documentation? > > Am I supposed to reverse engineer all the source files to figure out > how I'm > supposed to use it? > > > Or > > anyone like to develop it with me? > > > > Thanks. From t.googlegroups at mohme.org Wed Jan 31 10:01:51 2007 From: t.googlegroups at mohme.org (Thomas) Date: 31 Jan 2007 07:01:51 -0800 Subject: Can't install Turbogears (with pysqlite) on Windows In-Reply-To: <1170231106.741090.249460@j27g2000cwj.googlegroups.com> References: <1170231106.741090.249460@j27g2000cwj.googlegroups.com> Message-ID: <1170255711.117403.4990@v33g2000cwv.googlegroups.com> The solution can be found here: http://groups.google.com/group/turbogears/browse_thread/thread/2dc72464a48fde94 From paddy3118 at netscape.net Mon Jan 1 22:00:07 2007 From: paddy3118 at netscape.net (Paddy) Date: 1 Jan 2007 19:00:07 -0800 Subject: OO question In-Reply-To: References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> <1167631258.804660.154490@n51g2000cwc.googlegroups.com> Message-ID: <1167706807.899031.87920@a3g2000cwd.googlegroups.com> Steven D'Aprano wrote: > On Sun, 31 Dec 2006 22:00:58 -0800, Paddy wrote: > > >> def save(self, filename): > >> self.currentfile = file(filename, "w") > >> for address in self.addresses: > >> self.save_one_address(address.export()) > >> self.currentfile.close() > >> self.currentfile = None > > > > Small addition. > > If a class does a save then it should also do the load of the data too. > > What, you've never heard of a write-only file? > Ahh /dev/null ;-) - Paddy. From larry.bates at websafe.com Mon Jan 22 17:49:06 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 22 Jan 2007 16:49:06 -0600 Subject: module check In-Reply-To: <1169477715.178874.223290@51g2000cwl.googlegroups.com> References: <1169477715.178874.223290@51g2000cwl.googlegroups.com> Message-ID: Victor Polukcht wrote: > Can anybody suggest a correct way of checking in python module exists > and correctly installed from python program. > Not sure I understand the question, but I'll try: try: import yourmodule except: print "Can't import yourmodule" -Larry From sean at datafly.net Wed Jan 24 19:34:19 2007 From: sean at datafly.net (Sean Schertell) Date: Thu, 25 Jan 2007 09:34:19 +0900 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: <45b72b0d$0$5107$ba4acef3@news.orange.fr> Message-ID: <49E1CCC0-D22F-4411-B192-429E42045578@datafly.net> Not to totally hijack the thread -- but since you're all talking about best GUI frameworks. Any thoughts on the best looking framework for OS X only? Is there any way to write little Python apps that will launch in OS X using OS X widgets? Thanks, Sean On Jan 25, 2007, at 8:33 AM, dimitri pater wrote: > > > On 1/24/07, Laurent Rahuel wrote: Hi, > > I known this can be impossible but what about an "HTML" GUI ? > Yep, I think you should consider a HTML GUI. I have just finished a > project using CherryPy running on localhost. The big advantage is > that the app runs on Linux, Mac and Win using a browser without any > problem. You can use css and js to polish the user interface and > usability of your application. > > regards, > Dimitri > --- > You can't have everything. Where would you put it? -- Steven Wright > --- > please visit www.serpia.org > -- > http://mail.python.org/mailman/listinfo/python-list :::: DataFly.Net :::: Complete Web Services http://www.datafly.net From grante at visi.com Fri Jan 5 12:41:55 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 17:41:55 -0000 Subject: Dividing integers...Convert to float first? References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> Message-ID: <12pt3f3kc1jmcf8@corp.supernews.com> On 2007-01-05, Jonathan Smith wrote: > >>> from __future__ import division > >>> 1/2 > 0.5 $ python Python 2.4.3 (#1, Dec 10 2006, 22:09:09) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import LotteryNumbers File "", line 1 SyntaxError: future feature LotteryNumbers is not defined >>> Damn. I guess it's back to work then. -- Grant Edwards grante Yow! It's a lot of fun at being alive... I wonder if visi.com my bed is made?!? From nagle at animats.com Wed Jan 31 22:36:25 2007 From: nagle at animats.com (John Nagle) Date: Thu, 01 Feb 2007 03:36:25 GMT Subject: division by 7 efficiently ??? In-Reply-To: <1170299594.491478.310430@a34g2000cwb.googlegroups.com> References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> <1170299594.491478.310430@a34g2000cwb.googlegroups.com> Message-ID: krypto.wizard at gmail.com wrote: > Its not an homework. I appeared for EA sports interview last month. I > was asked this question and I got it wrong. I have already fidlled > around with the answer but I don't know the correct reasoning behind > it. The answer to that question is that the fastest way to divide by 7 is to use the divide instruction. You'd have to go down to a really old 8-bit microprocessor like the Intel 8051 to find something where bit-twiddling like that pays off. And no way would this be a win in Python, which is interpreted. John Nagle From danb_83 at yahoo.com Fri Jan 5 01:13:26 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 Jan 2007 22:13:26 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> <459DCC77.2030708@gmx.net> Message-ID: <1167977606.551848.49160@11g2000cwr.googlegroups.com> On Jan 4, 11:57 pm, belinda thom wrote: ... > So, back to my question: is a catalog of standard python errors > available? I've looked on the python site but had no success. >>> [name for name in dir(__builtins__) if name.endswith('Error')] ['ArithmeticError', 'AssertionError', 'AttributeError', 'EOFError', 'EnvironmentError', 'FloatingPointError', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'ReferenceError', 'RuntimeError', 'StandardError', 'SyntaxError', 'SystemError', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'ValueError', 'ZeroDivisionError'] From gagsl-py at yahoo.com.ar Wed Jan 3 18:25:35 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Jan 2007 20:25:35 -0300 Subject: import order or cross import In-Reply-To: References: Message-ID: <7.0.1.0.0.20070103202254.056c5758@yahoo.com.ar> At Wednesday 3/1/2007 07:56, Duncan Booth wrote: >However, you really should try to separate scripts from modules otherwise >the double use as both __main__ and a named module is going to come back >and bite you. I second this. Something with a __main__ can use (import) other modules, but shoud not be used (imported) by anyone. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From carsten at uniqsys.com Tue Jan 2 08:43:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 02 Jan 2007 08:43:38 -0500 Subject: Special Characters (Unicode, Ascii) in Python and MySQL In-Reply-To: <1167717459.802890.96740@n51g2000cwc.googlegroups.com> References: <1167717459.802890.96740@n51g2000cwc.googlegroups.com> Message-ID: <1167745418.3387.8.camel@dot.uniqsys.com> On Mon, 2007-01-01 at 21:57 -0800, ronrsr wrote: > I have an MySQL database called zingers. The structure is: > > zid - integer, key, autoincrement > keyword - varchar > citation - text > quotation - text > > I am having trouble storing text, as typed in latter two fields. > Special characters and punctuation all seem not to be stored and > retrieved correctly. > > Special apostrophes and single quotes from Microsoft Word are causing a > special problem, even though I have ''ed all 's > > perhaps the encoding of the database itself should be different? it is > currenlty latin_swedish_ci > > Input and output is through a browser. > > I think my problem may be that I need to encode the string before > saving it in the databse. Can anyone point me in the right direction > here? > > > > here's the error message: > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position > 95: ordinal not in range(128) > args = ('ascii', "update zingers set keywords = > 'a;Action;b;Religi... \n \n \n ' where zid = 422", 95, 96, 'ordinal not > in range(128)') > encoding = 'ascii' > end = 96 > object = "update zingers set keywords = 'a;Action;b;Religi... \n > \n \n ' where zid = 422" > reason = 'ordinal not in range(128)' > start = 95 > > > > the characters I am trying to add are startquote and endquote copied > and pasted from Microsoft Word. > > > > Can anyone help me on this? Apparently not, since you've already posted this problem on December 18th and got various responses. Did you read http://effbot.org/pyfaq/how-do-i-escape-sql-values-when-using-the-db-api.htm as Fredrik suggested in the earlier thread? -Carsten From dtgeadamo at yahoo.com Sun Jan 28 11:41:26 2007 From: dtgeadamo at yahoo.com (Viewer T.) Date: 28 Jan 2007 08:41:26 -0800 Subject: Python interfacing with COM Message-ID: <1170002486.751749.23180@m58g2000cwm.googlegroups.com> I am quite a newbie and I am trying to interface with Microsoft Word 2003 COM with Python. Please what is the name of the COM server for Microsoft Word 2003? From metsakuri at gmail.com Thu Jan 4 03:34:53 2007 From: metsakuri at gmail.com (tonisk) Date: 4 Jan 2007 00:34:53 -0800 Subject: pow() works but sqrt() not!? In-Reply-To: References: Message-ID: <1167899693.759071.51450@31g2000cwt.googlegroups.com> you forgot to import math module >>> import math >>> math.sqrt(9) 3.0 if you want math functions to your current namespace use: >>> from math import * -- T?nis On Jan 4, 10:13 am, "siggi" wrote: > Hi all, > > this is a newbie question on : > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on > win32 > PC with WinXP > > Inhttp://www.python.org/doc/2.3.5/lib/module-math.html > I read: > > "sqrt( x) Return the square root of x." > > Now the test for module math with function pow(): > --------------------------------------------------->>> pow(9,9)387420489 > > Fine, but sqrt() fails: > ------------------->>> sqrt(9)I get this error message > > 'Traceback (most recent call last): > File "", line 1, in > sqrt(9) > NameError: name 'sqrt' is not defined' > > Same for sin() and cos(). ">>> Import math" does not help. Will I have to > define the sqrt() function first? If so, how? > > Please help! > > Thank you, > > Siggi From cvanarsdall at mvista.com Wed Jan 24 11:58:51 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 24 Jan 2007 08:58:51 -0800 Subject: The reliability of python threads Message-ID: <45B7904B.90303@mvista.com> Hey everyone, I have a question about python threads. Before anyone goes further, this is not a debate about threads vs. processes, just a question. With that, are python threads reliable? Or rather, are they safe? I've had some strange errors in the past, I use threading.lock for my critical sections, but I wonder if that is really good enough. Does anyone have any conclusive evidence that python threads/locks are safe or unsafe? Thanks, Carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From deets at nospam.web.de Wed Jan 31 06:57:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 31 Jan 2007 12:57:56 +0100 Subject: another newbie question: why should you use "*args" ? References: Message-ID: <52bei4F1n0f69U1@mid.uni-berlin.de> stef wrote: > > why should I use *args, > as in my ignorance, > making use of a list (or tupple) works just as well, > and is more flexible in it's calling. > So the simple conclusion might be: never use "*args", > or am I overlooking something ? Yup. For example decorators, that wrap functions. If you do that, you want to return a function that captures all passed arguments, does something, and then invokes the original function with the original arguments. Like this: def logging_decorator(f): def _f(*args, **kwargs): print "calling %r with (%r, %r)", % (f, args, kwargs) return f(*args, **kwargs) return _f @logging_decorator def im_just_a_function(some, argument, and, other=None): pass Diez From gagsl-py at yahoo.com.ar Mon Jan 8 13:48:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 15:48:26 -0300 Subject: More Efficient fnmatch.fnmatch for multiple patterns? In-Reply-To: <1168279822.921033.267210@v33g2000cwv.googlegroups.com> References: <1168279822.921033.267210@v33g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070108154603.036d5708@yahoo.com.ar> At Monday 8/1/2007 15:10, abcd wrote: >I am using fnmatch.fnmatch to find some files. The only problem I have >is that it only takes one pattern...so if I want to search using >multiple patterns I have to do something like.... > >patterns = ['abc*.txt', 'foo*'] > >for p in patterns: > if fnmatch.fnmatch(some_file_name, p): > return True > >...is there a built-in function that will match using multiple patterns? matched = any(fnmatch(filename, p) for p in patterns) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gantgold at yahoo.com Tue Jan 16 12:16:02 2007 From: gantgold at yahoo.com (gandalf gold) Date: Tue, 16 Jan 2007 09:16:02 -0800 (PST) Subject: smtplib question Message-ID: <20070116171602.72920.qmail@web62308.mail.re1.yahoo.com> Hi everyone, I was trying out smtplib and found out that I can email to anyone in my domain but not to an email address not in the domain. From browsing on the web, it seems that this has to do with the configuration of the mail server. The mail server in my organization is MS exchange. Obviously I can email to any email address from my MS outlook. What's the easiest way to fix the program? Thanks. - gan import sys, smtplib fr = "xxx at yyy.com" to = "xxx at zzz.com" # will not work line = "testing" subj = "subject line" msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (fr, to, subj, line) server = smtplib.SMTP("EXCHCLUSTER.ccis.edu") server.set_debuglevel(1) server.sendmail(fr, [to], msg) server.quit() ____________________________________________________________________________________ Do you Yahoo!? Everyone is raving about the all-new Yahoo! Mail beta. http://new.mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From stuart at bmsi.com Mon Jan 22 19:51:48 2007 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 22 Jan 2007 19:51:48 -0500 Subject: Best way to document Python code... References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: On Mon, 22 Jan 2007 17:35:18 -0500, Stuart D. Gathman wrote: > The HTML generated by pydoc doesn't link to standard modules properly. > They are generated as relative links. So it can't be used without > modification for generating docs for a web page about a python package. > > I'm struggling with the same issue. Coding Python is so much easier than > Java. However documenting Java is so much easier than Python. Just > include doc comments, run javadoc, and voila! Wow! I just tried epydoc, and it is every bit as easy as javadoc and with similar output. Too bad it isn't standard. But the comments and docstrings it parses work fine with pydoc also. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From kentsin at gmail.com Tue Jan 2 20:08:27 2007 From: kentsin at gmail.com (kent sin) Date: Wed, 3 Jan 2007 09:08:27 +0800 Subject: Filename encoding on XP Message-ID: What encoding does the NTFS store the filename? I got some downloaded files, some with Chinese filename, I can not backup them to CD because the name is not accepted. I use walk, then print the filename, there are some ? in it, but some Chinese characters were display with no problem. I suspect the encoding of the filename is not unicode. How do I find out more about this? -- Sin Hang Kin. From bedouglas at earthlink.net Sun Jan 14 19:36:58 2007 From: bedouglas at earthlink.net (bruce) Date: Sun, 14 Jan 2007 16:36:58 -0800 Subject: python - process id Message-ID: <109f01c7383d$45666f10$0301a8c0@tmesa.com> hi... is there a way to have a test python app, get its' own processID. i'm creating a test python script under linux, and was wondering if this is possible.. also, i've tried using an irc client to join the irc #python channel, and for some reason i keep getting the err msg saying that the 'address is banned' i've never been to the python channel, but i'm using dsl, so i'm getting a dynamic address.. and yeah, i've tried changing the address a number of times.. thanks From paddy3118 at netscape.net Tue Jan 9 02:29:56 2007 From: paddy3118 at netscape.net (Paddy) Date: 8 Jan 2007 23:29:56 -0800 Subject: Colons, indentation and reformatting. (2) In-Reply-To: <45a33a24$0$7658$4c368faf@roadrunner.com> References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> <45a33a24$0$7658$4c368faf@roadrunner.com> Message-ID: <1168327796.187713.107530@38g2000cwa.googlegroups.com> Paul McGuire wrote: > "Paddy" wrote in message > news:1168323368.592642.314130 at i15g2000cwa.googlegroups.com... > >I was just perusing a Wikipedia entry on the "off side rule" at > > http://en.wikipedia.org/wiki/Off-side_rule . > > It says that the colon in Python is purely for readability, and cites > > our FAQ entry > > http://www.python.org/doc/faq/general.html#why-are-colons-required-fo... > > . > > However, near the top of the Alternatives section, it states that for C > > type, curly braces using languages: > > "An advantage of this is that program code can be automatically > > reformatted and neatly indented without fear of the block structure > > changing". > > > > Thinking about it a little, it seems that a colon followed by > > non-indented code that has just been pasted in could also be used by a > > Python-aware editor as a flag to re-indent the pasted code. > > > > Tell me it is not so, or I will be editing the Wikipedia page I think. > > > > - Paddy. > > > No, the ambiguity comes in when you have a nested construct within another > nested construct. Here is some (fake) code where all the indentation was > lost after pasting through a badly-behaved newsreader (this is NOT real > code, I know that it wont really run, I'm just trying to demonstrate the > indentation issue): > > while x: > a = 100 > if b > 3: > a += 1 > b += 1 > > Here are some valid indented versions: > > while x: > a = 100 > if b > 3: > a += 1 > b += 1 > > while x: > a = 100 > if b > 3: > a += 1 > b += 1 > > while x: > a = 100 > if b > 3: > a += 1 > b += 1 > > while x: > a = 100 > if b > 3: > a += 1 > b += 1 > > The colons alone are not sufficient to tell us which is correct. > > -- Paul Won't the following rules work when pasting complete Python statements and complete lines, after other lines in an editor: lets call the line after which the block is to be pasted the paste line, and the original indent of the first line of the copied block to be pasted the copy indent. If the paste line ends in a colon then the copy indent must be greater than the paste line indent, or the copy block should be re-indented on pasting to make it so. If the paste line does not end in a colon then the copy block indent should be equal too or less than the paste line indent. If this is not the case then the user should be asked wether to re-indent the copy block to be equal to, or de-dented w.r.t. the paste line indent prior to pasting. - Paddy. From citronelu at yahoo.com Mon Jan 8 15:45:45 2007 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 8 Jan 2007 12:45:45 -0800 Subject: Execute binary code In-Reply-To: References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> Message-ID: <1168289145.319706.199950@11g2000cwr.googlegroups.com> Larry Bates wrote: > What you are asking is a virus/trojan "like" program. There's no reason > you shouldn't be able to write the code to TEMP directory and execute it. > > -Larry No, it is not about a trojan, but I guess it's pointless to try to convince you otherwise. It's not about being able to write the code to TEMP directory and execute it, it's about not wanting to do so. -Cornelius From vinoth.3v at gmail.com Sat Jan 13 00:55:28 2007 From: vinoth.3v at gmail.com (=?utf-8?B?4K614K6/4K6p4K+L4K6k4K+N?=) Date: 12 Jan 2007 21:55:28 -0800 Subject: How can I integrate RPC with WSGI ??? Message-ID: <1168667728.272747.186210@a75g2000cwd.googlegroups.com> How can I integrate RPC with WSGI ??? is any methods for it?? From bjourne at gmail.com Sat Jan 6 19:54:00 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 7 Jan 2007 00:54:00 +0000 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <740c3aec0701061654g6a3b53e9h6403343784f026e6@mail.gmail.com> On 6 Jan 2007 16:07:05 -0800, time.swift at gmail.com wrote: > Coming from a C++ / C# background, the lack of emphasis on private data > seems weird to me. I've often found wrapping private data useful to > prevent bugs and enforce error checking.. > > It appears to me (perhaps wrongly) that Python prefers to leave class > data public. What is the logic behind that choice? Google for "python for consenting adults" Or ask yourself the opposite question. Why does C++ and C# prefer more private data? It is given that emphasizing private data (encapsulation) leads to more internal complexity and more lines of code because you have to write getters and setters and stuff. With that in mind, why do you think that data encapsulation makes code less error prone? Can you prove it? Or do you have anecdotal evidence of where data encapsulation saved your ass? IMHO, that data hiding is good, is one of those ideas that have been repeated so much that virtually everyone thinks it is true. But Python proves that it isn't necessarily so. -- mvh Bj?rn From 12cc104 at gmail.com Sun Jan 7 23:53:21 2007 From: 12cc104 at gmail.com (proctor) Date: 7 Jan 2007 20:53:21 -0800 Subject: regex question Message-ID: <1168232001.377605.236270@11g2000cwr.googlegroups.com> hello, i hope this is the correct place... i have an issue with some regex code i wonder if you have any insight: ================ import re, sys def makeRE(w): print w + " length = " + str(len(w)) reString = "r'" + w[:1] w = w[1:] if len(w) > 0: for c in (w): reString += "|" + c reString += "'" print "reString = " + reString return reString test = sys.argv[1] stg = sys.argv[2] while test: print "test = ", test print "stg = ", stg rx_a = re.compile(makeRE(test)) i = rx_a.search(stg).start() print "i = " + str(i) id = test.find(stg[i]) test = test[:id] + test[id+1:] print "test == ", test stg = stg[:i] + stg[i+1:] print ================ i get the following output: ================ test = abc stg = defabc abc length = 3 reString = r'a|b|c' i = 4 test == ac test = ac stg = defac ac length = 2 reString = r'a|c' Traceback (most recent call last): File "aaaa.py", line 21, in ? i = rx_a.search(stg).start() AttributeError: 'NoneType' object has no attribute 'start' ================= i am fairly new to this, and can't see the reason for the error. what am i missing? btw, i think there are simpler ways to go about this, but i am doing it this way (regexs) for a bit of a challenge and learning experience. thanks to all! sincerely, proctor From indy90 at gmail.com Thu Jan 25 12:18:12 2007 From: indy90 at gmail.com (Indy) Date: Thu, 25 Jan 2007 19:18:12 +0200 Subject: asyncore.dispatcher.handle_read Message-ID: <725281c20701250918i31fd8a68xd1911af92cfb02a6@mail.gmail.com> Greetings. I am writing an asynchronous server, and I use the standard library's module asyncore. I subclass asyncore.dispatcher. handle_accept works just right, that is, when a client socket makes a request to connect to my server socket, things that I set in handle_accept definition, happen. So, it is OK. But, the problem is that handle_read does not work as expected. Things I set in handle_read definition, do not happen when a client socket sends me data. Why? Is this a known problem? Please, can you help me? Thanks a lot, in advance. Best regards, Aristotelis Mikropoulos -- Programs must be written for people to read, and only incidentally for machines to execute. From py at th.on Tue Jan 23 19:10:49 2007 From: py at th.on (py) Date: Wed, 24 Jan 2007 00:10:49 GMT Subject: smtplib starttls gmail example Message-ID: Hmm, my last post seems to have been redirected to /dev/null. Anyhoo. Jean Paul, I read your code with interest. Does twisted also raise the apparently well-known and often ignored socket error, and do you supposed this error has something to do with the fact that the trailing \n.\n is encrypted? the error msg reports something about premature eof. altho one would suppose the commands and data are decrpyted before the smtp daemon sees them.... -dave From horpner at yahoo.com Wed Jan 10 11:14:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Jan 2007 17:14:28 +0100 Subject: Working with named groups in re module References: Message-ID: On 2007-01-10, Fredrik Lundh wrote: > Neil Cerutti wrote: >> A found some clues on lexing using the re module in Python in >> an article by Martin L?wis. > >> Here, each alternative in the regular expression defines a >> named group. Scanning proceeds in the following steps: >> >> 1. Given the complete input, match the regular expression >> with the beginning of the input. >> 2. Find out which alternative matched. > > you can use lastgroup, or lastindex: > > http://effbot.org/zone/xml-scanner.htm > > there's also a "hidden" ready-made scanner class inside the SRE > module that works pretty well for simple cases; see: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/457664 Thanks for the excellent pointers. I got tripped up: >>> m = re.match('(a+(b*)a+)', 'abbbbaa') >>> dir(m) ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start'] There are some notable omissions there. That's not much of an excuse for my not understanding the handy docs, but I guess it can can function as a warning against relying on the interactive help. I'd seen the lastgroup definition in the documentation, but I realize it was exactly what I needed. I didn't think carefully enough about what "last matched capturing group" actually meant, given my regex. I don't think I saw "name" there either. ;-) lastgroup The name of the last matched capturing group, or None if the group didn't have a name, or if no group was matched at all. -- Neil Cerutti We dispense with accuracy --sign at New York drug store From jon at ffconsultancy.com Tue Jan 2 20:14:20 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 03 Jan 2007 01:14:20 +0000 Subject: Writing more efficient code References: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> <1167687229.430930.197720@v33g2000cwv.googlegroups.com> <459989ec$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> <1167699678.310643.140480@n51g2000cwc.googlegroups.com> Message-ID: <459b03e5$0$8725$ed2619ec@ptn-nntp-reader02.plus.net> bearophileHUGS at lycos.com wrote: > Jon Harrop: >> I think most people could pick up the core ideas in a day and start >> writing working programs. > > Probably I am not that intelligent, I probably need some months :-) But > that language has many good sides, and one day I'll probably try to > learn it a bit. It is very cool, and there are a growing number of resources about these languages. You might also like to try Microsoft's F#, which runs under .NET. >> Mathematica is expensive but learning to use pattern matching is much >> easier than learning how to write a pattern matcher and much less tedious >> than reimplementing it yourself all the time (which is exactly what the >> OP will end up doing). > > I see. This is a very old post of mine, at the bottom there are few > notes about the Mathematica pattern matching syntax: > http://groups.google.com/group/comp.lang.python/msg/93ce3e9a08f5e4c7 Yes. Lots of good points. I think this sort of functionality would be a welcome addition to Python. What is the easiest way to add such functionality to Python? Perhaps it can be written in Python? > To avoid reimplementing it yourself all the time then maybe someone > (you?) can try to write a good pattern matcher for sequences for > CPython. With such system it may become less important to switch to a > different language ;-) I think that is an excellent idea. Who will pay me? ;-) -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet From conferrer at cuartilla.jp Wed Jan 24 10:26:46 2007 From: conferrer at cuartilla.jp (rocky) Date: 24 Jan 2007 15:26:46 GMT Subject: for thibaut: genuinely excellent pictures - umcu - (1/1) Message-ID: <76554951z39773H643349837Z967779246Q5681E633493486P@news.cuartilla.jp> Hello, Images, video, mp3 music, the real news from around the world... it's all inside waiting for you. You can find almost anything you are looking for. They offer some of the best premium newsgroup access anywhere. One thing I love about them, they don't keep log files of the news I read or files I download. Take a look, I know you'll love it as much as I do. They give you access to some of the best groups others may not carry. Great prices and support await you as you travel into the beautiful world of premium nntp access. Take a look at all the great features below and imagine! You'll LOVE it. Blazing fast downloads Posting allowed! Convenient thumbnail indexes Very long retention Keyword searchable Streaming audio and video 2,000,000 new posts each day Just go to http://www.newsdude.net and see why I love them so much. Have a great night! Jik hel ki vatnuzehgow newdebotrig totva fesmo, riwwi berte doy berwa guypo! At absa i ecci. Evwu rop marke huppu ok i anyo ovtu! Rog pi sahmilunyiw bashorasnah ak hud! Uh irfu up op awtu. I iskutagyuf ruz vi gevsigushes hitmi mafri dapji, futwe it diz nog ot ur atmi. Osja ahhe i emsekuzpid, bey fuhfa ni sokgeferjub gamtosogjos bah! Of uyho egsi i ecnu oscelapsob akso as i anyocazgol offu! I peh nohtiwedjip didpu gi huczu mevpapudpom jud fojru nohyu! Oj uzhi i ug embi if i apta! Uvbicerdez ecru i oywo. Okcemokfal iybo uz i ejyerowlur lis gi vum mudhi ev ar! Ahpes ewfu kir mi vizkihudduk rakbewuwgif pi wofco sewyuzucdiw zusso sin. Mapja hi dac nirgasaktik og i irbemommij iskapojbes uywa fiw, ri ut ivde i zot pepwomekyak tavru ki huz dal. Ref jecfo gi az umminizpez avga i eh abpa i ejne onwavepgeb, okca azzi i ler tuhtu dezpu! Ib i ofmijihvej on, i evda anyohiknah i ton, zajsocehmel tonci vuplutiv dezva sen ib olre azyu wum! Sahci nellu gento, pi ed et ewze i onricodjaf! Ufme ujmi ilni i evli if i wut zigyusagjez wi zosgofuptum, il ozne ujhu, ecwi awvu i ihcovogkat! Of nep vi coh hablazezgav ci pagro, zer bi firto ak esfi i un! Arwusuftez ahpo i or ovmo um i on egli opwi, sik pujgu fi cohzejokyaj tojkadeyref fi deryubavzon memde jibpu! Bid di biztukesdof ic pin oz av i eyrutarrav! Apya ehbi uvgi ugyi i amco ulmuzaccum! Ak i riw pez toyweb, vi bemba zovsinuscav fi bes duswa ji og ud, asze i azyi ey niz sos nurku. Bucbu ji er izlo liv sijgo ruy lacje ef i orpo! Intozudpup i otka oryedebbaz i addi akwo ec afre i ur, ehzonekhuv uste afju utvi er, i okza oh apsu ar uzhe ehtu! Umja al i jok cagluluwdek fun ri if bos debga zecju! Mi nof geska cahva gon ji mumsezuphop, tocvu ki juhyehemyog faygopubjow! Marwe luh dik pipge, hogli tuj ci wajmi fevni. Hi cammahibnul pebki deksa bowva nar sodtu peyfo kewgi! Ji lif jigpu li nadnis bobgehacboj jesne ti vazrofergih ik, avko i ubdulaltid asgorojhob i ebrokemlac uwvafukgat egbi i atyu ibkihamyeg! Amke em i awfosorbam bam uk ov kaf vi jakfuvapset. Up par ec! I uspu hul pi ut vel pi zulva patni. Oy ewle uspo azto. I agpi kik ah i osji ar i ecri wij, vi hozmu ap ifke usfu! Orro um ay i afyu ceh hi dibmu! Visbinivpuw ti jiv wagbe pezte lar. Dopli if agyo i ur evmelicbog az, ifyu i apru uzfo! I odto os i buv. Ik god tejge caj, vi jev fir mi hobbe. Vohjigiydap ji toj ac enlu i is apremubhuw i ehju osda ber, gul at i ohce, utheceswez ohci ak ukhu i ozvo iffo, ipzu ol evha i if, ujziruhpuf upke is i azdo asto i onyatewwil obhebikrid i ojyu. Den zazja wi serpa numbenidfav, sidve vuf li fumhulokwaw un avsi ewwi uthi i izbivahhel. Etku ged wej fafki vip ti ew asbi. Igpu keh pi dov vekvojavhuk ri hakge, is ejne gow! Pi kisre luzpeweggib kas law repri zecdu om i ezlu aj, i owja apgelidyek uk sal ev i rak. Necsakigtat mol rofce davbu mohke razca, bimso vuw hassi degha ni ramla, babyinokzak kojmazow ov ub, i uvse efhecujfup igde iwwi ucro arle i empu ossowargat, dap huv ci buf molko. Hen ki sugha kekpirojjoz ni hokku jij nobni tiv. Bofli vi tahja vep, pi af ebjubatwum sis lurni hacji ig i isni epfu! Amga ezke i osja nin jub fedba uh mov. Al ucra kow. Farsa ciknu uj as joy bi didde oz ahri bab. Dogme mi ot isle i bav cigtofitcos. Ti oz adnekorsob on eszu ewvu owri i atru. Ofge utto izwu gih ji negdesalfaz coy hi vochurecnan cacgepocmup. Si jobkav nop von, juyda vi hijja rog vulhe. Bonto uw i ogvigotmif esmapiwceg is igvi i ey. Em i inzeficnev hih, an i ergi apdo uzfe i okze iryu ukci den luj. Vofge si fob it zat uf ipzu i erki ic i oslulutcer. Onkubohyiz ab i avse ec i am al! Uz i inpegirmiw ses ji voprorurlak en. Ispo izsi sek wi reyci ug how vi luz wenpozommol, am ir kag ij ehso i av hil, el moc rem uy pug fi sikro. Gev mon iz ug ofvu ud onfo i uzyocujzun! Naz wudri sic li mozciporcaw dew honte si pefpu! Wezwurobvuz dilpu bi ik dar wogwu. Tawzi ci vih ib i ezyonecweg opcu i alze wib iy! Hin bi jat dazcudorzoh vi bugjo suh ri mohragepbol. Huvyihakseb wi luhtukonled rabladorrih pidjo. Ej did up! Ibti i uybulujwup rum om ozma ogdu i aw, bab ti ig kok di ay eywi. I ukzegarnov ekro avru ekka i oh urcutikvaz eg okfa. Zuv li had uk onma, i iskociftam etro kik wab likmo cokdu ey, eb efpem im ikyo ucfa i ayko eypakojbed! I elfetejjeb olma i av ip, updac i urnafetras uncejuwbif etvo ibba ihzo ah muc losbe. Ti cavlucihrid hubna pijye hi ag us i wab jefbi! Foksa degju ni feyjo bisli. Cob af izdo fib gopna! Jud coj kol li et opzunerfun set od i kac git! Wurpa uv i oyli ayrajilcaw i adze, ucwu poh ti nalde, jufyi al uvvi ceh gobju! Af i isya pep ki woc jehsogangup ni iz iy usce ed! I mid cargecascuw bew vi nogva wicyuguknum vum! Jofmo rujge ji tukto kut ep ot opju, epva i adji ocgocobjin i duy gabze ciwme ... From sndive at gmail.com Thu Jan 25 21:30:09 2007 From: sndive at gmail.com (sndive at gmail.com) Date: 25 Jan 2007 18:30:09 -0800 Subject: How do I build python with debug info? (and python module load questions) Message-ID: <1169778609.559899.26160@k78g2000cwa.googlegroups.com> I want to step into PyImport_ImportModule("my_foo") that's failing despite the my_foo.py being in the current directory. (PyRun_SimpleFileEx works on the exact same file). How would I run configure to build libpython with -g? I wonder if I should just keep using PyRun_SimpleFileEx. I want to be able to call arbitrary functions in the imported file/module using PyRun_SimpleString("import my_foo\nmy_foo.bar(whatever)") after the file is loaded. There is no '' in sys.path, I assume that should not affect PyImport_ImportModule to look in the current directory first. Does it? Thank you! From piotrlewalski at gmail.com Sat Jan 13 14:04:17 2007 From: piotrlewalski at gmail.com (piotr) Date: Sat, 13 Jan 2007 20:04:17 +0100 Subject: template engine References: <8764ba7oqf.fsf@gmail.com> Message-ID: On Sat, 13 Jan 2007 16:42:16 -0200, Jorge Godoy wrote: > Take a look at Kid (http://www.kid-templating.org/) and Genshi > (http://genshi.edgewall.org/). I've already done a short look at kid, but to be honest I don't like it's XML/Python syntax. I strongly prefer idea from SimpleTAL or HTMLTemplates where HTML and Python code are separated. But syntax is for me not so important like functionality so maybe I have to get back and look at kid again :) any other engines? :) thanks //peter From gagsl-py at yahoo.com.ar Sat Jan 13 09:55:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Jan 2007 11:55:30 -0300 Subject: ValueError from dict - some detail would be helpful References: <1168529175.794131.109390@77g2000hsv.googlegroups.com> Message-ID: "Facundo Batista" escribi? en el mensaje news:eo8agn$5au$1 at sea.gmane.org... > metaperl wrote: > >> File "/sw/lib/python2.5/csv.py", line 120, in _dict_to_list >> raise ValueError, "dict contains fields not in fieldnames" >> >> >> --- it would be nice if it said what field it was > > Yeap, nice and useful... but, for example, what'd happen if the fields > that are not in fieldnames are 10, or 100? How the message could be? The code inside _dict_to_list currently just stops at the first unknown key. Just report that - much better than nothing. http://sourceforge.net/tracker/index.php?func=detail&aid=1634717&group_id=5470&atid=355470 -- Gabriel Genellina From __peter__ at web.de Tue Jan 9 13:42:05 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Jan 2007 19:42:05 +0100 Subject: Question about using "with" References: Message-ID: Steven W. Orr wrote: >>From the tutorial, they said that the following construct will > automatically close a previously open file descriptor: > > ------------------- > #! /usr/bin/python > import sys > > for nn in range ( 1, len(sys.argv ) ): > print "arg ", nn, "value = ", sys.argv[nn] > with open(sys.argv[nn]) as f: > for line in f: > print line, > ------------------ > > but when I run it (with args) I get: > > 591 > ./cat.py cat.py > File "./cat.py", line 6 > with open(sys.argv[nn]) as f: > ^ > SyntaxError: invalid syntax > 592 > > > This example came from http://docs.python.org/tut/node10.html down in > section 8.7 > > Am I missing something? The with-statement only works in Python 2.5, and you have to enable it explicitly: >>> from __future__ import with_statement >>> with open("tmp.txt") as f: ... print len(f.read()) ... 15 >>> f.read() Traceback (most recent call last): File "", line 1, in ValueError: I/O operation on closed file Peter From parallelpython at gmail.com Sat Jan 13 13:32:50 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 13 Jan 2007 10:32:50 -0800 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: <1168713168.608367.221350@51g2000cwl.googlegroups.com> > Looks interesting, but is there any way to use this for a cluster of > machines over a network (not smp)? Networking capabilities will be included in the next release of Parallel Python software (http://www.parallelpython.com), which is coming soon. > Couldn't you just provide similar conveniences on top of MPI? Searching > for "Python MPI" yields a lot of existing work (as does "Python PVM"), > so perhaps someone has already done so. Yes, it's possible to do it on the top of any environment which supports IPC. > That's one more project... It seems that there is significant > interest in parallel computing in Python. Perhaps we should start a > special interest group? Not so much in order to work on a single > project; I believe that at the current state of parallel computing we > still need many different approaches to be tried. But an exchange of > experience could well be useful for all of us. Well, I may just add that everybody is welcome to start discussion regarding any parallel python project or idea in this forum: http://www.parallelpython.com/component/option,com_smf/Itemid,29/board,2.0 From no-spam at no-spam-no-spam.invalid Thu Jan 11 04:37:06 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 11 Jan 2007 10:37:06 +0100 Subject: Is there a way to protect a piece of critical code? In-Reply-To: References: Message-ID: Hendrik van Rooyen wrote: > "robert" wrote: > >> List .append() and .pop() will be atomic in any Python though its not > mentioned explicitely - otherwise it would be time to leave Python. >> There is also Queue.Queue - though it has unneccessary overhead for most > purposes. >> > am aware of Queue module - the same app uses it for something else. > I dont like too many try -- excepts in the code - I find they confuse > me when I try to read it later - and in this case I cannot block on waiting for > the queue to fill. pushing data objects through an inter-thread queue is a major source for trouble - as this thread shows again. Everybody builds up a new protocol and worries about Empty/Full, Exception-handling/passing, None-Elements, ... I've noticed that those troubles disappear when a functional queue is used - which is very easy with a functional language like Python. For example with http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 One would just use a cq=CallQueue() On the producer side one would just write the functional code one wants to execute in a target thread: cq.call( what_i_want_do_func ) The consumer/receiver thread would just do (periodically) a non-blocking cq.receive() => Without any object fumbling, protocol worries and very fast. And note: This way - working with functional jobs - one can also "protect a piece of critical code" most naturally and specifically for certain threads without spreading locks throughout the code. Even things which are commonly claimed "forbidden" (even when using lots of locks) can be magically done in perfect order and effectively this way. Think of worker threads doing things in the GUI or in master / database owner threads etc. Similarly discrete background thread jobs can be used in a functional style this way: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491280 ( an alternative for the laborious OO-centric threading.Thread which mostly is a lazy copy from Java ) or for higher job frequencies by using "default consumer threads" as also shown in the 1st example of http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 Robert From arkanes at gmail.com Wed Jan 10 11:31:50 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 10 Jan 2007 10:31:50 -0600 Subject: Execute binary code In-Reply-To: <1168445561.239053.140340@77g2000hsv.googlegroups.com> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> <1168355051.339026.211830@v33g2000cwv.googlegroups.com> <1168445561.239053.140340@77g2000hsv.googlegroups.com> Message-ID: <4866bea60701100831h53178d2o625dcefade7b14b2@mail.gmail.com> On 10 Jan 2007 08:12:41 -0800, sturlamolden wrote: > > Chris Mellon wrote: > > > This works fine if the binary data is "pure" asm, but the impresssion > > the OP gave is that it's a compiled binary, which you can't just "jump > > into" this way. > > You may have to offset the function pointer so the entry point becomes > correct. > That won't be enough. You basically would have to re-implement the OS loading process, handling relocations and loading any linked libraries. Possible, in theory, but very non-trivial. > -- > http://mail.python.org/mailman/listinfo/python-list > From Barry.Carroll at psc.com Mon Jan 8 16:25:52 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 8 Jan 2007 13:25:52 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A69@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: python-list-bounces+barry.carroll=psc.com at python.org [mailto:python- > list-bounces+barry.carroll=psc.com at python.org] On Behalf Of John Machin > Sent: Saturday, January 06, 2007 11:09 PM > To: python-list at python.org > Subject: Re: File Closing Problem in 2.3 and 2.4, Not in 2.5 > > Martin v. L?wis wrote: > > Carroll, Barry schrieb: > > > What I want to know is: > > > > > > * has anyone else encountered a problem like this, * how was the > > > problem corrected, * can the fix be retro-fitted to 2.5 and 2.4? > > > > From your description, I suspect an error in your code. Your description > > indicates that you don't expect to have more than five files open > > simultaneously. Yet, the error message "Too many open files" occurs when > > you open many more files (in the order of hundreds of files). > > > > It is very unlikely that there is a bug in Python where it would fail to > > close a file when .close() is explicitly invoked on it (as your > > description suggests that you do), so if you get that error message, it > > can only mean that you fail to close some files. > > I don't understand: the OP's description suggests nothing of the sort > to me. What he said was: > """ > In this way, a tree of Parser instances is created, each with a single > open file object. (BTW, recursive and circular references are not > allowed.) When each Parser instance comes to the end of its table, the > instance is explicitly destroyed, presumably destroying any objects it > holds, AND closing its open file. > """ > which I interpret as: he is doing del parser_instance, and *presuming* > (incorrectly) that attributes of parser_instance (including an open > file object) are magically whisked away instantly, instead of > later/maybe. He later says he explicitly closed the files, which fixed > what he alleges (incorrectly) to be a bug. > > To the OP: > (1) The del statement doesn't "destroy" anything. It unbinds the name > from the object in the current namespace, and decrements the object's > reference count. Only if the reference count is then zero will the > janitor be called in. > (2) Check the reference count on the parser_instance just before you > del it. You could be retaining a reference somewhere. > (3) Explicitly close all non-lightweight objects like files (even > read-only ones) and sockets rather than hoping they will go away. > > HTH, > John John: Thank you. I was afraid I had been totally misunderstood. We have retained the explicit file close in the current version of the Parser code. I still have a question, however. Python 2.3 and 2.4 both produce the "Too many open files" error on Windows XP Pro, but Python 2.5 does not. Running on the 2.5 interpreter, our program process all the table invocations with no errors, a total of over 650 file opens. Also, Python 2.3 on RedHat Fedora core 1 runs our program to completion with no errors. (I know, we are running pretty ancient SW here. Constraints unrelated to this question make that necessary.) Do you know why the error would appear on some combinations of OS and interpreter and not on others? Thanks again for your help. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From piotrlewalski at gmail.com Sat Jan 13 13:29:25 2007 From: piotrlewalski at gmail.com (piotr) Date: Sat, 13 Jan 2007 19:29:25 +0100 Subject: template engine Message-ID: Hi, I'm looking for a template engine that can give me names of required variables in parse time. Calculation of a value for a specific variable name could be possibly done in specified callback function. For example: $title #if user hello $user/name #else hello guest #endif for above document engine should call my function first giving an argument "title", then second time with argument "user", and optionally if result for user was not empty call function again with argument "user/name" then engine should replace specific placeholders with results of my callback function obviously this is just example syntax, I hope you catch the idea that would be nice if engine could work with non HTML documents. thanks in advance for your help, and sorry for my English :) //peter From skip at pobox.com Tue Jan 9 08:59:32 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Jan 2007 07:59:32 -0600 Subject: Using with CSV library in Python 2.2!!! In-Reply-To: <1168348224.843657.27330@42g2000cwt.googlegroups.com> References: <1168348224.843657.27330@42g2000cwt.googlegroups.com> Message-ID: <17827.40900.14680.844066@montanaro.dyndns.org> mohan> 1. Does Python 2.2 come with CSV library module or not? If yes, mohan> have I lost it somewhere?? As the docs for the csv module indicate, it was new in 2.3. mohan> 2. If Python 2.2 does not come with CSV module, is it possible to mohan> add the csv module to the Python root and start working?? You might find that it will work with 2.2, though you might have to make some source code changes to _csv.c to get it to compile. mohan> 3. If yes, where do I get this module from?? You can get both csv.py and _csv.c via ViewCVS: http://svn.python.org/view/*checkout*/python/tags/r236/Modules/_csv.c?content-type=text%2Fplain&rev=52574 http://svn.python.org/view/*checkout*/python/tags/r236/Lib/csv.py?content-type=text%2Fplain&rev=52574 Skip From duncan.booth at invalid.invalid Mon Jan 8 12:48:23 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jan 2007 17:48:23 GMT Subject: sys.exit versus raise SystemExit References: <45a26b70$0$32019$fa0fcedb@news.zen.co.uk> <1168273151.359419.118640@42g2000cwt.googlegroups.com> <45a27f06$0$31239$da0feed9@news.zen.co.uk> Message-ID: Will McGugan wrote: > wittempj at hotmail.com wrote: >> >> sys.exit() raises a SystemExit, see >> http://docs.python.org/lib/module-sys.html >> > Oh I know. I was just wondering if there was some sort of subtle 'best > practice' recommendation that I wasnt aware of for using sys.exit over > raising the exception manually. In the same way that 'open' is prefered > over 'file', even though they appear to do the same thing. 'open' is preferred when you are opening a file, 'file' is preferred when it is the type you want. That way you leave open the option to intercept the 'open' action without interfering with tests against the type. I guess in a similar way you should prefer the overridable sys.exit() function rather than using the exception directly. From bill.mill at gmail.com Wed Jan 10 11:21:15 2007 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 10 Jan 2007 11:21:15 -0500 Subject: Regex Question Message-ID: <797fe3d40701100821u74807093lcff2b9bd5ffe5359@mail.gmail.com> Hello all, I've got a test script: ==== start python code ===== tests2 = ["item1: alpha; item2: beta. item3 - gamma--", "item1: alpha; item3 - gamma--"] def test_re(regex): r = re.compile(regex, re.MULTILINE) for test in tests2: res = r.search(test) if res: print res.groups() else: print "Failed" ==== end python code ==== And a simple question: Why does the first regex that follows successfully grab "beta", while the second one doesn't? In [131]: test_re(r"(?:item2: (.*?)\.)") ('beta',) Failed In [132]: test_re(r"(?:item2: (.*?)\.)?") (None,) (None,) Shouldn't the '?' greedily grab the group match? Thanks Bill Mill bill.mill at gmail.com From nagle at animats.com Fri Jan 19 22:34:13 2007 From: nagle at animats.com (John Nagle) Date: Sat, 20 Jan 2007 03:34:13 GMT Subject: More M2Crypto issues In-Reply-To: References: <6u7sh.264$4H1.150@newssvr17.news.prodigy.net> Message-ID: Heikki Toivonen wrote: > John Nagle wrote: > >> OpenSSL version: "OpenSSL 0.9.7a Feb 19 2003" > > > Hmm, I've never actually used that old OpenSSL myself, just assumed from > the original author's notes that anything from 0.9.7 onward worked. > Guess not. I am thinking of changing the requirements to state which one > works... I think the oldest that I have personally tested may have been > 0.9.7d. I think older versions were built with an older OpenSSL and an older SWIG. The SWIG preprocessor has some limitations which can cause errors to be reported during the SWIG preprocessor phase. This problem in SWIG has hit other projects. See http://blog.gmane.org/gmane.comp.programming.swig.devel/month=20051201 where the Common LISP people had a similar problem. John Nagle From bthom at cs.hmc.edu Tue Jan 2 03:26:13 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Tue, 02 Jan 2007 00:26:13 -0800 Subject: doctesting Message-ID: <7EC2DA1E-229B-4005-A1EC-7FBBC8586B20@cs.hmc.edu> Hi, I'd like to write a tester script that I can place in one place (say ~/bin/python/tester.py) and then have it visible to me at the cmd- line (by setting the path variable appropriately). I have had no luck in getting it to work, however. It appears like the doctest code itself assumes that all modules to be imported lie in some directory other than the one I invoked the tester.py script from. In particular, simple imports in a .txt file like: >>> import foo fail even though I've started the script in a directory that contains file foo.py I only achieve success when I manually copy tester.py into this same directory (symlinks don't fix the problem). This is a real drag b/c it means I have to copy this tester.py routine into _every_ directory that contains a .txt python unit test file. From a code-reuse point of view, this is pretty hideous... Advice appreciated, --b From srikrishnamohan at gmail.com Tue Jan 23 14:17:43 2007 From: srikrishnamohan at gmail.com (km) Date: Wed, 24 Jan 2007 00:47:43 +0530 Subject: best package for a physical simulation? In-Reply-To: References: <60915.195.220.102.78.1169558458.squirrel@mailgate.phys.ens.fr> Message-ID: Hi, checkout MMTK package http://dirac.cnrs-orleans.fr/MMTK/ regards, KM On 1/24/07, Robert Kern wrote: > > sittner at lkb.ens.fr wrote: > > Hello everyone, > > i would like to use python to perform some simulation involving > collisions > > of colloidal particles. > > which is the best package/engine to do that in python? > > What kind of numerical methods does such simulation require? > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless > enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Thu Jan 25 12:41:09 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 25 Jan 2007 11:41:09 -0600 Subject: Python does not play well with others In-Reply-To: References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> Message-ID: <17848.60341.346203.660506@montanaro.dyndns.org> John> My main concern is with glue code to major packages. The John> connections to OpenSSL, MySQL, and Apache (i.e. mod_python) all John> exist, but have major weaknesses. I have no SSL experience or direct mod_python experience (I do use Myghty effectively), but I have used MySQLdb extensively in multi-threaded environments. There is a Python database API (PEP 249). As far as I know, MySQLdb implements this API well. I have personally never had problems. Andy Dustman, the author of the package is quite responsive to requests raised in the mysql-python forums on SourceForge (http://sourceforge.net/forum/?group_id=22307). If you have problems with MySQLdb, bring them up there. I'm sure Andy will respond. Skip From pavlovevidence at gmail.com Sat Jan 27 09:58:04 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 27 Jan 2007 06:58:04 -0800 Subject: assertions to validate function parameters In-Reply-To: References: Message-ID: <1169909883.944892.74390@k78g2000cwa.googlegroups.com> On Jan 25, 11:54 am, Matthew Wilson wrote: > Lately, I've been writing functions like this: > > def f(a, b): > > assert a in [1, 2, 3] > assert b in [4, 5, 6] > > The point is that I'm checking the type and the values of the > parameters. > > I'm curious how this does or doesn't fit into python's duck-typing > philosophy. The duck-typing thing fits into a wider philosophy of being liberal in what you accept. As you're constraining what a function accepts, it definitely goes against the philosophy. I suggest you not blindly slap assertions on every single function. Assertions should only be used to check for ostensibly impossible conditions. Therefore, guarding arguments like this is probably only a good idea for internal or private functions that you can personally guarantee will only be called with the right values. Personally, I find assertions are more helpful in complex situtations where I find myself having to maintain some sort of invariant. Some condition is supposed to always be true at this point, and my code relies on this. I've taken steps to maintain the invariant, but I could have made a mistake. So I throw an assertion in. If there's a leak somewhere, it will catch it. > I find that when I detect invalid parameters overtly, I spend less time > debugging. If it helps go ahead an use them. The world won't end if you use an assertion in a less than ideal situation. And, after all, if someone doesn't like it they can shut them off. > Are other people doing things like this? Any related commentary is > welcome. Well, there are examples of this usage of assert the standard library. Some public functions (off hand I can think of the threading module) use assertions to check for invalid arguments, a use I highly disagree with. The library shouldn't be making assertions on behalf of the users. If an AssertionError is raised from the threading module, it should be because there is a bug in the threading module, not because the user passed it a bad value. But, yes, it has been done. Carl Banks From wanjunfeng at gmail.com Tue Jan 16 01:47:48 2007 From: wanjunfeng at gmail.com (Kevin Wan) Date: 15 Jan 2007 22:47:48 -0800 Subject: I wrote a C++ code generator in Python, would anyone please help me to review the code? :) Message-ID: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> fgen is a free command line tool that facilitates cross platform c++ development, including header generation, cpp file generation, makefile generation, unit test framework generation, etc. http://sf.net/projects/fgen I'm not very familiar with Python. Any feedback are appreciated! Or anyone like to develop it with me? Thanks. From DustanGroups at gmail.com Wed Jan 31 07:48:57 2007 From: DustanGroups at gmail.com (Dustan) Date: 31 Jan 2007 04:48:57 -0800 Subject: another newbie question: why should you use "*args" ? In-Reply-To: References: Message-ID: <1170247737.232403.114850@k78g2000cwa.googlegroups.com> On Jan 31, 5:41 am, stef wrote: > why should I use *args, > as in my ignorance, > making use of a list (or tupple) works just as well, > and is more flexible in it's calling. Others have mentioned the instances in which it's actually useful - for catch-all arguments. But you also should take into consideration the aesthetics, since python is supposed to be an aesthetically nice language. > So the simple conclusion might be: never use "*args", > or am I overlooking something ? > > # method 1 > def execute (self, *args): > for i in range ( len(args) ): > ... do something > > # method 2 > def chunk_plot(self, list): > for i in range ( len(list) ): > .... do something It's bad practice to use built-ins like 'list' as a regular variable name. > # calling method 1: > execute (S[0], S[4] ) > > # calling method 2: > execute ( ( S[0], S[4] ) ) Let's take a look at those side-by-side: execute (S[0], S[4] ) execute ( ( S[0], S[4] ) ) Now, which one *looks* better? > # or *the extra flexibility) > mylist = ( S[0], S[4] ) > execute ( mylist ) Also, take into consideration the opposite end of the pole; you have your list of arguments (args), and your about to call a function that was declared something like this: def someFunction(arg1, arg2, arg3): # etc. Which is clearer? someFunction(*args) someFunction(args[0], args[1], args[2]) And if you've got a variable number of arguments, it becomes virtually impossible to avoid using the *args syntax. And that doesn't even begin to cover the need for **kargs! (which, if you haven't noticed, is generally used next to *args) It turns out that it's not really necessary in a static-typed language like java (although java 5.0 introduced it); it's the dynamic nature of python that makes these syntactic sugars necessary. And without them, function calls can get really ugly. > thanks, > Stef Mientki From bignose+hates-spam at benfinney.id.au Wed Jan 17 15:27:28 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 Jan 2007 07:27:28 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <740c3aec0701160837r33340866w5ddef3e09a0de537@mail.gmail.com> <873b6abp12.fsf@benfinney.id.au> <740c3aec0701170103k29c17df9xdb8c32a3a878ac00@mail.gmail.com> <87r6tu80kl.fsf@benfinney.id.au> <20070117144339.GL1906@loki> Message-ID: <87mz4h8klr.fsf@benfinney.id.au> Chuck Rhode writes: > Ben Finney wrote: > > > I recommend, instead, separate factory functions for separate > > input types. > > Uh, how 'bout separate subclasses for separate input types? The resulting object in each case would be the same type ('Rational'), with the same behaviour. Subclassing would make sense only if the resulting objects needed to have different behaviour in each case. -- \ "The power of accurate observation is frequently called | `\ cynicism by those who don't have it." -- George Bernard Shaw | _o__) | Ben Finney From carsten at uniqsys.com Mon Jan 1 15:53:44 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 01 Jan 2007 15:53:44 -0500 Subject: Missing erf() In-Reply-To: <17816.3619.126136.486222@montanaro.dyndns.org> References: <1167592158.085766.45140@48g2000cwx.googlegroups.com> <17816.3619.126136.486222@montanaro.dyndns.org> Message-ID: <1167684824.3550.8.camel@localhost.localdomain> On Sun, 2006-12-31 at 13:23 -0600, skip at pobox.com wrote: > rrenaud> Is there a reason why erf() is not included in the math > rrenaud> package? According to the following URL it looks like it has > rrenaud> been standard C since 1999. > > Python is implemented in the C89 dialect. Maybe Python 3.0 will be > implemented using C99. In the meantime, you could: 1) Patch mathmodule.c to add the missing function(s), or 2) Make a small extension module that exposes the missing function(s), or 3) Use ctypes to access libm directly. Something along the lines of this: >>> from ctypes import * >>> libm = CDLL("libm.so") >>> libm.erf.restype = c_double >>> libm.erf(c_double(0)) 0.0 >>> libm.erf(c_double(1)) 0.84270079294971489 >>> libm.erf(c_double(2)) 0.99532226501895271 Hope this helps, Carsten. From bdesth.quelquechose at free.quelquepart.fr Sat Jan 6 09:57:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Jan 2007 15:57:48 +0100 Subject: Pausing for Python Interpreter error messages... In-Reply-To: <1168058097.855006.229820@s80g2000cwa.googlegroups.com> References: <1168058097.855006.229820@s80g2000cwa.googlegroups.com> Message-ID: <459fb2b6$0$324$426a74cc@news.free.fr> redefined.horizons at gmail.com a ?crit : > I've written a few classes that I have been testing in IDLE. However, > every time I make a change to the classes based on the testing I have > to walk through all he steps of preparing the classes for testing > again. > > So I wrote a script that does all the set-up work for me. You may want to have a look at the unittest module then: http://docs.python.org/lib/module-unittest.html > The only > problem is when I run this script using the Python interpreter I can't > get the command prompt to stay up long enough for me to read the > message. > > How do I get the command prompt to stay up? first open the "command prompt", then launch your script from the command prompt. > Is there a way to run my > script and view the error message in IDLE? menu run->run module, or just hit the F5 key. > Thanks for the help. > > Scott Huey > > P.S. - I'm using Windows XP with the latest Python 2.3. > Python 2.3 is years old. Latest is 2.5. From adamgarstang at googlemail.com Mon Jan 15 18:47:45 2007 From: adamgarstang at googlemail.com (Adam) Date: 15 Jan 2007 15:47:45 -0800 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> Message-ID: <1168904865.253014.210140@m58g2000cwm.googlegroups.com> Stef Mientki wrote: > hello, > > Is there some handy/ nice manner to view the properties of some variable ? > As a newbie, I often want to see want all the properties of a var, > and also some corner values (large arrays) etc. > > Probably it's not so difficult, > but I don't see how to distinguish for example between a string and an > array. An array has a shape, a string not etc. > > > thanks, > Stef Mientki I am also a newbie so if this is not what you want I can't give much more as of yet. You can use type() to check what a Variable is. Usage: #-------------Python Code----------------------------- >>> aVar = ["zero", 1, float(2)] >>> type(aVar) >>> type(aVar[0]) >>> type(aVar[1]) >>> type(aVar[2]) >>> if type(aVar[1]) == int: print "test" test #-----------------End Code------------------------------- There are also function like len(). Usage: #-------------Python Code----------------------------- >>> len(aVar) 3 >>> len(aVar[0]) 4 #-----------------End Code------------------------------- Hope this helps. Adam From nagle at animats.com Wed Jan 24 23:43:27 2007 From: nagle at animats.com (John Nagle) Date: Thu, 25 Jan 2007 04:43:27 GMT Subject: Catching floating point errors from linked C code In-Reply-To: <1169696243.262973.188540@s48g2000cws.googlegroups.com> References: <1169696243.262973.188540@s48g2000cws.googlegroups.com> Message-ID: John Pye wrote: > Hi all > > I have some C code that is giving me some 'nan' values in some > calculations. The C code is wrapped using SWIG to give me a Python > module that I am then exercising through a unittest suite. > > It seems that I should expect the C code to throw floating point > exceptions (SIGFPE) and either the whole thing to abort, or for Python > to catch the errors and report them. Instead I'm getting neither. I > want to be able to track down the exact location of problems in my C > code. > > Is there something that Python does to turn on/off the catching of > divide-by-zero errors, eg by manipulating signal handlers > and/or settings? What platform are you on? Python is probably running with floating point exceptions disabled, but you can enable them in your C code, and restoring the floating point mode when you leave, if you want. This is probably only worth doing under a debugger, because otherwise you just end up with an aborted instance of Python. John Nagle From robert.kern at gmail.com Tue Jan 23 19:59:03 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Jan 2007 18:59:03 -0600 Subject: Simple Matrix class In-Reply-To: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> Message-ID: Paul McGuire wrote: > I've posted a simple Matrix class on my website as a small-footprint > package for doing basic calculations on matrices up to about 10x10 in > size (no theoretical limit, but performance on inverse is exponential). Why is that? A simple and robust LU decomposition should be no more than O(n**3). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ptmcg at austin.rr.com Mon Jan 29 04:51:42 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 29 Jan 2007 01:51:42 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170046719.708692.243290@s48g2000cws.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: <1170064302.264009.12650@p10g2000cwp.googlegroups.com> On Jan 28, 10:58 pm, "NoName" wrote: > Perl: > @char=("A".."Z","a".."z",0..9); > do{print join("", at char[map{rand @char}(1..8)])}while(<>); > > !!generate passwords untill U press ctrl-z > > Python (from CookBook): > > from random import choice > import string > print ''.join([choice(string.letters+string.digits) for i in > range(1,8)]) > > !!generate password once :( > > who can write this smaller or without 'import'? from random import choice pwdchars = ''.join(chr(c) for c in range(ord('a'),ord('z')+1)+ range(ord('A'),ord('Z')+1)+ range(ord('0'),ord('9')+1) ) while(True) : print ''.join(choice(pwdchars) for i in range(8)) (Note that you want to use range(8), not range(1,8), since range gives you the values [a,b) if two arguments are given, or [0,a) if only one is given, and it appears that you want 8-character passwords.) But really, there's nothing wrong with using import, and reusing known good code from the string module is better than reimplementing it in new code as I have done (less code === fewer opportunities for bugs). rand is not a built-in as it apparently is in Perl, but random is part of the core library, so all Python installs will have it available - likewise for string. -- Paul From rzantow at gmail.com Sat Jan 6 16:55:45 2007 From: rzantow at gmail.com (rzed) Date: Sat, 06 Jan 2007 16:55:45 -0500 Subject: still struggling, howto use a list-element as a name ? References: <182cf$45a00556$d443bb3a$17174@news.speedlinq.nl> Message-ID: Stef Mientki wrote in news:182cf $45a00556$d443bb3a$17174 at news.speedlinq.nl: >>> class Power_Supply(device): >>> pinlist = { >>> 0: ('GND', _DIG_OUT, _par2), >>> 1: ('VCC', _DIG_OUT, _par33) >>> } >> >> I may be confused about what you're after, but wouldn't something >> like this work? (I don't know what a _par2 object is; I've named >> it something here.) > _par2, is just (a reference to) a constant >> >> class Power_Supply(device): >> def __init__(self): >> self.pin = { >> 0:dict(Name='GND',Value=_DIG_OUT,something=_par2), >> 1:dict(Name='VCC',Value=_DIG_OUT,something=_par33), >> } > Why so complex, I need 10 or more parameters (or empty), > and then this becomes completely unreadable. > As this is part of the "user interface", > (I want that completely unknown with Python people, > write these lines), > I think my "pinlist" is much easier. > Whatever works for you. In your original example, you first created "pinlist" (which is actually a Python dict), and then used it to place values in an unspecified type named "pin" (which I took to be another dict). I just combined the two steps. You talk about the "pinlist" being easier ... I'm not sure what you mean. Easier to create? Maybe. But if you are then going to assign the values to names, then it doesn't strike me as easier to go through the two-step process. But as I said, I may be confused about what you are really trying to do. > >> for k in self.pin.keys(): >> self.__dict__[self.pin[k]['Name']] = self.pin[k] > thanks "rzed" ?, > that is exactly what I was looking for: > self.__dict__[self.pinlist[k][0]] = self.pin[k] I'm glad it helped. -- rzed From sjmachin at lexicon.net Sun Jan 7 20:06:10 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 Jan 2007 17:06:10 -0800 Subject: Working with Excel inside Python References: <1168205727.130771.257030@51g2000cwl.googlegroups.com> Message-ID: <1168218370.688414.171150@s80g2000cwa.googlegroups.com> gblais at cox.net wrote: > Or, you might want to look at two packages: > > xlrd > > pyExcelerator > > The first can "read" .xls files, and the second can write them. I've had > great results with both. > Hi Gerry, Thanks for the testimonial for xlrd :-) However I don't understand how a reasonable solution to the OP's requirement (translate a tab-separated file to a DBF file with a bit of slicing and dicing on the way) would have anything to do with .xls files, or Excel, or VB ... Cheers, John From horpner at yahoo.com Mon Jan 8 13:57:16 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 8 Jan 2007 19:57:16 +0100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <%Isoh.22447$X97.12337@newsfe18.lga> Message-ID: On 2007-01-08, Jussi Salmela wrote: > Neil Cerutti kirjoitti: >> In C one uses the pointer to opaque struct idiom to hide data. >> For example, the standard FILE pointer. > > To Neil Cerutti: If a programmer in C has got a pointer to some > piece of memory, that piece is at the mercy of the programmer. > There's no data hiding at all in this case. That's somewhat disingenuous. You get just as much data hiding with an opaque data type in C as you get in C++ or Java. -- Neil Cerutti Potluck supper: prayer and medication to follow. --Church Bulletin Blooper From edquichan at yahoo.com Thu Jan 18 14:01:17 2007 From: edquichan at yahoo.com (EdG) Date: 18 Jan 2007 11:01:17 -0800 Subject: Traversing the properties of a Class In-Reply-To: References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> Message-ID: <1169146877.454130.96550@s34g2000cwa.googlegroups.com> Thanks. Neil Cerutti wrote: > On 2007-01-18, EdG wrote: > > For debugging purposes, I would like to traverse the class > > listing out all the properties. > > This is the first thing that came to mind. > > def show_properties(cls): > for attr in dir(cls): > if isinstance(getattr(cls, attr), property): > print attr > > -- > Neil Cerutti > > -- > Posted via a free Usenet account from http://www.teranews.com From horpner at yahoo.com Wed Jan 17 07:42:52 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 17 Jan 2007 13:42:52 +0100 Subject: A note on heapq module References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <45ad0f6c$1@nntp0.pdx.net> <1168982702.903306.152940@m58g2000cwm.googlegroups.com> Message-ID: On 2007-01-16, bearophileHUGS at lycos.com wrote: > Scott David Daniels: >> I'd suggest some changes. It is nice to have Heaps with equal >> contents equal no matter what order the inserts have been >> done. Consider how you want Heap([1, 2, 3]) and Heap([3, 1, >> 2]) to behave. Similarly, it is nice to have str and repr >> produce canonical representations (I would skip the __str__ >> code, myself, though). Also, subclasses should get their >> identities tweaked as so: > > My version was a *raw* one, just an idea, this is a bit better: > http://rafb.net/p/nLPPjo35.html > I like your changes. In the beginning I didn't want to put > __eq__ __ne__ methods at all, because they are too much slow, > but being them O(n ln n) I think your solution is acceptable. > > Some methods may have a name different from the heap functions: > def smallest(self): > def push(self, item): > def pop(self): > def replace(self, item): > > Two things left I can see: I think the __init__ may have a > boolean inplace parameter to avoid copying the given list, so > this class is about as fast as the original heapify function > (but maybe such thing is too much dirty for a Python stdlib): One more idea, cribbed from the linked list thread elsewhere: it might be nice if your Heap could optionally use an underlying collections.deque instead of a list. I don't know how excellent Python's deque is, but it's possible a deque would provide a faster heap than a contiguous array. C++'s std::deque is the default implementation of C++'s std::priority_queue for that reason (unless I'm confused again). -- Neil Cerutti We will sell gasoline to anyone in a glass container. --sign at Santa Fe gas station From fsck_spam at telenet.be Wed Jan 17 14:06:47 2007 From: fsck_spam at telenet.be (Rikishi 42) Date: Wed, 17 Jan 2007 20:06:47 +0100 Subject: Making a simple script standalone References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: <7n8284-od9.ln1@whisper.very.softly> On Wednesday 17 January 2007 00:22, James Stroud wrote: >> There is nothing graphical, nothing fancy about the script. >> The only imports are: os, stat, string and time. >> >> Any suggestions on an - easy and clear - path to follow ? > > > pyinstaller + innosetup. I will look into it, thanks! Hope it's not as heavy as with py2exe... -- Research is what I'm doing, when I don't know what I'm doing. (von Braun) From nmm1 at cus.cam.ac.uk Thu Jan 18 17:43:26 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 18 Jan 2007 22:43:26 GMT Subject: How to find out if another process is using a file References: Message-ID: In article , Donn Cave writes: |> > |> |> > |> O_EXCL fails if the file exists at all - whether closed or open. |> > |> > Yes. In theory. In practice, it usually works on normal files, provided |> > that all opens are local. Under some circumstances, it will even work |> > for NFS mounted files, as far as I recall. |> |> Mm, by "fail", I meant |> |> An attempt to open with O_EXCL set will "fail" if the file exists at all, |> i.e., the file will not be opened, a negative value will be returned, |> and errno will be set to EEXIST. |> |> What I neglected to mention is that this effect obtains when O_EXCL |> is used in combination with O_CREAT. Without O_CREAT, O_EXCL doesn't |> mean anything and is ignored. |> |> If there is any significant difference between theory and practice |> in this matter, it's news to me. Actually, it is undefined behaviour in POSIX, and I have used a Unix where O_EXCL on its own failed if the file existed (of course, it also failed if it DIDN'T exist, because of the lack of O_CREAT). I can't remember which - perhaps AIX or OSF/1 (not DEC). But I was referring to a different problem. Some remote and parallel filing systems handle such things very badly, and it is often possible to create a file even if it exists and O_CREAT|O_EXCL is set. A similar remark applies to 'special' files, even on fairly mainstream, local filing systems. Regards, Nick Maclaren. From rzantow at gmail.com Sat Jan 20 08:57:37 2007 From: rzantow at gmail.com (rzed) Date: Sat, 20 Jan 2007 08:57:37 -0500 Subject: OT Annoying Habits (Was: when format strings attack) References: <01bc01c73c5f$75e8cfe0$03000080@hendrik> Message-ID: Dane Jensen wrote in news:mailman.2941.1169295400.32031.python-list at python.org: > On Friday 19 January 2007 22:51, Hendrik van Rooyen wrote: >> "Steven D'Aprano" wrote: >> > Or perhaps I should say: >> > >> > .snoitnevnoc >> > hsilgnE tpada )ylbissop revenehw( dluohs ew os dna ,naitraM >> > ton ,puorgswen egaugnal hsilgnE na no er'ew ,segaugnal hcus >> > era ereht fi neve tuB >> >> First I thought it was Welsh or Cornish or something. >> >> Then it was like being in my first year of school again- >> reading letter by letter. Never realised how difficult it is. >> >> I suppose it will improve with practice. > > Not to steer this topic even futher off topic, but this is > something that's been on my mind lately... > > The biggest problem with it that the letters were forwards and > not also backwards (and the parens). But then, it's my > understanding that as a left-handed person, reading and writing > backwards is far easier for me than for the majority that is > right-handed. Have any other lefties found that the case? How would anybody know? As a left-hander, I have found it easy enough to read backwards, but then, being left-handed forces a certain habit of adaptability in any case. Maybe that makes it easier to read backward, but that is not a task I'm often called on to do. It takes practice regardless. This subthread reminds me of my *highly secure* plaintext encryption system that would render the sentence as I think it looks vaguely Esperantonic (Esperantoid? Esperantic?), if anything. -- rzed From S.Mientki-nospam at mailbox.kun.nl Thu Jan 18 17:24:20 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 18 Jan 2007 23:24:20 +0100 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> <1168904865.253014.210140@m58g2000cwm.googlegroups.com> <8ab5f$45ad5c12$d443bb3a$7243@news.speedlinq.nl> <5d831$45aea748$d443bb3a$26464@news.speedlinq.nl> Message-ID: <3feaf$45aff382$d443bb3a$12046@news.speedlinq.nl> thanks Gabriel > str(key)[7:-2] => key.__name__ I didn't know that one > Nice to see you built a useful tool! It's a great way to learn a language. Yes, and this group is helping me a whole lot, thanks ! cheers, Stef Mientki From wescpy at gmail.com Fri Jan 12 17:56:16 2007 From: wescpy at gmail.com (wesley chun) Date: Fri, 12 Jan 2007 14:56:16 -0800 Subject: ANN: Python training course, Feb 7-10, San Francisco Message-ID: <78b3a9580701121456n7a8667d3odab40257532e0ed5@mail.gmail.com> apologies to all... this is the Intro course, not Advanced as the orig subject line stated, and it takes place Feb 7-9, 2007. On 1/12/07, wesley chun wrote: > FINAL REMINDER... we still have some seats left! > > What: (Intensive) Intro to Python > When: February 7-9, 2007 > Where: San Francisco (SFO/San Bruno), CA, USA > Web: http://cyberwebconsulting.com (click "Python Training" link) From grante at visi.com Fri Jan 5 10:16:09 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 15:16:09 -0000 Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> Message-ID: <12psqtppgi5cme6@corp.supernews.com> On 2007-01-05, king kikapu wrote: >> Python code is normally deployed as straight source code. > > But isn't this a problem of its own? I mean, many people do not feel > good if the know that their source code is lying around on other > machines... Are they embarassed by their code? -- Grant Edwards grante Yow! Can I have an IMPULSE at ITEM instead? visi.com From deets at nospam.web.de Sat Jan 13 15:18:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 13 Jan 2007 21:18:05 +0100 Subject: sqlobject 0.8.0b1 and python 2.5 In-Reply-To: References: Message-ID: <50st46F1hiu23U1@mid.uni-berlin.de> Daniel Nogradi schrieb: > Hi list, > > I get loads of DeprecationWarnings while using sqlobject 0.8.0b1 with > python 2.5. Does this mean that the sqlobject project is not very up > to date? Or should I just ignore them and happily use it? In general, > what's the status of sqlobject, will it be dropped altogether after > sqlobject2 is out? To my knowledge, the 0.8.x series is the current line of development, and has made major progress over the previous versions. What makes you think it will be stopped developing? And where does a sqlobject2 come from? Regarding the warnings: I presume pretty much projects will have these, cleaning up a code base, especially when the code is supposed to work with python versions down to 2.2 is a major task, not do be done to lightheartedly so to not risk introduction of errors. Diez From joshua at eeinternet.com Thu Jan 11 20:08:45 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 11 Jan 2007 16:08:45 -0900 Subject: Doing date/time + TZ math in python References: <459ee41c$0$4805$88260bb3@free.teranews.com> <1168123983.983339.163010@s80g2000cwa.googlegroups.com> Message-ID: <45a6d2eb$0$4777$88260bb3@free.teranews.com> wittempj at hotmail.com wrote: >> The problem is, how do I create a datetime object and tell it that it's >> America/Anchorage *daylight savings time* instead of whatever the system >> is >> currently set at? pytz only has America/Anchorage, and I saw no way to >> tell it explicitly that the timezone is in Daylight instead of Standard >> time (e.g. using AKST vs. AKDT for the time zone). >> >> I'm sure there is a way to do it, and I'm sure it's quite simple, but it >> hasn't jumped out at me yet. Is there a module that I haven't seen that >> would be better suited for this? > > It looks like3 you're 9 hours in this example: > http://docs.python.org/lib/datetime-tzinfo.html, see e.g. > http://www.worldtimezone.com/index12.php Right, I know I'm at GMT-9, and tzinfo correctly deduces that when it creates an object. But what if I were currently at GMT-8 (my time zone on daylight savings time) and I was importing data created during standard time? How would I create an object and tell it this is America/Anchorage on standard time, or conversely, how would I right now create and object and tell it to use daylight time? In other words, how can I explicitly specify whether or not the time object being created is daylight savings time or not? I did not see that option in the documentation reading I did. Thanks! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From rhamph at gmail.com Mon Jan 15 15:48:13 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 15 Jan 2007 12:48:13 -0800 Subject: Maths error In-Reply-To: References: Message-ID: <1168894093.278546.209850@m58g2000cwm.googlegroups.com> Nick Maclaren wrote: > The problem with it is that it is an unrealistically pessimal model, > and there are huge classes of algorithm that it can't handle at all; > anything involving iterative convergence for a start. It has been > around for yonks (I first dabbled with it 30+ years ago), and it has > never reached viability for most real applications. In 30 years, it > has got almost nowhere. > > Don't confuse interval methods with interval arithmetic, because you > don't need the latter for the former, despite the claims that you do. > > |> For people just getting into it, it can be shocking to realize just how > |> wide the interval can become after some computations. > > Yes. Even when you can prove (mathematically) that the bounds are > actually quite tight :-) I've been experimenting with a fixed-point interval type in python. I expect many algorithms would require you to explicitly round/collapse/whatever-term the interval as they go along, essentially making it behave like a float. Do you think it'd suitable for general-use, assuming you didn't mind the explicit rounding? Unfortunately I lack a math background, so it's unlikely to progress past an experiment. From jm.suresh at gmail.com Thu Jan 11 05:26:40 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 11 Jan 2007 02:26:40 -0800 Subject: dot operations Message-ID: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> Hi, Frequently I get to do like this: a = (1, 2, 3, 4) # some dummy values b = (4, 3, 2, 1) import operator c = map(operator.add, a, b) I am finding the last line not very readable especially when I combine couple of such operations into one line. Is it possible to overload operators, so that, I can use .+ for element wise addition, as, c = a .+ b which is much more readable. Similarly, I want to use .- , .*, ./ . Is it possible to do? thanks. - Suresh From ddvlad at gmail.com Sat Jan 27 04:10:13 2007 From: ddvlad at gmail.com (Vlad Dogaru) Date: 27 Jan 2007 01:10:13 -0800 Subject: Convert String to list of chars In-Reply-To: <11Duh.1840$G23.1501@newsreading01.news.tds.net> References: <11Duh.1840$G23.1501@newsreading01.news.tds.net> Message-ID: <1169889013.523506.256300@q2g2000cwa.googlegroups.com> On Jan 27, 9:18 am, Neil Cerutti wrote: > On 2007-01-27, juanef... at gmail.com wrote: > > > How can I convert a string to a char list? > > for example > > > "hello" --> ['h','e','l','l','o'] > > > I have been searching but I can't find my answers > list("hello") Wow, I've been using [c for c in 'hello'] for as long as I can remember needing it. Thanks! Vlad From tubby at bandaheart.com Thu Jan 18 20:02:31 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 18 Jan 2007 20:02:31 -0500 Subject: Determining when a file is an Open Office Document Message-ID: Silly question, but here goes... what's a good way to determine when a file is an Open Office document? I could look at the file extension, but it seems there would be a better way. VI shows this info in the files: mimetypeapplication/vnd.oasis.opendocument.textPK mimetypeapplication/vnd.oasis.opendocument.presentationPK etc. Not really a Python specific question but, how do you guys do this sort of thing? I've figured out how to break out the content.xml file in the new OOo XML format, and do re searching and matching on that, now I just need a fast, reliable way to determine when I need to do that versus just reading the file. Thanks, Tubby From vpolukcht at gmail.com Mon Jan 22 09:55:15 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 22 Jan 2007 06:55:15 -0800 Subject: module check Message-ID: <1169477715.178874.223290@51g2000cwl.googlegroups.com> Can anybody suggest a correct way of checking in python module exists and correctly installed from python program. From kylotan at gmail.com Thu Jan 11 06:43:53 2007 From: kylotan at gmail.com (Ben Sizer) Date: 11 Jan 2007 03:43:53 -0800 Subject: creating simple Python scripting interfaces via C++ In-Reply-To: <1168272267.679069.325890@38g2000cwa.googlegroups.com> References: <1168272267.679069.325890@38g2000cwa.googlegroups.com> Message-ID: <1168515833.590286.123330@o58g2000hsb.googlegroups.com> Ok, my first attempt at this creates proxy objects in Python, and stores a pointer to the C++ instance in the Python object. I cast that pointer to an int and pass it as a single parameter to the object's __init__ function. static PyObject* Actor_init(PyObject *self, PyObject *args) { PyObject* selfParam; PyObject* ptrValue; if (!PyArg_ParseTuple(args, "OO", &selfParam, &ptrValue)) return NULL; PyObject_SetAttrString(selfParam, "_cpp_ptr", ptrValue); Py_INCREF(Py_None); return Py_None; } I have no idea why self is always NULL, when I'm calling the functions as methods of an object. Any ideas why this is the case? For what it's worth I attach each method via the PyMethodDef -> PyCFunction_New -> PyMethod_New -> PyDict_SetItemString(classDict) route. To get data back from the C++ object to Python, I extract that value and cast it back to the appropriate pointer type. static PyObject* Actor_showName(PyObject *self, PyObject *args) { PyObject* selfParam; if (!PyArg_ParseTuple(args, "O", &selfParam)) return NULL; PyObject* cppPtr = PyObject_GetAttrString(selfParam, "_cpp_ptr"); long cppPtrVal = PyInt_AsLong(cppPtr); Actor* pActor = reinterpret_cast(cppPtrVal); // Delegate to the C++ object pActor->ShowName(); Py_INCREF(Py_None); return Py_None; } I've omitted some error checking, but this is the way I'm going for now. Are there any glaring errors I've made (apart from perhaps assuming sizeof(pointer) <= sizeof(long), that is)? And is there anywhere else more appropriate that I should be asking this question, given the lack of responses to this and my other embedding topic so far? -- Ben Sizer From george.sakkis at gmail.com Mon Jan 29 13:36:38 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 29 Jan 2007 10:36:38 -0800 Subject: [Boost.Graph] graph.vertices property creates new objects Message-ID: <1170095798.778605.30310@q2g2000cwa.googlegroups.com> I've just started toying with the python bindings of BGL and I'm puzzled from the following: >>> from boost.graph import Graph >>> g = Graph() >>> v = g.add_vertex() >>> g.vertices.next() == v True >>> g.vertices.next() is v False It seems that the vertices iterator creates new vertex objects every time instead of iterating over the existing ones. This essentially prevents, among other things, storing vertices as keys in a dictionary since the hashes of the stored and the new vertex differ although they compare equal. Is this really what's happening, and if so, why ? George From cginboston at hotmail.com Thu Jan 4 10:26:08 2007 From: cginboston at hotmail.com (Chaz Ginger) Date: Thu, 04 Jan 2007 15:26:08 GMT Subject: Packaging up a Python/Twisted Matrix application... Message-ID: I have a rather large Python/Twisted Matrix application that will be run on Windows, Linux and perhaps Macs. I was wondering if there are any tools that can be used to create an installer that will bring in Python, Twisted Matrix, my application libraries and anything else I need? I have tried using ezsetup with no luck (it seems not everything can be installed with it). I was hoping to find something as nice (and complete) as Perl's CPAN but can't seem to find anything. Does anyone have any recommendations? Peace, Chaz. From researchbase at gmail.com Fri Jan 19 08:30:33 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Fri, 19 Jan 2007 19:00:33 +0530 Subject: how to mimik a main() function to start a program with entry point? Message-ID: hello all. I have one simple query and may be that's to stupid to answer but I am not finding the answer any ways. I have a set of modules in my package and out if which one is my actual starting point to my entire program. say for example I have an entire database application ready and I want a main (as in java or c) to initiate the program and may be bring up a login screen and then pass the control on to the main window. if I am giving raw source code that is easy because I will tell user to run the command ./xyz.py which has that function. but if I freze it into an executable with py2exe for example , how do I solve this problem? thanks. Krishnakant. From rossabri at hotmail.com Tue Jan 9 18:12:45 2007 From: rossabri at hotmail.com (rossabri at hotmail.com) Date: 9 Jan 2007 15:12:45 -0800 Subject: The trouble with sockets.... (fixing inheritance, etc.) Message-ID: <1168384365.791194.179700@77g2000hsv.googlegroups.com> This topic has been addressed in limited detail in other threads: [1] "sockets don't play nice with new style classes :(" May 14 2005. http://groups.google.com/group/comp.lang.python/browse_thread/thread/76d27388b0d286fa/c9849013e37c995b [2] "Subclassing socket" Dec 20 2005 - Jan 14 2006. http://groups.google.com/group/comp.lang.python/browse_thread/thread/391728cd442339c8/c0581b9ee5e7ceaf Briefly, the socket module ("socket.py") provides a wrapper for python extension code ("_socket.so","Modules/socketmodule.*" in the source) that is built on top of the system socket library ("socket.h",etc). This wrapper attempts to provide a SocketType we can instantiate and treat as a typical Python object. It does this by forwarding some of its function calls (send, recv, etc.) to an object that it references as self._sock. This "delegation" pattern has been used in the past to allow built-in types to be treated like normal types. The problem is that, in this instance, delegation fails to maintain the inheritance behavior that we expect from normal types. (See [1] and [2] for examples.) My question is: What can be done about this? The issue is somewhat complicated. It seems to me that the crux of the problem is that sockets can spawn other sockets via the .dup and .accept methods. These calls pass right down to the system level and return references to objects of the built-in type (ie, _socket.socket) to interpreted code. All the interpreted code can do it try to "cast" (in the sense of Java) the object to a non-built-in type. If "newsock" is a reference to a _socket.socket object, the socket module does this by calling (notionally) "SocketType(_sock=newsock)". The new object of type SocketType delegates to the object of type _socket.socket via self._sock. Please see the source code for a clearer picture. Now I'll have a little chat with myself. Q1) Can't we just have _socket.socket.dup and _socket.socket.accept return something of type(self) rather than type _socket.socket? A1) I don't think you can "tell" the compiled code about what "type" of PyObject to return. Maybe the Python gods will bless us with a complete answer here. Q2) Ok, so it looks like we are stuck with delegation at some level or another then, huh? A2) Well, yeah, but in some sense Python is all about delegating data and operations to compiled code. It's just a matter of how and where. We want to maintain a clear object model in the interpreted code and push the dirty work down to compiled code. The problem is that in the case of the socket module, the "how and where" are not obvious because of the way the accept and dup system calls work. Q3) Are you saying that the way that sockets work is fundamentally different than the way other built-in objects work? A3) Yeah, I guess I am. There aren't really any other built-ins that can reach down to compiled code and spawn themselves like that. When stuff like that happens in Python, it is usually handled with a copy, deepcopy, or some kind of factory function. Sockets just do some things that are hard to shoe-horn into a standard Python idiom. The easiest solution to this problem is probably to fix the delegation mechanism so that it transparently supports inheritance. The .accept and .dup methods would pass a _socket.socket object into type(self).__init__. Some __getattribute__ magic would likely be involved. It's not immediately obvious to me how to do this, but my intuition is that it can be done fairly painlessly. The ideal solution is to redesign both the _socket and socket modules so that we don't have to resort to delegation. However, due to the argument that I have given, this will likely result in an interface change. Interface changes are painful, yes, but at least things become more pythonic. What does the peanut gallery think? How should we go about fixing this problem? From arkanes at gmail.com Thu Jan 25 09:09:06 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 25 Jan 2007 08:09:06 -0600 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> <4866bea60701240736v837d246w187ecb1ccb90eefd@mail.gmail.com> Message-ID: <4866bea60701250609u61e72d30q21dd11c8c8fd9bcd@mail.gmail.com> On 1/25/07, Boris Borcic wrote: > Chris Mellon wrote: > > On 1/24/07, Boris Borcic wrote: > >> Chris Mellon wrote: > >>> Using either win32 or wxPython you will be able to produce bitmaps > >>> directly, without needing to create a visible window. > >>> > >>> > >>> Some quick & dirty wxPython code > >>> > >>> def getTextBitmap(text, font, fgcolor, bgcolor): > >>> dc = wx.MemoryDC() > >>> dc.SetFont(font) > >>> width, height= dc.GetTextExtent(text) > >>> bmp = wx.EmptyBitmap(width, height) > >>> dc.SelectObject(bmp) > >>> dc.SetBackground(wx.Brush(bgcolor)) > >>> dc.Clear() > >>> dc.SetTextBackground(bgcolor) > >>> dc.SetTextForeground(fgcolor) > >>> dc.DrawText(text, 0, 0) > >>> dc.SelectObject(wx.NullBitmap) > >>> return bmp > >>> > >>> > >>> Raw win32 code will look similar but will be much more verbose. > >> Thx again for this base. > >> > >> Quickly testing this, it appears that the result is rendered half a pixel off in > >> the x-direction. Does this make sense ? Is it possible to position text with > >> subpixel accuracy ? > >> > > > > The GDI text api, which is what wx is wrapping here, only provides > > pixel accuracy. You are probably seeing a kerning effect from your > > chosen font and perhaps the effects of ClearType. > > I am not. Turning antialiasing off (as a desktop setting) changes the rendering > but wx._gdi_ still insists that horizontal coordinates are between pixels (to > the contrary of vertical coordinates). This means thin black vertical lines are > rendered by two pixel columns, the left one red, the right one cyan. > Non-aliased, 90-degree rotated text is still smeared likewise left-to-right on > the screen what becomes top-to-bottom relative to the text. Setting the scales > at 0.5 and drawing the text one pixel off (to express a half-pixel shift) > doesn't work. A long almost vertical thin black line that's one pixel off > top-to-bottom results in two parallel vertical uniformly colored red and cyan > pixel columns, broken in the middle. > > In short, wx._gdi_ fights quite hard to enforce what I am trying to avoid :( I > might admire its consistency if it extended to treating both axes similarly... > I have not recently had a need to examine drawn text output this closely, but I am familiar with the C++ code that implements the drawing and it's a direct wrapping of win32 GDI calls. If it's not matching your source text, then the source may be drawn using a different method or using one of the alternate engines, like GDI+. From gagsl-py at yahoo.com.ar Wed Jan 24 12:37:18 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 14:37:18 -0300 Subject: sys.path issue in cygwin In-Reply-To: <001501c73f8d$63edb590$14fd0179@WANGSHUHAO> References: <001501c73f8d$63edb590$14fd0179@WANGSHUHAO> Message-ID: <7.0.1.0.0.20070124143053.034d86b8@yahoo.com.ar> At Wednesday 24/1/2007 04:58, Wang Shuhao wrote: >To keep the question simple, I've set PATH= in cygwin.bat to avoid >python initialze sys.path from Windows' PATH environment. The simple answer is that sys.path has nothing to do with the PATH environment variable. sys.path is initialized from the location of the Python executable; PYTHONPATH can be used to prepend additional directories. You might set PYTHONHOME too, but for a standard installation its not needed - mainly for embedded interpreters where the running application is not python itself. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jonc at icicled.net Sat Jan 6 18:37:20 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sat, 6 Jan 2007 17:37:20 -0600 Subject: Traceback of hanged process In-Reply-To: <1168123532.3498.51.camel@chopin> References: <1168123532.3498.51.camel@chopin> Message-ID: <200701061737.20605.jonc@icicled.net> On Saturday 06 January 2007 16:45, Hynek Hanke wrote: > Hello, > > please, how do I create a pythonic traceback from a python process that > hangs and is not running in an interpreter that I executed manually > or it is but doesn't react on CTRL-C etc? I'm trying to debug a server > implemented in Python, so I need some analog of 'gdb attach' for C. > > Unfortunatelly, googling and reading documentation revealed nothing, so > please excuse if this question is dumb. > > Thank you, > Hynek Hanke Hynek, It is possible to redirect stderr to a file so that in case of a crash or fault the errors will be logged to a file. I think the following code would do it. import sys log_file = open('errors.log', 'w') sys.stderr = open('errors.log', 'w') log_file.close() Hope it helps. - Jonathan From wuwei23 at gmail.com Mon Jan 22 20:36:04 2007 From: wuwei23 at gmail.com (alex23) Date: 22 Jan 2007 17:36:04 -0800 Subject: class explorer for automating IE In-Reply-To: <1169454620.313191.263020@m58g2000cwm.googlegroups.com> References: <1169448532.869501.190530@v45g2000cwv.googlegroups.com> <1169449585.832667.325370@11g2000cwr.googlegroups.com> <1169454620.313191.263020@m58g2000cwm.googlegroups.com> Message-ID: <1169516164.311920.156730@51g2000cwl.googlegroups.com> John wrote: > The problem is that this does not run javascript code it seems. > I got started with pamie, which seems to work till now. Have you seen IEC? http://www.mayukhbose.com/python/IEC/index.php I've used IEC and found it very straightforward. I had no call to test its ability to handle javascript, but according to the site: "Ability to process Javascript and VBscript." Hope this helps. -alex23 From gagsl-py at yahoo.com.ar Thu Jan 18 12:34:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 14:34:52 -0300 Subject: How to find out if another process is using a file References: Message-ID: "Tom Wright" escribi? en el mensaje news:eoo6vd$33u$1 at gemini.csx.cam.ac.uk... > I'm writing a program which reads a series of data files as they are > dumped > into a directory by another process. At the moment, it gets sporadic bugs > when it tries to read files which are only partially written. > > I'm looking for a function which will tell me if a file is opened in > write-mode by another process - if it is, my program will ignore it for > now > and come back to it later. This needs to work on linux and windows. Mac > OS would be a bonus too. An os-independent solution would be good, but I > could write os-specific options and have it pick the appropriate one. Use os.open with the O_EXCL flag; will fail if the other process has the file still open (and will fail if another process is reading the file, too, not just if someone is writing). -- Gabriel Genellina From tleeuwenburg at gmail.com Wed Jan 10 21:26:28 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 10 Jan 2007 18:26:28 -0800 Subject: what is the idiom for copy lots of params into self? In-Reply-To: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> Message-ID: <1168482387.968342.169880@i39g2000hsf.googlegroups.com> def __init__(self, **kw): self.argdict = kw Emin wrote: > Dear Experts, > > When writing large classes, I sometimes find myself needing to copy a > lot of parameters from the argument of __init__ into self. Instead of > having twenty lines that all basically say something like self.x = x, I > often use __dict__ via something like: > > class example: > def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n): > for name in > ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']: > self.__dict__[name] = locals()[name] > > This saves a lot of code and makes it easier to see what is going on, > but it seems like there should be a better idiom for this task. Any > suggestions? > > Thanks, > -Emin From jstroud at mbi.ucla.edu Fri Jan 26 22:52:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 26 Jan 2007 19:52:20 -0800 Subject: Resizing widgets in text windows In-Reply-To: <1169847315.631951.295830@a75g2000cwd.googlegroups.com> References: <1169847315.631951.295830@a75g2000cwd.googlegroups.com> Message-ID: deacon.sweeney at gmail.com wrote: > Hi, I've been searching for a .resize()-like function to overload much > like can be done for the delete window protocol as follows: > > toplevel.protocol("WM_DELETE_WINDOW", callback) > > I realize that the pack manager usually handles all of the resize > stuff, but I've found an arrangement that the pack manager fails for. > That is, if one embeds a canvas into a window created inside a text > widget, Your meaning here is unclear. How is it possible to have "a window created inside a text widget"? > then resize the text widget (via its container), the canvas and > its container windows do not resize. So I need to resize the window > that the canvas is embedded in. Try the Toplevel.wm_geometry() function. > The most obvious way of doing this > would be as above, but there does not seem to be an equivalent to the > "WM_DELETE_WINDOW" protocol for resizing. Do you want to detect when a window is resized or do you want to resize a window programatically. If the former, bind the Toplevel to ''. E.g. from Tkinter import * def config(t): def _r(e, t=t): geom = e.widget.wm_geometry() geom = geom.split('+')[0] t.wm_geometry(geom) print 'resized %s to %s' % (t, geom) return _r tk = Tk() tk.title('resize me') t2 = Toplevel(tk) t2.title('I get resized') tk.bind('', config(t2)) Is that cool or what? James > Any help would be greatly appreciated. > > Deacon Sweeney > From uval at rz.uni-karlsruhe.de Sun Jan 21 22:45:34 2007 From: uval at rz.uni-karlsruhe.de (=?UTF-8?B?U2Now7xsZSBEYW5pZWw=?=) Date: Mon, 22 Jan 2007 04:45:34 +0100 Subject: pylab, matplotlib ... roots function question In-Reply-To: References: Message-ID: Hi, [...] > No, that's actually wrong. What version of numpy are you using? With a recent > SVN checkout of numpy, I get the correct answer: > > In [3]: roots([1,0,0]) > Out[3]: array([ 0., 0.]) In [17]: import sys, numpy In [18]: sys.version Out[18]: '2.5 (r25:51908, Sep 23 2006, 01:23:14) \n[GCC 4.1.1]' In [19]: numpy.version.version Out[19]: '1.0rc1' moon:/pool/PROG/python # uname -a Linux moon 2.6.16.13-4-smp #1 SMP Wed May 3 04:53:23 UTC 2006 x86_64 x86_64 x86_64 GNU/Linux I think I will get and compile newer version of source BTW, I also look for good (more or less complete and/or interessting) tutoruals on signal processing with python something like low/high-pass filtering/ploting of wave files etc I would appreciate pointers very much. I am learning this at the moment, when it all starts to make sense to me, I will write such a tutorial on my own later Regards, Daniel From steven.bethard at gmail.com Thu Jan 4 18:33:38 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 04 Jan 2007 16:33:38 -0700 Subject: When argparse will be in the python standard installation In-Reply-To: <87d55u7bp7.fsf@pobox.com> References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> <459C008D.5040404@v.loewis.de> <459CBAC8.9060007@v.loewis.de> <64mdnTE_-5Ff3gDYnZ2dnUVZ_q6vnZ2d@comcast.com> <87d55u7bp7.fsf@pobox.com> Message-ID: Steven Bethard schrieb: > If someone has an idea how to include argparse features into optparse, > I'm certainly all for it. But I tried and failed to do this myself, so > I don't know how to go about it. Martin v. L?wis wrote: > It's not necessary that the implementation is retained, only that the > interface is preserved. [snip] > If you need to make incompatible changes, it would be best if you > could produce a list of such changes Steven Bethard writes: > FWIW, here's a short list of issues that could be easily addressed: > > * alias ArgumentParser to OptionParser [snip] John J. Lee wrote: > all of these issues could ... be addressed by instead providing both > OptionParser and an OptsAndArgsParser class (or whatever you'd call > the latter). You're essentially proposing to move argparse.ArgumentParser to the optparse module. (The ArgumentParser class handles both optional and positional command-line args -- it *is* your OptsAndArgsProcessor). That's certainly an easy option for me =) but does it address Martin and Fredrik's concerns that there are already too many argument parsing libraries in the stdlib? > Presumably most of the actual implementation code > would be shared. Well, the "harder issues" I listed in the previous post were basically the reasons that sharing the implementation code would be difficult. I don't know how to do it without breaking OptionParser in backwards incompatible ways. (The documented ways of extending optparse make this particularly difficult since they make public a number of internal optparse details.) STeVe From ardsrk at gmail.com Tue Jan 30 02:05:37 2007 From: ardsrk at gmail.com (ArdPy) Date: 29 Jan 2007 23:05:37 -0800 Subject: Help me understand this Message-ID: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> Hi, Pls tell me whats going on in the code snippet below: >>> n = 10 >>> statstr = "N = ",n >>> type(statstr) #case1 >>> print statstr ('N = ', 10) >>> print "N = ",n #case 2 N = 10 In the first case the result is printed as a tuple and in the second it appears as an ordinary string. From codecraig at gmail.com Wed Jan 31 08:20:42 2007 From: codecraig at gmail.com (abcd) Date: 31 Jan 2007 05:20:42 -0800 Subject: marshal.loads ValueError In-Reply-To: References: <1170247461.799295.227550@a75g2000cwd.googlegroups.com> Message-ID: <1170249642.170475.323110@a75g2000cwd.googlegroups.com> On Jan 31, 8:02 am, Benjamin Niemann wrote: > marshal is used to (de)serialize python objects from/to strings. > marshal.loads() tries to deserialize an encoded string back into a python > object - which does not make sense here. > What you probably want is: > > exec data in my_module.__dict__ thanks that took care of it. From emin.shopper at gmail.com Thu Jan 11 17:40:53 2007 From: emin.shopper at gmail.com (Emin) Date: 11 Jan 2007 14:40:53 -0800 Subject: How much slower is dict indexing vs. list indexing? Message-ID: <1168555253.601611.258600@k58g2000hse.googlegroups.com> Dear Experts, How much slower is dict indexing vs. list indexing (or indexing into a numpy array)? I realize that looking up a value in a dict should be constant time, but does anyone have a sense of what the overhead will be in doing a dict lookup vs. indexing into a list? Some ad hoc tests I've done indicate that the overhead is less than 15% (i.e., dict lookups seem to take no more than 15% longer than indexing into a list and there doesn't seem to be much difference in indexing into a list vs. a numpy array). The reason I ask is because I'm wondering how hard I should work to compute and store an index into a list to avoid repeated hash table lookups. From my tests, it looks like the answer is basically "don't bother". Does anyone have information, thoughts, or comments on this? Thanks, -Emin From roux.claude at xrce.xerox.com Mon Jan 22 06:03:59 2007 From: roux.claude at xrce.xerox.com (Roux Claude) Date: Mon, 22 Jan 2007 12:03:59 +0100 Subject: Linking in a Linux environment Message-ID: Bonjour, We have implemented Python as an "embedded script language" in our NLP application, XIP which a grammar rule engine written in C++ and available as a library. We have also developped a GUI in Java, which is linked to this XIP library, to simplify the development of NL grammars. JAVA GUI IDE Library: XIP (C++) Python Modules can be called from grammar rules Now we have the following problem, when we try to execute a Python script from a grammar in a Linux environment, the system fails when this Python module tries to import basic modules like "math" for instance. The system returns a "PyExc_OverflowException undefined variable" error. This problem only occurs on Linux platforms, we do not have any problems on Mac OS and on Windows. We have linked our NLP library with Python 2.4.4, and we have tried many different manipulations to solve this problem. We have tried to link with the static and the dynamic Python library, without any success. Searching the WEB, we have discovered similar problems, but none of the proposed solutions actually worked. For instance, some people wrote that the problem was to due to the compiling options of our Python library; we checked the Makefile for these options, which we found to be already there. We also tried to modify the dlopen options, as suggested, through the specific dlopen operations in the Python corresponding library. NOP... However, the use the Python 2.5 dynamic library seems to solve most of these problems, which would be ok, if people would accept to switch to a version that is quite new. Halas, this is not that simple... I still do not have any clear answer about what is going on. If someone could help me on this one, I'll be really grateful... :-) Merci d'avance, Claude From 12cc104 at gmail.com Mon Jan 8 03:49:08 2007 From: 12cc104 at gmail.com (proctor) Date: 8 Jan 2007 00:49:08 -0800 Subject: regex question References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> <1168243020.304940.212700@42g2000cwt.googlegroups.com> <1168244922.620428.273260@38g2000cwa.googlegroups.com> <1168245604.911965.248360@11g2000cwr.googlegroups.com> Message-ID: <1168246148.673027.13720@38g2000cwa.googlegroups.com> Mark Peters wrote: > > is there any way i would be successful then, in using raw string inside > > my makeRE() function? > > Why do you think you even need a raw string? > > Just build and return the string 'a|b|c' (NOTE: DON'T add the quotes to > the string) yes, i suppose you are right. i can't think of a reason i would NEED a raw string in this situation. all very helpful! thanks very much. sincerely, proctor. From smusnmrNOSPAM at yahoo.com Thu Jan 4 04:10:02 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Thu, 4 Jan 2007 10:10:02 +0100 Subject: pow() works but sqrt() not!? References: <1167899693.759071.51450@31g2000cwt.googlegroups.com> Message-ID: Thank you very much, T?nis!: *** 1 *** >you forgot to import math module >>> import math Nope, I did not! But I used sqrt(9), and not math.sqrt(9). The latter works excellent, thank you! From now on, I will use "import math" and "math.fuction()" for EVERY mathematical function, even for pow() etc. just to be on the safe side! *** 2 *** >if you want math functions to your current namespace use: >>> from math import * What is a "namespace" and what is the difference between ">>>import math" and ">>>from math import *" ? Siggi "tonisk" schrieb im Newsbeitrag news:1167899693.759071.51450 at 31g2000cwt.googlegroups.com... you forgot to import math module >>> import math >>> math.sqrt(9) 3.0 if you want math functions to your current namespace use: >>> from math import * -- T?nis On Jan 4, 10:13 am, "siggi" wrote: > Hi all, > > this is a newbie question on : > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] > on > win32 > PC with WinXP > > Inhttp://www.python.org/doc/2.3.5/lib/module-math.html > I read: > > "sqrt( x) Return the square root of x." > > Now the test for module math with function pow(): > --------------------------------------------------->>> pow(9,9)387420489 > > Fine, but sqrt() fails: > ------------------->>> sqrt(9)I get this error message > > 'Traceback (most recent call last): > File "", line 1, in > sqrt(9) > NameError: name 'sqrt' is not defined' > > Same for sin() and cos(). ">>> Import math" does not help. Will I have to > define the sqrt() function first? If so, how? > > Please help! > > Thank you, > > Siggi From paul at boddie.org.uk Wed Jan 24 12:46:47 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Jan 2007 09:46:47 -0800 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <1169660807.369400.120220@h3g2000cwc.googlegroups.com> On 24 Jan, 02:50, John Nagle wrote: > The major complaint I have about Python is that the packages > which connect it to other software components all seem to have > serious problems. As long as you don't need to talk to anything > outside the Python world, you're fine. I think you're overstating your case here, since there is a lot of Python code out there (much of it under the radar of many readers of this newsgroup/list) whose purpose is precisely that of integration with other software components. Having read what you've written elsewhere with regard to SSL integration with Python, though, the causes of the symptoms you're seeing are mostly correctly identified in your own analysis. > In the Perl, Java, PHP, and C/C++ worlds, the equivalent functions just work. We may have differing experiences here. Java stuff, in my experience, usually needs lots of precisely versioned .jar files and then frequently doesn't "just work". C and C++ aren't complete environments, but there are admittedly some libraries/frameworks/environments based on those languages which might provide solutions which often work satisfactorily. I don't really want to think of the cocktail of solutions available for Perl to solve any given problem, but people often report that the quality varies somewhat between them. > That's because, in those worlds, either the > development team for the language or the development team > for the subsystem takes responsibility for making them work. > Only Python doesn't do that. And this is where I'd almost reach agreement with you. It's not enough for the language to keep growing new features if the libraries are broken or appear archaic, and this task seems to be outside the "core developers" area of interest. Of course, people like you and I could help update the libraries, although finding the time for making more than just suggestions can be quite difficult, but the core developers merely signalling that the libraries are a priority area for development would probably lead to fewer people pushing their own favourite syntax brush-ups or esoteric constructs, hopefully leading some people (with enough time) to update, document and improve what's already there. Paul From nmadnani at gmail.com Thu Jan 18 22:53:58 2007 From: nmadnani at gmail.com (Nitin) Date: 18 Jan 2007 19:53:58 -0800 Subject: subclassing pyrex extension types in python Message-ID: <1169178838.303291.291740@s34g2000cwa.googlegroups.com> Hi All I am trying to subclass an extension type in Python and add attributes to the new class but I keep getting errors. I read the "Extension Types" document on the Pyrex website but I couldn't get an answer from it. Here's the Spam extension type from Pyrex website: cdef class Spam: cdef int amount def __new__(self): self.amount = 0 def get_amount(self): return self.amount Once compiled, here's how I am using this: import spam class mySpam(spam.Spam): def __init__(self, name1=None, name2=None): spam.Spam.__init__(self) self.name1 = name1 self.name2 = name2 When I run this Python code, I get an error "TypeError: 'name2' is an invalid keyword argument for this function" Is there something I need to know about Pyrex extension types and keyword arguments ? I tried to google for this but couldn't come up with anything. Thanks ! Nitin From rvernica at gmail.com Fri Jan 26 20:09:05 2007 From: rvernica at gmail.com (Rares Vernica) Date: Fri, 26 Jan 2007 17:09:05 -0800 Subject: Unicode error handler In-Reply-To: References: Message-ID: It does the job. Thanks a lot, Ray Peter Otten wrote: > Rares Vernica wrote: > >> Is there an encode/decode error handler that can replace all the >> not-ascii letters from iso-8859-1 with their closest ascii letter? > > A mapping, not an error handler, but it might do the job: > > http://effbot.org/zone/unicode-convert.htm > > Peter From TimDGCB at gmail.com Wed Jan 31 15:21:36 2007 From: TimDGCB at gmail.com (TimDGCB at gmail.com) Date: 31 Jan 2007 12:21:36 -0800 Subject: DCOP memory leak? In-Reply-To: <1170269516.158040.38450@s48g2000cws.googlegroups.com> References: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> <1170265582.892012.69290@v45g2000cwv.googlegroups.com> <1170269516.158040.38450@s48g2000cws.googlegroups.com> Message-ID: <1170274896.450862.268330@s48g2000cws.googlegroups.com> On 31 jan, 19:51, "David Boddie" wrote: > On Jan 31, 6:46 pm, "TimD... at gmail.com" wrote: > > > The code I posted is not my actual program and was only to demonstrate > > my problem. The complete program I'm writing uses QT and so the loop > > is replaced by a Timer event. > > I tried out the suggestion. I had already tried the del dcop > > instruction, so I knew that wasn't it. I also placed the DCOP variable > > outside my loop but that didn't help either. > > You might get a precise answer to your question if you send a message > to the PyQt/PyKDE mailing list: > > http://mats.imk.fraunhofer.de/mailman/listinfo/pykde > > The original authors and contributors of various Python DCOP modules > read that list, so there's a chance they can either solve your problem > or offer some advice on how to work around it. > > > What I did notice that my program only grew in memory use when the > > 'ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() ' code was > > executed (or any other function using the AmarokDcopRes variable like > > 'ok, volume = AmarokDcopRes.player.getVolume()' ) > > Do you find the same problem with other DCOP interfaces? > > David Hi David, I did tried out some other DCOP calls from other programs and I have the same problem. I followed your suggestion to subcribe and poste to the pyKDE mailing list. I hope they can help me there. Thanks, Tim From tmaroff at yahoo.com Tue Jan 9 16:25:15 2007 From: tmaroff at yahoo.com (Tristan) Date: 9 Jan 2007 13:25:15 -0800 Subject: A question about IDLE and environment variables Message-ID: <1168377915.536426.159580@77g2000hsv.googlegroups.com> Hello community: I post this because I could not find satisfactory answers in the posts generated by this nice group. I work on winXP. I have many little python applications in different folders, each application can share or not other objects located in the same or other folders. The way I work to use these applications is: 1) For almost everyone, I execute a corresponding ".bat file" into which I define and/or include values for some "temporal" environment variables that let me find all the objects that the selected application uses. Sometimes I include in the .bat file the execution of the application, but generally I leave in a prompt status, ready to invoke python or some dos commands. 2) When I close the command prompt window, there are no traces of my enviroment variables in my windows system (that is right). Only the default windows environment variables remain. I tried to do the same with the IDLE (and I imagine tha same occurs with Python command line), but I have the next problem: I can not find in IDLE (or another app?) the way to previously define and/or include automatically values for my "temporal" environment variables as I do in the .bat files. The use of Control Panel -> System -> Advanced is tedious to use as, my enviroment variables values are "temporal". Any advice, please??? From vodel at hrz.tu-chemnitz.de Fri Jan 5 07:44:00 2007 From: vodel at hrz.tu-chemnitz.de (Matthias Vodel) Date: Fri, 5 Jan 2007 13:44:00 +0100 Subject: Change coords of a canvas.line item References: Message-ID: Very nice :) Thank you, Matthias From dummy at dummy.nl Fri Jan 19 12:19:04 2007 From: dummy at dummy.nl (Cecil Westerhof) Date: Fri, 19 Jan 2007 18:19:04 +0100 Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> Message-ID: <45b0fd87$0$333$e4fe514c@news.xs4all.nl> BJ?rn Lindqvist wrote: > On 1/18/07, Cecil Westerhof wrote: >> I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse >> I can not time the time used to import time, but os and sys do not take >> more as a millisecond. My script itself takes 3 or 4 milliseconds. But >> importing cgi takes 95 milliseconds. (This is on my test system a PII 300 >> MHz. Is there a way to make this more fast? The import off cgi makes the >> script at least 20 times as slow. Something like mod-python is not a >> possibility. I could use it on my test machine, but not at the osting >> provider. > > Maybe python-launcher-daemon can help you? > http://blogs.gnome.org/view/johan/2007/01/18/0 But if you can not use > mod_python then you probably can not use any long running processes > either. By my current provider I can not use this. But I am going to look for another. What are the pro's en cons off the different systems? FastCGI, PyApache, mod_pythion and maybe others I am not aware off. From ken at seehart.com Sun Jan 7 15:42:07 2007 From: ken at seehart.com (Ken Seehart) Date: Sun, 07 Jan 2007 12:42:07 -0800 Subject: audio video streaming communications Message-ID: <45A15B1F.7000200@seehart.com> Hello, I am looking for a good audio/video conferencing library. Ideally it should work with wxPython (or have some means of making it work there). So far my main difficulty in my attempt at searching for such a package is that there is so much stuff out there on downloading music and videos. I am not interested in download torrents, etc. I'm just looking video conferencing, and live video broadcasts, etc. Any recommendations? Thanks, - Ken From steve at holdenweb.com Fri Jan 12 03:43:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Jan 2007 08:43:55 +0000 Subject: *#$% &@! Jerub on #python, you desynced me for no good reason In-Reply-To: <1168584166.949097.233620@11g2000cwr.googlegroups.com> References: <1168584166.949097.233620@11g2000cwr.googlegroups.com> Message-ID: gavino wrote: > I can't fucking believe this guy. The chat was jsut getting > interesting about epoll on linux and twisted moduel for it and he > desyncs me. > FUCK JERUB > complete fucking asshole!! > Well I hope you feel better now. Please don't imagine that this outburst will have any practical effects *other* than that, however. This is the Internet. What happened, happened. Move on. If there are any lessons to be learned, one of them might be that not everybody appreciates your chosen mode of expression. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From pierre at saiph.com Sat Jan 13 04:39:01 2007 From: pierre at saiph.com (Imbaud Pierre) Date: Sat, 13 Jan 2007 10:39:01 +0100 Subject: module file Message-ID: <45a8a8b6$0$22646$426a34cc@news.free.fr> I am willing to retrieve the file an imported module came from module.__file__, or inspect.getfile(module) only gives me the relative file name. How do I determine the path? Its obviously possible from python: ipython displays the information (interactively: *module?*). NB: I saw the discussion about the python path, "find a .py path", this is different! Its not the script, but the module I want to retrieve! From http Sat Jan 27 11:49:12 2007 From: http (Paul Rubin) Date: 27 Jan 2007 08:49:12 -0800 Subject: Dictionary inserts and threads References: <45bb7eac$0$321$e4fe514c@news.xs4all.nl> Message-ID: <7x64as1kl3.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > I assume that this is not a problem, but since assuming something > gives a lot of room for screw-ups I rather ask beforehand if I should > except all kinds of troubles when multiple threads update 'at the same > time' a dictionary or that I should lock the dictionary, for each > update? Use a lock, or serialize the updates through a queue. From bob at passcal.nmt.edu Fri Jan 26 13:07:27 2007 From: bob at passcal.nmt.edu (Bob Greschke) Date: Fri, 26 Jan 2007 11:07:27 -0700 Subject: Fixed length lists from .split()? Message-ID: <2007012611072716807-bob@passcalnmtedu> I'm reading a file that has lines like bcsn; 1000000; 1223 bcsn; 1000001; 1456 bcsn; 1000003 bcsn; 1000010; 4567 The problem is the line with only the one semi-colon. Is there a fancy way to get Parts=Line.split(";") to make Parts always have three items in it, or do I just have to check the length of Parts and loop to add the required missing items (this one would just take Parts+=[""], but there are other types of lines in the file that have about 10 "fields" that also have this problem)? Thanks! Bob From gagsl-py at yahoo.com.ar Tue Jan 16 19:43:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 21:43:13 -0300 Subject: urrlib2 multithreading error In-Reply-To: <1168958510.834175.184730@a75g2000cwd.googlegroups.com> References: <1168958510.834175.184730@a75g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20070116214146.0428aac8@yahoo.com.ar> At Tuesday 16/1/2007 11:41, viscanti at gmail.com wrote: >When I use it on a single thread everything goes ok, when I create >multiple threads the execution halts and the program terminates, just >before the last line (when I execute the request.read(.) ). Obviously I >tried to catch the exception but it doesn't work, the interpreter exits >without any exception or message. Ouch... Can you reduce your program to the minimum code that fails, and post it? -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From python at hope.cz Wed Jan 24 11:20:25 2007 From: python at hope.cz (Johny) Date: 24 Jan 2007 08:20:25 -0800 Subject: Regex for URL extracting Message-ID: <1169655624.981833.29730@j27g2000cwj.googlegroups.com> Does anyone know about a good regular expression for URL extracting? J. From nmm1 at cus.cam.ac.uk Thu Jan 18 04:58:07 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 18 Jan 2007 09:58:07 GMT Subject: Class data members in C References: Message-ID: In article , "Hendrik van Rooyen" writes: |> |> > Oh, one of the first two - I am not bonkers! Changing a class after |> > instance creation is guaranteed to cause confusion, if nothing else. |> > |> *grin* - its also just about impossible to do, if you try to imagine |> what you would have to do to all instances when you effectively |> change the __init__ method. And some people expect it to happen |> automagically... Oh, it's quite easy to do, with several different semantics. I have even used a couple of them. All are seriously counter-intuitive :-) I have never used one that successfully reran initialisation, though I have seen people attempt it! And tried it myself .... |> Sorry I can't be of more help. All of the docs I have read essentially |> talk about changing instances. From a practical point of view I would |> say: "Just redefine it". But that is not very helpful. Specially if you are |> mucking about in C, as your title suggests... Thanks. As someone else posted, the answer is PyDict_SetItemString immediately after PyType_Ready. Regards, Nick Maclaren. From simon at arrowtheory.com Mon Jan 15 13:35:40 2007 From: simon at arrowtheory.com (Simon Burton) Date: 15 Jan 2007 10:35:40 -0800 Subject: compile your python programs with rpython Message-ID: <1168886140.256596.101250@v45g2000cwv.googlegroups.com> The pypy'ers have written a brief description on using rpython to create standalone executables: http://codespeak.net/pypy/dist/pypy/doc/standalone-howto.html This is definately worth playing around with, it's very nice writing (r)python code that gets executed as if it were c code. Simon. From py at th.on Thu Jan 25 11:07:25 2007 From: py at th.on (py) Date: Thu, 25 Jan 2007 16:07:25 GMT Subject: smtplib starttls gmail example - comments? Message-ID: <1B4uh.3171$R65.534@trnddc01> Excellent imput! I learned - no need for trailing . and i was doing it wrong anyway. - all those extra trys were redundant. - the trailing comma functionality in print. - the extra ehlo is an rfc req. Thanks all. -dave From allison.william at gmail.com Sun Jan 7 09:11:53 2007 From: allison.william at gmail.com (William Allison) Date: Sun, 07 Jan 2007 09:11:53 -0500 Subject: I want to learn In-Reply-To: References: <1168174097.252001.71130@s80g2000cwa.googlegroups.com> Message-ID: Thomas Ploch wrote: > joeyslistings at yahoo.com schrieb: >> Hi, >> >> I have been "programming" in the .net environment and ide for a few >> years and I am looking to make the switch over to python. I have >> absolutely no python experience whatsoever. I am looking for a python >> guru who has instant messenger or gtalk or whatever who can meet me >> online in the mornings, give me some direction for the day and then >> answer some questions here and there online throughout the day. > > > So you are looking for a person (no, a guru), that stays by your side > the whole day, gives you answers and helps you learning python. > > This is a ridiculous request. > > If you want to learn python, you should start with visiting > http://www.diveintopython.org/ and read it. If you have previous > programming experience, this is the place to start. > >> Sorry to interrupt the group but since all python gurus appear to be >> happily at work on the next level apps at google nobody responded to >> my craigslist ads. > > You can always ask your questions here on the list, there are enough > people that are willing to help. > > Thomas Also look into the tutor mailing list. Not EXACTLY what you're asking for but, very helpful, friendly people subscribe to it. http://mail.python.org/mailman/listinfo/tutor From steve at REMOVE.THIS.cybersource.com.au Thu Jan 25 09:51:23 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 26 Jan 2007 01:51:23 +1100 Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> <1169725374.504546.153890@v33g2000cwv.googlegroups.com> <7xirevuw5s.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 25 Jan 2007 04:29:35 -0800, Paul Rubin wrote: > "gangesmaster" writes: >> what i see as a bug is this code not working as expected: >> >> >>> def make_foos(names): >> ... funcs = [] >> ... for n in names: >> ... def foo(): >> ... print "my name is", n >> ... funcs.append(foo) >> ... return funcs > > But it does work as expected, if your expectations are based on what > closures actually do. > >> i have to create yet another closure, make_foo, so that the name >> is correctly bound to the object, rather than the frame's slot: > > The Python idiom is: > > def make_foos(names): > funcs = [] > for n in names: > def foo(n=n): > print "my name is", n > funcs.append(foo) > return funcs > > The n=n in the "def foo" creates the internal binding that you need. Hmmm... I thought that the introduction of nested scopes removed the need for that idiom. Its an ugly idiom, the less I see it the happier I am. And I worry that it will bite you on the backside if your "n=n" is a mutable value. My solution is, don't try to have one function do too much. Making a list of foos should be a separate operation from making a single foo: >>> def makefoo(name): ... def foo(): ... return "my name is " + name ... return foo ... >>> makefoo("fred")() 'my name is fred' >>> def makefoos(names): ... foos = [] ... for name in names: ... foos.append(makefoo(name)) ... return foos ... >>> L = makefoos(["fred", "wilma"]) >>> L[0]() 'my name is fred' >>> L[1]() 'my name is wilma' That makes it easier to do unit testing too: you can test your makefoo function independently of your makefoos function, if that's important. If you absolutely have to have everything in one function: >>> def makefoos(names): ... def makefoo(name): ... def foo(): ... return "my name is " + name ... return foo ... L = [] ... for name in names: ... L.append(makefoo(name)) ... return L ... >>> L = makefoos(["betty", "barney"]) >>> L[0]() 'my name is betty' >>> L[1]() 'my name is barney' Best of all, now I don't have to argue as to which binding behaviour is more correct for closures!!! *wink* -- Steven. From fredrik at pythonware.com Wed Jan 3 10:30:41 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 Jan 2007 16:30:41 +0100 Subject: Can I beat perl at grep-like processing speed? References: Message-ID: Nick Craig-Wood wrote: >> #!/usr/bin/env python >> import re >> r = re.compile(r'destroy', re.IGNORECASE) >> >> for s in file('bigfile'): >> if r.search(s): print s.rstrip("\r\n") footnote: if you're searching for literal strings with Python 2.5, using "in" is a lot faster than using re.search. From smusnmrNOSPAM at yahoo.com Tue Jan 9 11:09:57 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Tue, 9 Jan 2007 17:09:57 +0100 Subject: how to clean sys.path Message-ID: Hi all, when I do >>>sys.path in IDLE (winXP), i get a horrendously long list of paths, paths I may have used during a lot of trials and errors. How can I clean up sys.path? I mean, trim it of unnecessary paths? So far, I know only the command >>>sys.path.append(r'c:....etc...'), but how to delete or insert at the beginning of the list, I know not. Thanks, siggi From gagsl-py at yahoo.com.ar Tue Jan 30 18:19:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 20:19:32 -0300 Subject: Convert raw data to XML References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> <1170184059.739808.244660@s48g2000cws.googlegroups.com> <1170189278.490020.52670@h3g2000cwc.googlegroups.com> Message-ID: elrondrules at gmail.com wrote: > is there any other way to do this without using BeautifulStoneSoup.. > using existing minidom or ext.. > i dont want to install anything new It appears that you already know the answer... Look at the minidom documentation, toprettyxml method. -- Gabriel Genellina From rkmr.em at gmail.com Fri Jan 12 15:17:04 2007 From: rkmr.em at gmail.com (mark) Date: Fri, 12 Jan 2007 12:17:04 -0800 Subject: dynamic argument name for functions Message-ID: I want to pass a value to an argument of a function. The argument name is dynamic and is stored in a variable. How do I call the function using with arg_name and value as the parameters. thanks mark For ex: def function(arg1='None', arg2='None', arg3='None'): print arg1 print arg2 print arg3 arg_name = 'arg1' arg_value = 'i am passing a value to argument 1' function(???????) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr._bogus_.com Thu Jan 18 01:34:03 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 18 Jan 2007 00:34:03 -0600 Subject: [Python-Dev] Deletion order when leaving a scope? References: <45AEC612.1030001@hastings.org> Message-ID: <45af14dc$0$7727$4c368faf@roadrunner.com> "Calvin Spealman" wrote in message news:mailman.2860.1169086798.32031.python-list at python.org... > Absolutely an irrelevent side effect, especially when you take into > consideration the 4 and counting alternative implementations of the > language. > > None the less, I can explain why it is as it is, keeping in mind its > not like that on purpose, its just how it is. Locals are optimized > into an array for fast lookup. Every name assigned to in a function is > known as a local in that function and this internal array holds its > reference. It is simply a product of the array indexes and deletion > order being the same, 0 to N. > Oh good! Now I can write code that relies on this behavior! -- Paul From martin at v.loewis.de Fri Jan 5 22:26:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 06 Jan 2007 04:26:58 +0100 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 In-Reply-To: References: Message-ID: <459f1703$0$24039$9b622d9e@news.freenet.de> Carroll, Barry schrieb: > What I want to know is: > > * has anyone else encountered a problem like this, * how was the > problem corrected, * can the fix be retro-fitted to 2.5 and 2.4? >From your description, I suspect an error in your code. Your description indicates that you don't expect to have more than five files open simultaneously. Yet, the error message "Too many open files" occurs when you open many more files (in the order of hundreds of files). It is very unlikely that there is a bug in Python where it would fail to close a file when .close() is explicitly invoked on it (as your description suggests that you do), so if you get that error message, it can only mean that you fail to close some files. Notice that you may have other files open, as well, and that those also count towards the limit. As a debugging utility, you can use Sysinternal's process explorer. Make the program halt (not exit) when the exception occurs (e.g. by having it sleep(1) in a loop), then view all open handles in the process explorer (check the menu if it doesn't display them initially). Regards, Martin From meelab at free.fr Wed Jan 3 17:38:35 2007 From: meelab at free.fr (meelab) Date: Wed, 03 Jan 2007 23:38:35 +0100 Subject: static object Message-ID: <459c306c$0$314$426a74cc@news.free.fr> Dear All, I am looking for a way to create a "static object" or a "static class" - terms might be inappropriate - having for instance: class StaticClass: . . and then staticObject1 = StaticClass() staticObject2 = StaticClass() so that staticObject1 and staticObject2 refers exactly to the same instance of object. In other words, that is a class which would result in only 1 instance always the same no matter how many times I will "instantiate" it. My purpose is to permit this class to initialize a massive amount of data that I need to access from different points of my program without duplicating this data in memory and without loosing time in reloading it each time I need it. I noticed the staticmethods, and the __new__ method which could , but I always get stuck in actually creating static DATA without having global data. Does anyone have a start of a clue to this ? Many thanks in advance Emmanuel. From rridge at csclub.uwaterloo.ca Sat Jan 20 00:12:08 2007 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 19 Jan 2007 21:12:08 -0800 Subject: Determining when a file is an Open Office Document References: <1169171820.851021.49200@l53g2000cwa.googlegroups.com> <1169239691.159739.304050@l53g2000cwa.googlegroups.com> Message-ID: <1169269928.081540.210010@51g2000cwl.googlegroups.com> Ross Ridge wrote: > So identifying PDF files is pretty easy. Steven D'Aprano wrote: > Sure. MIS-identifying PDF files is pretty easy. Identifying them is not. > Consider this example: Your contrived example doesn't show how a PDF file would be misidentified, it only shows how a file deliberately made to look like PDF file would be "misidentified". Since that was the intent of crafting such a file, I don't see the problem. > Is there a security vulnerability buried in the detection of file types by > magic bytes? I don't know, but I wouldn't be surprised if there were. There's only a security vulnerability if you choose to trust a file based on it's assumed file type. Since PDF files generally aren't trusted, it's not likely to be an issue for whatever application tubby has in mind. >Any file system that doesn't have file type metadata is reduced to >guessing the type of the file, and guesses can be wrong. File type metadata can also be wrong. You can give any file a .PDF extension and Windows will believe it's a PDF file. On Mac OS if file has a signature "CARO"/"PDF ", it will believe it's a PDF file regardless of it's contents. Metadata doesn't make programs any less vulnerable to deliberate attempts to fool them. Ross Ridge From Barry.Carroll at psc.com Tue Jan 16 14:39:39 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 16 Jan 2007 11:39:39 -0800 Subject: OT: teleporters (Was: General Question About Python) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A78@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: Hendrik van Rooyen [mailto:mail at microcorp.co.za] > Sent: Saturday, January 13, 2007 9:47 PM > To: Torabisu; python-list at python.org > Subject: Re: General Question About Python > > "Torabisu" wrote: > > > > > > Hendrik van Rooyen wrote: > > > > What do you want done? - I am only a thousand miles away... > > > > > > > If I can just get my Python teleporter sorted out, distance will be no > > problem... A little buggy at the moment though... Poor John, I told > > him not to test it but oh well. > > OMG! - I have been feeding that unexpected heap of minced meat > to the cat... > > - Hendrik > Gentlemen: Y'all really need to be more careful. Much research has been done on matter teleportation, and there is ample documentation of the dangers involved. The logs of the USS Enterprise alone are rife with the horrible consequences of "transporters gone wild".(1) In addition, the historical records of the NSEA Protector contain a particularly gruesome account of a "digital conveyor" malfunction which caused the subject to turn inside out and then explode.(2) These experiments MUST be conducted under the most rigorous controls to prevent similar catastrophes. (Unless, you're using Perl programmers as test subjects, in which case it's okay. ;^) Humorously yours, Barry --------------- (1) "Star Trek: the Motion Picture": Roddenberry, Foster and Wise, 1979 (2) "Galaxy Quest": Howard, Gordon and Parisot, 1999 From bg_ie at yahoo.com Tue Jan 9 05:09:51 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 9 Jan 2007 02:09:51 -0800 Subject: A simple array in Python Message-ID: <1168337391.770307.54750@11g2000cwr.googlegroups.com> Hi, I have the following enum - class State: Fire = 0 Water = 1 Earth = 2 And I want a variable which holds a value for each of these states, something like - myState1[State.Fire] = 10 myState1[State.Earth] = 4 myState2[State.Fire] = 20 myState2[State.Earth] = 24 How do I do this? Thanks Barry. From rubbishemail at web.de Wed Jan 10 05:17:58 2007 From: rubbishemail at web.de (rubbishemail at web.de) Date: 10 Jan 2007 02:17:58 -0800 Subject: convert binary data to int Message-ID: <1168424278.193439.216770@k58g2000hse.googlegroups.com> Hello, I need to convert a 3 byte binary string like "\x41\x00\x00" to 3 int values ( (65,0,0) in this case). The string might contain characters not escaped with a \x, like "A\x00\x00" Any ideas? Daniel From ebgssth at gmail.com Thu Jan 18 11:43:51 2007 From: ebgssth at gmail.com (js ) Date: Fri, 19 Jan 2007 01:43:51 +0900 Subject: How to find out if another process is using a file In-Reply-To: References: Message-ID: How about using lock? Let writing process locks the files before writing, and unlock after the job's done. I think it'd work file in most environment. On 1/19/07, Tom Wright wrote: > I'm writing a program which reads a series of data files as they are dumped > into a directory by another process. At the moment, it gets sporadic bugs > when it tries to read files which are only partially written. > > I'm looking for a function which will tell me if a file is opened in > write-mode by another process - if it is, my program will ignore it for now > and come back to it later. This needs to work on linux and windows. Mac > OS would be a bonus too. An os-independent solution would be good, but I > could write os-specific options and have it pick the appropriate one. > > Is there any way of doing this? I've drawn a blank with google so far. > > A nasty hack would be to use the file modification time, and wait until > that's a few seconds in the past, but is there a nice solution? > > > -- > I'm at CAMbridge, not SPAMbridge > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py at yahoo.com.ar Sun Jan 7 14:24:24 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 11:24:24 -0800 Subject: urlib.quote gives KeyError in Python 2.4.4 but workin 2.3.5 In-Reply-To: <1168195697.483795.71160@38g2000cwa.googlegroups.com> References: <1168195697.483795.71160@38g2000cwa.googlegroups.com> Message-ID: <1168197864.496582.105530@42g2000cwt.googlegroups.com> On 7 ene, 15:48, "nyenyec" wrote: > urllib.quote chokes on unicode in 2.4.4. >>> urllib.quote(u"\xe9") > KeyError: u'\xe9' > > but it seems to work in Python 2.3.5 > > Is this a known bug? See some recent posts about "urllib.unquote and unicode" -- Gabriel Genellina From franck.perez at gmail.com Mon Jan 8 06:49:15 2007 From: franck.perez at gmail.com (Franck PEREZ) Date: Mon, 8 Jan 2007 12:49:15 +0100 Subject: Proper way of handling "plug-in" methods Message-ID: All, My application deals with strings formatting. I have built-in methods but I also expect the user to add its methods in its own .py files (some sort of plugin methods, all user methods should be exposed in my application). Here is the structure I have thought of : formatting.py _formattingDict = {} #a dict composed of all available methods, both builtin and user def expose(...) : #adds a method to the dict builtinformatting.py import myapp.formatting.expose @expose def builtinMethod(inputStr) : return someOutput /home/user/.myapp/customformatting.py import myapp.formatting.expose @expose def customMethod(inputStr) : return someOutput model.py #References all the methods, both builtin and custom execfile("builtinformatting.py") execfile("/home/user/.myapp/customformatting.py") Expected result after the execfile : formatting._formattingDict contains the 2 methods builtinMethod and customMethod Is this a proper way of structuring my application ? Do you see anything better ? Moreover, I dislike execfile("builtinformatting.py") since classic import would do the job. However I first wanted a united method for both builtin and custom scripts since it is the same logic for me. Thanks very much in advance for your advice. Franck From fredrik at pythonware.com Wed Jan 3 13:18:42 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Jan 2007 19:18:42 +0100 Subject: Unsubscribing from the list In-Reply-To: <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> Message-ID: Dotan Cohen wrote: > Actually, I'm a compete idiot Robert provided *detailed* instructions, which you ignored. I quoted the same instructions in my reply, which you also ignored. the sentence after the one where you stopped reading also tells you what to do. one might suspect that you don't really want to unsubscribe from this list... From stargaming at gmail.com Tue Jan 16 11:22:58 2007 From: stargaming at gmail.com (Stargaming) Date: Tue, 16 Jan 2007 17:22:58 +0100 Subject: arguments of a function/metaclass In-Reply-To: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> References: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> Message-ID: rubbishemail at web.de schrieb: > Hello, > > > I have a member function with many (20) named arguments > > def __init__(self,a=1,b=2): > self.a=a > self.b=b > > I would like to get rid of the many redundant lines like self.a=a and > set the members automatically. > The list of default arguments could be given like > > def __init__(**kwargs): > arglist={"a":1,"b":2] > > if this makes things easier > > Of course there has to be a check that raises an error in case of an > unknown argument not mentioned in this list. > > > I am sure there is an elegant way how to do this, could you give me any > hints??? > > > Many thanks > > > > Daniel > If it's a long list of arguments, it will stay a long list (i. e. representation) of arguments, whatever you do. You could minimize your layout, though, to e. g. use a decorator that takes a list of arguments automatically saved to self. But that's just a "layout" (or design) issue and it will stay clumsy, whatever you do (perhaps splitting up the dict to many lines will make it more readable, but that's it). To bring up a more liberate attempt, why don't you just save *all* args received (self.__dict__.update(kwargs)). If the user provides more arguments -- nevermind! You would have to do something about default values though and here you got to use the list again, first updating self.__dict__ with the list and afterwards with kwargs. Stargaming From gandalf at designaproduct.biz Thu Jan 25 11:42:12 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 25 Jan 2007 17:42:12 +0100 Subject: Two dimensional lists In-Reply-To: References: Message-ID: <45B8DDE4.9000903@designaproduct.biz> > # shouldn't I be able to fill the lists simply by pointing to a location? > > matrix[a_idx, p_idx] = 0x219 # and so on? > Lists are not matrices. For example: L = [ [1,2,3], ['a','b','c'], 10 ] print L[1][2] # Prints 'c', you will like this syntax but... print L[2][5] # TypeError: 10 is not subscriptable You can create a function that creates a "list of lists" filled with zeros, and then use this data structure as a matrix. BUT! If you need to use matrices filled with numbers, try numarray: http://www.stsci.edu/resources/software_hardware/numarray Numarray is much more efficient for this task. Best, Laszlo From Barry.Carroll at psc.com Fri Jan 5 19:22:11 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 5 Jan 2007 16:22:11 -0800 Subject: What is proper way to require a method to be overridden? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A63@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: python-list-bounces+barry.carroll=psc.com at python.org [mailto:python- > list-bounces+barry.carroll=psc.com at python.org] On Behalf Of Fuzzyman > Sent: Friday, January 05, 2007 4:05 PM > To: python-list at python.org > Subject: Re: What is proper way to require a method to be overridden? > > > Carl Banks wrote: > > jeremito wrote: > > > I am writing a class that is intended to be subclassed. What is the > > > proper way to indicate that a sub class must override a method? > > > > You can't (easily). > > > > Well... > > How about not defining it on the base class, but check in the > constructor that the attribute exists and that it is of type > FunctionType ? > > Fuzzyman > http://www.voidspace.org.uk/python/articles.shtml > > -- > http://mail.python.org/mailman/listinfo/python-list Greetings: Thomas Christopher's book "Python Programming Patterns" has an example of this that I like. On page 72 he shows code for a class, AbstractSet, which he later subclasses in ListSet and DictSet. Each of the methods intended for subclassing simply to raise a NotImplementedError, e.g.: def insert(self,x): raise NotImplementedError, "set.insert" In this way the superclass's interface is well defined (the methods and their parameters are all listed, but if invoked before they are overwritten, they abort with a useful error message. Pretty slick, IMHO. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From Ingo.Wolf at gmx.de Wed Jan 17 11:56:51 2007 From: Ingo.Wolf at gmx.de (iwl) Date: 17 Jan 2007 08:56:51 -0800 Subject: predefined empty base class ?? Message-ID: <1169053011.399278.290980@a75g2000cwd.googlegroups.com> Hi, is there an predefined empty base class which I can instanziate to have an container i can copy attributes in? From skip at pobox.com Tue Jan 9 09:39:19 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Jan 2007 08:39:19 -0600 Subject: Using with CSV library in Python 2.2!!! In-Reply-To: <1168352108.295247.280690@51g2000cwl.googlegroups.com> References: <1168348224.843657.27330@42g2000cwt.googlegroups.com> <1168352108.295247.280690@51g2000cwl.googlegroups.com> Message-ID: <17827.43287.949653.793293@montanaro.dyndns.org> mohan> Thanks man. What kind of source code changes should I do to mohan> "_csv.c" file , have you any idea on that too?? I've no particular ideas. There are sometimes small C API changes between feature releases though. If you read through the What's New document for version 2.3 (google for it) you;ll probably have a pretty good idea of any such changes. mohan> Otherwise upgrading to Python 2.4 would be the easiest choice. Oh, you didn't mention that. By all means, upgrade to 2.4 or 2.5 instead of trying to backport the csv module to an outdated Python version. Skip From gagsl-py at yahoo.com.ar Mon Jan 29 23:53:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 01:53:47 -0300 Subject: sending a class as an argument References: <1170044663.163303.131930@v45g2000cwv.googlegroups.com> Message-ID: En Mon, 29 Jan 2007 01:24:23 -0300, manstey escribi?: > > Our class has its attributes set as classes, as in > > MyClass.Phone.Value='34562346' > MyClass.Phone.Private=True > > Inside the MyClass definition we have a function like this: > > def MyFunc(self,clsProperty): > if clsProperty.Private: > print 'Private property' > else: > print ClsProperty.Value This method does not use `self` at all, and that's rather suspicious for an instance method. And you set properties on the class itself? So you never create instances of that class? > In our code, we then call >>>> MyClass.MyFunc(MyClass.Phone) > > We want to be able in our code instead simply to call: >>>> MyClass.MyFunc(Phone) or MyClass.MyFunc('Phone') > > But we can't get it to work. If we rewrite the function as follows: > > def MyFunc(self,attr): > if self.attr.Private: > print 'Private' > else: > print self.attr.Value > > we get an error. Surely an AttributeError, because you dont have any attribute named "attr". Notice that on this version you are using `self`, but on the above version you didnt use it. There are easy ways in Python to access an attribute by name, but I think that this would just add more noise to your code. Please tell us about your design, or rethink it. Do actually exist instances of MyClass, or not? I can imagine "Phone" being an attribute of a certain instance of Person, by example, but not a class attribute. > Is there a better way to do this? Thanks Surely, but we need to know your goal, what do you really want to do, not how do you think you should do that. -- Gabriel Genellina From grahamd at dscpl.com.au Fri Jan 26 16:32:36 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 26 Jan 2007 13:32:36 -0800 Subject: xml.dom.minidom.parseString segmentation fault on mod_python In-Reply-To: <1169809222.955833.176380@j27g2000cwj.googlegroups.com> References: <1169804514.862290.274940@q2g2000cwa.googlegroups.com> <1169809222.955833.176380@j27g2000cwj.googlegroups.com> Message-ID: <1169847155.992129.68440@l53g2000cwa.googlegroups.com> On Jan 26, 10:00 pm, "Ziga Seilnacht" wrote: > On Jan 26, 10:41 am, qert... at gmail.com wrote: > > > Python 2.4.4 > >mod_python3.2.10 + Apache 2.0 > > > def index( req, **params ): > > from xml.dom.minidom import parseString > > doc = parseString( "whatever" ) > > > => blank screen, _no_any_exception_; Apache error_log: > > [Fri Jan 26 10:18:48 2007] [notice] child pid 17596 exit signal > > Segmentation fault (11) > > > Outsidemod_pythoncode works well. Any ideas? I would be grateful.http://www.python.org/sf/1558223http://www.python.org/sf/1295808http://www.python.org/sf/1075984 > > Try to compile all your dependencies against the same version of > Expat or upgrade to python 2.5. For further information read: http://www.dscpl.com.au/wiki/ModPython/Articles/ExpatCausingApacheCrash Graham From david at boddie.org.uk Thu Jan 11 08:00:22 2007 From: david at boddie.org.uk (David Boddie) Date: 11 Jan 2007 05:00:22 -0800 Subject: creating simple Python scripting interfaces via C++ References: <1168272267.679069.325890@38g2000cwa.googlegroups.com> <1168515833.590286.123330@o58g2000hsb.googlegroups.com> Message-ID: <1168520420.006334.191000@i56g2000hsf.googlegroups.com> Ben Sizer wrote: > And is there anywhere else more appropriate that I should be asking > this question, given the lack of responses to this and my other embedding > topic so far? You could try asking on the C++ SIG mailing list at python.org: http://mail.python.org/mailman/listinfo/c++-sig David From eight02645999 at yahoo.com Sat Jan 20 00:09:53 2007 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 19 Jan 2007 21:09:53 -0800 Subject: regexp qns References: <1169268024.164643.71320@l53g2000cwa.googlegroups.com> Message-ID: <1169269793.713444.152110@a75g2000cwd.googlegroups.com> James Stroud wrote: > eight02645999 at yahoo.com wrote: > > hi > > suppose i have a string like > > > > test1?test2t-test3*test4*test5$test6#test7*test8 > > > > how can i construct the regexp to get test3*test4*test5 and > > test7*test8, ie, i want to match * and the words before and after? > > thanks > > > > > py> import re > py> s = 'test1?test2t-test3*test4*test5$test6#test7*test8' > py> r = re.compile(r'(test\d(?:\*test\d)+)') > py> r.findall(s) > ['test3*test4*test5', 'test7*test8'] > > James thanks ! I check the regexp doc it says: """ (?:...) A non-grouping version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern. """ but i could not understand this : r'(test\d(?:\*test\d)+)'. which parenthesis is it referring to? Sorry, could you explain the solution ? thanks From gisdudester at gmail.com Wed Jan 31 00:18:52 2007 From: gisdudester at gmail.com (GISDude) Date: 30 Jan 2007 21:18:52 -0800 Subject: PY Zip Message-ID: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> Hi all. I am trying to find a module that has a Zip utility that I can use in Python. I would like to be able to call the module and ZIP up a directory. I thought there was such a module, but I have not been able to find it. I need this to be able to be used in Python Win. Is there a ZIP utilty already stored with a basic PYTHON download? Thanks all. From kbk at shore.net Thu Jan 4 22:40:49 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 4 Jan 2007 22:40:49 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200701050340.l053en59025586@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 418 open ( +5) / 3522 closed ( +1) / 3940 total ( +6) Bugs : 959 open (+13) / 6405 closed ( +5) / 7364 total (+18) RFE : 250 open ( +2) / 245 closed ( -1) / 495 total ( +1) New / Reopened Patches ______________________ update to PEP 344 - exception attributes (2007-01-02) CLOSED http://python.org/sf/1626538 opened by Jim Jewett backticks will not be used at all (2007-01-03) http://python.org/sf/1627052 opened by Jim Jewett Fix for #1601399 (urllib2 does not close sockets properly) (2007-01-03) http://python.org/sf/1627441 opened by John J Lee Win32: Fix build when you have TortoiseSVN but no .svn/* (2007-01-04) http://python.org/sf/1628061 opened by Larry Hastings Win32: Add bytesobject.c to pythoncore.vcproj (2007-01-04) http://python.org/sf/1628062 opened by Larry Hastings socket.readline() interface doesn't handle EINTR properly (2007-01-04) http://python.org/sf/1628205 opened by Maxim Sobolev Patches Closed ______________ update to PEP 344 - exception attributes (2007-01-02) http://python.org/sf/1626538 closed by ping New / Reopened Bugs ___________________ sqlite3 documentation omits: close(), commit(), autocommit (2006-12-30) http://python.org/sf/1625205 opened by kitbyaydemir re module documentation on search/match is unclear (2006-12-31) http://python.org/sf/1625381 opened by Richard Boulton 'imp' documentation does not mention that lock is re-entrant (2006-12-31) http://python.org/sf/1625509 opened by Dustin J. Mitchell add ability to specify name to os.fdopen (2007-01-01) http://python.org/sf/1625576 opened by Mark Diekhans 'Installing Python Modules' does not work for Windows (2007-01-02) http://python.org/sf/1626300 opened by Christopher Lambacher Would you mind renaming object.h to pyobject.h? (2007-01-02) http://python.org/sf/1626545 opened by Anton Tropashko posixmodule.c leaks crypto context on Windows (2007-01-03) http://python.org/sf/1626801 opened by Yitz Gale website issue reporter down (2007-01-03) http://python.org/sf/1627036 opened by Jim Jewett mention side-lists from python-dev description (2007-01-03) http://python.org/sf/1627039 opened by Jim Jewett xml.dom.minidom parse bug (2007-01-03) CLOSED http://python.org/sf/1627096 opened by Pierre Imbaud xml.dom.minidom parse bug (2007-01-03) CLOSED http://python.org/sf/1627244 opened by Pierre Imbaud an extra comma in condition command crashes pdb (2007-01-03) http://python.org/sf/1627316 opened by Ilya Sandler Typo in module index for Carbon.CarbonEvt (2007-01-03) CLOSED http://python.org/sf/1627373 opened by Brett Cannon Status bar on OSX garbled (2007-01-03) http://python.org/sf/1627543 opened by sigzero RotatingFileHandler cannot recover from failed doRollover() (2007-01-03) http://python.org/sf/1627575 opened by Forest Wilkinson documentation error for "startswith" string method (2007-01-04) CLOSED http://python.org/sf/1627690 opened by Keith Briggs plat-mac videoreader.py auido format info (2007-01-04) http://python.org/sf/1627952 opened by Ryan Owen documentation error for "startswith" string method (2007-01-04) http://python.org/sf/1627956 opened by Keith Briggs Bugs Closed ___________ test_logging hangs on cygwin (2006-04-06) http://python.org/sf/1465643 closed by sf-robot xml.dom.minidom parse bug (2007-01-03) http://python.org/sf/1627096 closed by loewis xml.dom.minidom parse bug (2007-01-03) http://python.org/sf/1627244 closed by nnorwitz Typo in module index for Carbon.CarbonEvt (2007-01-03) http://python.org/sf/1627373 closed by nnorwitz documentation error for "startswith" string method (2007-01-04) http://python.org/sf/1627690 closed by loewis Logging problem on Windows XP (2006-09-27) http://python.org/sf/1566280 closed by loewis New / Reopened RFE __________________ smarter temporary file object (2001-04-12) http://python.org/sf/415692 reopened by gvanrossum optparse "store" action should not gobble up next option (2007-01-03) http://python.org/sf/1627266 opened by Raghuram Devarakonda From http Thu Jan 25 19:58:21 2007 From: http (Paul Rubin) Date: 25 Jan 2007 16:58:21 -0800 Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> <1169754601.992058.205640@q2g2000cwa.googlegroups.com> <7xsldy7u6f.fsf@ruckus.brouhaha.com> <1169758010.223732.272340@k78g2000cwa.googlegroups.com> <7xveiu4xis.fsf@ruckus.brouhaha.com> Message-ID: <7xodomeh8y.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > What makes you think Paddy indicated he wouldn't try to solve the problem? > Here's what he wrote: > > What I'm proposing is that if, for example, a process stops running > three times in a year at roughly three to four months intervals , and it > should have stayed up; then restart the server sooner, at aa time of > your choosing, whilst taking other measures to investicate the error. Well, ok, that's better than just rebooting every so often and leaving it at that, like the firmware systems he cited. > I see nothing wrong with trying to minimize the chances of a problem I think a measure to minimize the chance of some problem is only valid if there's some plausible theory that it WILL decrease the chance of the problem (e.g. if there's reason to think that the problem is caused by a very slow resource leak, but that hasn't been suggested). That's the part that I'm missing from this story. One thing I'd certainly want to do is set up a test server under a much heavier load than the real server sees, and check whether the problem occurs faster. From gagsl-py at yahoo.com.ar Tue Jan 23 00:39:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Jan 2007 02:39:51 -0300 Subject: Removing outdated files In-Reply-To: <45b59949@griseus.its.uu.se> References: <45b59949@griseus.its.uu.se> Message-ID: <7.0.1.0.0.20070123023901.0423a4b8@yahoo.com.ar> At Tuesday 23/1/2007 02:17, Jan Danielsson wrote: > I've been looking at the datetime.date class, but I can't see any >easy way to parse the week number from it. I could calculate this >information by brute force -- but I get a feeling that there are >functions in Python to extract week numbers from a date. .isocalendar() -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From S.Mientki-nospam at mailbox.kun.nl Sat Jan 6 17:27:30 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 06 Jan 2007 23:27:30 +0100 Subject: still struggling, howto use a list-element as a name ? In-Reply-To: References: <45a01981$0$296$426a74cc@news.free.fr> Message-ID: <441e$45a02246$d443bb3a$24795@news.speedlinq.nl> Jussi Salmela wrote: > Bruno Desthuilliers kirjoitti: >> Stef Mientki a ?crit : >>> In the example below, "pin" is an object with a number of properties. >>> Now I want >>> 1- an easy way to create objects that contains a number of these "pin" >>> 2- an multiple way to access these "pin", i.e. >>> device.pin[some_index] >>> device.some_logical_name >>> ad 1: >>> a dictionary (as "pinlist" in the example) seems a very >>> convenient way (from a viewpoint of the device creator). >>> As you can see in the "__init__" section this dictionary can easily >>> be transported to the pin-objects. >>> >>> ad 2: >>> THAT's the problem: how do automate these lines "self.GND = self.pin[0]" >>> >>> I'm also in for other solutions. >> >> I'm afraid I don't understand your design (nor the domain FWIW). > ditto >> >> >> But the whole thing still looks awfully convulted and kludgy to me, >> and I suspect serious design flaws... Why don't you try and explain >> your real problem, instead of asking how to implement what you *think* >> is the solution ? > ditto thank you all guys. I'm just doing some exercises in Python, and therefor I'm trying to rewrite some programs I've written in other languages into Python. The first program I tried to convert was a MatLab program, which could almost be written identical in Python. Even with my little experience in Python, I can tell you that it could have been written in Python in a much better way, but I deliberately did not, to show other people who are familiar with MatLab. The second example I'm now exercising with, is a simulator of (electrical) circuits, which I build in Delphi http://oase.uci.kun.nl/~mientki/data_www/pic/jalss/jalss.html > > Cheers, > Jussi From streamservenl at gmail.com Wed Jan 31 05:04:53 2007 From: streamservenl at gmail.com (jvdb) Date: 31 Jan 2007 02:04:53 -0800 Subject: Help needed on config files Message-ID: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> Hi there, I am quite new on python programming and need some help on solving my problem.. I have to make a (python) program which deletes files from directories. I don't think deleting, etc. is the problem. The problem is that the directories where i have to delete them are 'dynamic'/ subject to change. So what i thought is to make a config file containing an identifier (useful for myself) and there the directory. something like: [PROJECTx] [PROJECTy] I have already seen that there are sorts of modules where you can read a config file, but only when you know the key.. Can someone help me out on this? The configfile can be altered in time (as there are more projects coming where i have to delete files on a scheduled basis). This is a good learning project for me, but i really don't see how to solve this. From no-spam at no-spam-no-spam.invalid Fri Jan 12 06:48:44 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Fri, 12 Jan 2007 12:48:44 +0100 Subject: Parallel Python In-Reply-To: <1168597288.571937.176430@s34g2000cwa.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: Paul Boddie wrote: > parallelpyt... at gmail.com wrote: >> The main difference between MPI python solutions and ppsmp is that with >> MPI you have to organize both computations >> {MPI_Comm_rank(MPI_COMM_WORLD, &id); if id==1 then ... else ....} and >> data distribution (MPI_Send / MPI_Recv) by yourself. While with ppsmp >> you just submit a function with arguments to the execution server and >> retrieve the results later. > > Couldn't you just provide similar conveniences on top of MPI? Searching > for "Python MPI" yields a lot of existing work (as does "Python PVM"), > so perhaps someone has already done so. Also, what about various grid > toolkits? > > [...] > >> Overall ppsmp is still work in progress and there are other interesting >> features which I would like to implement. This is the main reason why I >> do not open the source of ppsmp - to have better control of its future >> development, as advised here: http://en.wikipedia.org/wiki/Freeware :-) > > Despite various probable reactions from people who will claim that > they're comfortable with binary-only products from a single vendor, I > think more people would be inclined to look at your software if you did > distribute the source code, even if they then disregarded what you've > done. My own experience with regard to releasing software is that even > with an open source licence, most people are likely to ignore your > projects than to suddenly jump on board and take control, and even if > your project somehow struck a chord and attracted a lot of interested > developers, would it really be such a bad thing? Many developers have > different experiences and insights which can only make your project > better, anyway. > > Related to your work, I've released a parallel execution solution > called parallel/pprocess [1] under the LGPL and haven't really heard > about anyone really doing anything with it, let alone forking it and > showing my original efforts in a bad light. Perhaps most of the > downloaders believe me to be barking up the wrong tree (or just > barking) with the approach I've taken, but I think the best thing is to > abandon any fears of not doing things the best possible way and just be > open to improvements and suggestions. > > Paul > > [1] http://www.python.org/pypi/parallel I'd be interested in an overview. For ease of use a major criterion for me would be a pure python solution, which also does the job of starting and controlling the other process(es) automatically right (by default) on common platforms. Which of the existing (RPC) solutions are that nice? Robert From wojciech_mula at poczta.null.onet.pl.invalid Mon Jan 29 09:10:34 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Mon, 29 Jan 2007 14:10:34 +0000 (UTC) Subject: Conversion of string to integer References: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> Message-ID: jupiter wrote: > I have a problem. I have a list which contains strings and numeric. > What I want is to compare them in loop, ignore string and create > another list of numeric values. > > I tried int() and decimal() but without success. > > eq of problem is > > #hs=string.split(hs) > hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"] tmp = [] for s in hs: try: tmp.append( float(s) ) except ValueError: # function float raises VE, if string 's' doesn't # represent a number pass # tmp contains a list of floats From webb.sprague at gmail.com Wed Jan 3 18:52:17 2007 From: webb.sprague at gmail.com (_) Date: 3 Jan 2007 15:52:17 -0800 Subject: Dumping objects into spreadsheet readable text (design question) Message-ID: <1167868337.342308.267230@s34g2000cwa.googlegroups.com> Hi Pythonistas and Pythonistos, I am doing some fairly complex statistical analyses and trying to display the output in a form readable to technicians not yet enlightened by the wonders of python (ie they still use either Excel, S-PLUS/R, or Matlab only). I need to dump the results into text such that these users can do further processing, and I am looking for ideas on good ways to do this. Note that formatting and displaying simple lists of named coeffecients or tables would easy; the problem is that these analyses (Lee-Carter mortality forecasts, for anyone who cares) require at least a single two-dimensional matrix of rates and ~12 scalar coefficients, and they generate 4 two-dimensional matrices, several three-dimensional matrices, and 20 or so scalar coefficients. Each of these pieces of data also has a canonical name with which they must be labeled in the output. All of these pieces of data go together. Finally, I would like to find some way to do this generally, so when my boss comes up with a new analysis I can re-use this text dump code. Has anybody done this? I am thinking of using cheetah, but I am still pondering design, hoping for list inspiration! pprint won't work because users will want to import into a spreadsheet, and it displays lots of "{" etc. Feel free to cc me on the reply, as I read the list as digest. TIA From gagsl-py at yahoo.com.ar Mon Jan 22 17:34:20 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Jan 2007 19:34:20 -0300 Subject: How to use time.clock() function in python In-Reply-To: <1169503516.425217.218790@q2g2000cwa.googlegroups.com> References: <1169503516.425217.218790@q2g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070122192923.04bf5888@yahoo.com.ar> At Monday 22/1/2007 19:05, yinglcs at gmail.com wrote: >I am following this python example trying to time how long does an >operation takes, like this: > >My question is why the content of the file (dataFile) is just '0.0'? >I have tried "print >>dataFile, timeTaken" or "print >>dataFile,str( >timeTaken)", but gives me 0.0. >Please tell me what am I missing? > > > t1 = time.clock() > os.system(cmd) > > outputFile = str(i) + ".png" > > t2 = time.clock() > > timeTaken = t2 - t1 > allTimeTaken += timeTaken > print >>dataFile, timeTaken time.clock() may not give you enough precision; see this recent post http://mail.python.org/pipermail/python-list/2007-January/422676.html Use the timeit module instead. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nanjundi at gmail.com Sun Jan 28 09:18:25 2007 From: nanjundi at gmail.com (Nanjundi) Date: 28 Jan 2007 06:18:25 -0800 Subject: Getting to an SSH account over a HTTP proxy In-Reply-To: References: <1169514995.916358.17030@11g2000cwr.googlegroups.com> Message-ID: <1169993905.595465.23650@m58g2000cwm.googlegroups.com> > problem. I do not want to create my own SSH client and, AFAICT, there > is no SSH client in Twisted. The library also seem to have some > problems with handling HTTP proxies in a transparent way:http://twistedmatrix.com/trac/ticket/1774 > > -- > mvh Bj?rn There is a ssh implementation in twisted. http://twistedmatrix.com/users/z3p/files/conch-talk.html Are you able to authenticate and run commands using a ssh client on port 80? I will try to post an example if possible. -N From skip at pobox.com Tue Jan 30 18:26:17 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 30 Jan 2007 17:26:17 -0600 Subject: PythonCard In-Reply-To: <1170193549.583822.156450@k78g2000cwa.googlegroups.com> References: <1170193549.583822.156450@k78g2000cwa.googlegroups.com> Message-ID: <17855.54297.627316.697850@montanaro.dyndns.org> Tequila> I'm having some trouble starting PythonCard on my PC. I've Tequila> downloaded and ran python-2.5.msi to install Python on my Tequila> machine. And PythonCard-0.8.2.win32.exe to install PythonCard. ... Tequila> import wx Tequila> ImportError: No module named wx Tequila> Does anyone know what the problem might be? Sorta looks like you need to install wxPython. In fact, the Windows instructions for PythonCard mention downloading wxPython before downloading PythonCard itself: http://pythoncard.sourceforge.net/windows_installation.html If you're confident wxPython *is* installed, check to make sure it's installed somewhere that Python will find it. Skip From jairodsl at gmail.com Sat Jan 13 18:24:08 2007 From: jairodsl at gmail.com (jairodsl) Date: 13 Jan 2007 15:24:08 -0800 Subject: Comparing a matrix (list[][]) ? Message-ID: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> Hi, How can I find the minus element greater than zero in a matrix, my matrix is matrix= [9,8,12,15], [0,11,15,18], [0,0,10,13], [0,0,0,5] I dont want to use "min" function because each element in the matrix is associated to (X,Y) position. Thanks a lot. jDSL From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 11 12:27:27 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 11 Jan 2007 18:27:27 +0100 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> <9ihph.72$fo1.64@newsfe03.lga> <1168518426.111465.290430@o58g2000hsb.googlegroups.com> Message-ID: <50nabvF1g30l4U5@mid.individual.net> Sean Davis wrote: > I solved this problem by creating a temporary file as an > intermediary, but why wait for Oracle to finish dumping data when > I can potentially be loading into postgres at the same time that > the data is coming in? So, I am actually > looking for a solution to this problem that doesn't require an > intermediate file and allows simultaneous reading and writing, > with the caveat that the data cannot all be read into memory > simultaneously, so will need to be buffered. The functions you use don't seem very suited for such a streaminglike task. Regards, Bj?rn -- BOFH excuse #282: High altitude condensation from U.S.A.F prototype aircraft has contaminated the primary subnet mask. Turn off your computer for 9 days to avoid damaging it. From diesch at spamfence.net Sun Jan 7 16:09:39 2007 From: diesch at spamfence.net (Florian Diesch) Date: Sun, 07 Jan 2007 22:09:39 +0100 Subject: Python re expr from Perl to Python References: Message-ID: <20070107210940.1596.4.NOFFLE@dieschf.news.arcor.de> "Michael M." wrote: > In Perl, it was: > > > ## Example: "Abc | def | ghi | jkl" > ## -> "Abc ghi jkl" > ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st > pipe). > $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; > > ## -- remove [ and ] in text > $na =~ s/\[//g; > $na =~ s/\]//g; > # print "DEB: \"$na\"\n"; > > > # input string > na="Abc | def | ghi | jkl [gugu]" > # output > na="Abc ghi jkl gugu" > > > How is it done in Python? >>> import re >>> na="Abc | def | ghi | jkl [gugu]" >>> m=re.match(r'(\w+ )\| (\w+ )\| (\w+ )\| (\w+ )\[(\w+)\]', na) >>> na=m.expand(r'\1\2\3\5') >>> na 'Abc def ghi gugu' Florian -- From Elan at nomailnospam.com Tue Jan 9 16:50:37 2007 From: Elan at nomailnospam.com (Elan Magavi) Date: Tue, 09 Jan 2007 21:50:37 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: wrote in message news:1168354695.334946.157400 at 51g2000cwl.googlegroups.com... > Hello all, > > I represent Octabox, an Internet Start-up developing a wide-scale > platform for Internet services. We are very interested to know your > thoughts on Internet productivity and how it might be improved, and to > that end we have set up a short survey at our website - > http://www.octabox.com/productivity_poll.php > We would very much appreciate if you would take a couple of minutes to > fill it up and influence our direction and empahsis. > > Thanks in advance, > Octabox Development Team Is that like.. OctaPussy? > From sturlamolden at yahoo.no Thu Jan 18 14:10:40 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 18 Jan 2007 11:10:40 -0800 Subject: How can I create a linked list in Python? In-Reply-To: <7xps9dl04y.fsf@ruckus.brouhaha.com> References: <45ad5104$0$393$426a74cc@news.free.fr> <1169009882.408482.43360@q2g2000cwa.googlegroups.com> <45ae8950$0$31033$426a74cc@news.free.fr> <1169074382.702857.313010@11g2000cwr.googlegroups.com> <7xps9dl04y.fsf@ruckus.brouhaha.com> Message-ID: <1169147440.211108.137940@s34g2000cwa.googlegroups.com> Paul Rubin wrote: > But that's what Lisp does too. Ok, I may have to reread Paul Graham's book on ANSI Common Lisp then. From helgaorg at gmail.com Mon Jan 29 18:12:37 2007 From: helgaorg at gmail.com (Pappy) Date: 29 Jan 2007 15:12:37 -0800 Subject: printing to a redirected stdout from a process that was called with "2>&1 > /dev/null &" Message-ID: <1170112357.792999.241280@s48g2000cws.googlegroups.com> SHORT VERSION: Python File B changes sys.stdout to a file so all 'prints' are written to the file. Python file A launches python file B with os.popen("./B 2>&^1 >dev/null &"). Python B's output disappears into never-never land. LONG VERSION: I am working on a site that can kick off large-scale simulations. It will write the output to an html file and a link will be emailed to the user. Also, the site will continue to display "Loading..." if the user wants to stick around. The simulation is legacy, and it basically writes its output to stdout (via simple print statements). In order to avoid changing all these prints, I simply change sys.stdout before calling the output functions. That works fine. The whole thing writes to an html file all spiffy-like. On the cgi end, all I want my (python) cgi script to do is check for form errors, make sure the server isn't crushed, run the simulation and redirect to a loading page (in detail, I write a constantly updating page to the location of the final output file. When the simulation is done, the constantly updating file will be magically replaced). The root problem is that the popen mechanism described above is the only way I've found to truly 'Detach' my simulation process. With anything else, Apache (in a *nix environment) sits and spins until my simulation is done. Bah. Any ideas? _jason From deets at nospam.web.de Thu Jan 11 12:24:39 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Jan 2007 18:24:39 +0100 Subject: COM compatibility References: <1168535500.394266.10860@i39g2000hsf.googlegroups.com> Message-ID: <50na6nF1grh00U1@mid.uni-berlin.de> Tmack wrote: > I'm not a programmer! > > I work for a software company. We have a SDK that customers can use to > customize the app. The requirement to use the SDK is: > > XYZ App has been designed in such a way that all the business objects > used > in the application are automatically exposed through a thin COM wrapper > created > automatically during the application build process. This means that > using the > XYZ App SDK is very efficient, and all the same underlying objects and > properties that the application's programmers use to build the XYZ App > user > interface are also available to third-party programmers via the SDK. > > Does it sound like Python would allow me use the apps SDK? It sounds as if it is possible scripting it with python using Mark Hammond's win32, yes. Diez From mail at microcorp.co.za Fri Jan 12 00:03:11 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Jan 2007 07:03:11 +0200 Subject: Is there a way to protect a piece of critical code? References: <7xzm8q6pw7.fsf@ruckus.brouhaha.com> <7xsleiysz8.fsf@ruckus.brouhaha.com> Message-ID: <003d01c73606$f589c920$03000080@hendrik> "Paul Rubin" wrote: > Paul Rubin writes: > > def get_from_queue(queue): > > try: > > return queue.get(block=False) > > except Queue.Empty: > > return QUEUE_IS_EMPTY > > Alternatively: > > def get_from_queue(queue): > try: > return (queue.get(block=False), True) > except Queue.Empty: > return (None, False) > > This is maybe a nicer interface (no special sentinel value needed). > You'd use > > value, nonempty = get_from_queue(queue) > > if nonempty is true then the item is valid. > Hey, this is even nicer - thanks! - Hendrik From gonzlobo at gmail.com Mon Jan 1 13:36:15 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Mon, 1 Jan 2007 11:36:15 -0700 Subject: Writing more efficient code Message-ID: Greetings, and happyNewYear to all. I picked up Python a few weeks ago, and have been able to parse large files and process data pretty easily, but I believe my code isn't too efficient. I'm hoping dictionaries will help out, but I'm not sure the best way to implement them. I've been using a bunch of nested if/elif/else statements to select slices (0317 & 03de) from a file, then parse the data (aa, hh, bb, d2-d9) into parameters (a = airspeed, h = heading) & flags. #sample file contents 0000007d 03 0317 aa aa aa aa aa hh hh hh bb bb 0000007e 06 03de d2 d3 d4 d5 d6 d7 d8 d9 10 11 # some pseudo code if PID == '03de': flapsCmd = int(d3, 16) if flapsCmd == 0xc0: elif flapsCmd == 0x03: if PID == '0317': airspeed == 'combine aa for airspeed & multiply by 0.1' heading == 'combine hh for heading' mach == 'combine bb for mach & multiply by 0.01' Might dictionaries help in this case... say Label0317(parameterName, slice (d3), scaleFactor(0.1))... I'd like to use them if they'll replace the dozens of nested conditionals. I have roughly 75 different parameters to decode from a file containing ~2.5 million lines of data. I know my pseudo code lacks details, but hopefully I'm getting my point across... (I suppose switch/select/case statements would help a bit, but python doesn't seem to use them... not to start a religious war or anything). Any help (or encouragement) is appreciated. From Thomas.Ploch at gmx.net Tue Jan 9 01:11:10 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Tue, 09 Jan 2007 07:11:10 +0100 Subject: private variables In-Reply-To: <74E534EE-D260-409D-8E91-0182BB897B94@cs.hmc.edu> References: <74E534EE-D260-409D-8E91-0182BB897B94@cs.hmc.edu> Message-ID: <45A331FE.90509@gmx.net> belinda thom schrieb: > Hello, > > In what version of python were private variables added? > > Thanks, > > --b > With this question you stepped into a bee hive. :-) Read the 'Why less emphasis on private data?' thread. But I can't tell you, when this so called 'private variables' were added. Thomas From klaus at seistrup.dk Sun Jan 28 08:40:30 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sun, 28 Jan 2007 13:40:30 +0000 (UTC) Subject: IP address References: <1169990510.352536.4760@a34g2000cwb.googlegroups.com> Message-ID: Adam wrote: > This will get your IP address: > > #######Code######## > print socket.gethostbyaddr(socket.gethostname()) > ('compname', [], ['192.168.1.2']) > ########End Code######## It will return an IP address, but not necessarily the one you want: #v+ klaus at home:~ $ python -c 'import socket; print socket.gethostbyaddr(socket.gethostname())' ('zdani.szn.dk', [], ['2001:1448:89::1']) klaus at home:~ $ #v- Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From ljz at asfast.com Thu Jan 11 01:43:44 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Thu, 11 Jan 2007 01:43:44 -0500 Subject: Joining threads but allowing signals to main thread? Message-ID: <87irfeawrj.fsf@asfast.com> I have a python-2.5 program running under linux in which I spawn a number of threads. The main thread does nothing while these subsidiary threads are running, and after they all complete, the main thread will then exit. I know that I can manage this through the use of Thread.join(), but when I do it as follows, the main thread doesn't respond to signals: import sys, time, signal, threading signaled = False class Signaled(Exception): pass def sighandler(signum, frame): global signaled print 'aborted!' signaled = True def sigtest(): global signaled if signaled: raise Signaled def myfunc(arg): while True: try: sigtest() # do something except Signaled: return threads = [] for a in sys.argv[1:]: t = threading.Thread(myfunc, args=(a,)) threads.append(t) # do some initialization for s in (signal.SIGHUP, \ signal.SIGINT, \ signal.SIGQUIT, \ signal.SIGTERM): signal.signal(s, sighandler) for t in threads: t.start() for t in threads: t.join() sys.exit(0) However, if I get rid of the t.join() loop and replace the last three executable lines of the program with these, the main thread responds to signals just fine: ... while threading.activeCount() > 1: time.sleep(0.001) sys.exit(0) Is there any way to allow my program to respond to signals without having to busy-wait in the main thread? Thanks in advance. -- Lloyd Zusman ljz at asfast.com God bless you. From alexandre_irrthum at yahoo.com Tue Jan 30 09:30:12 2007 From: alexandre_irrthum at yahoo.com (alexandre_irrthum at yahoo.com) Date: 30 Jan 2007 06:30:12 -0800 Subject: Compiling extension with Visual C++ Toolkit Compiler - MSVCR80.dll In-Reply-To: <1170107212.889990.45450@a75g2000cwd.googlegroups.com> References: <1170103633.189538.216620@v45g2000cwv.googlegroups.com> <1170107212.889990.45450@a75g2000cwd.googlegroups.com> Message-ID: <1170167412.537465.116710@a75g2000cwd.googlegroups.com> Thanks for your answers Martin and Peter, I figured out why python.exe was asking for MSVCR80.dll. The first time I compiled the library, MS Visual C++ Express 2005 was used during the build (despite my PATH pointing to MS Visual C++ Toolkit 2003). When I removed Express 2005, I forgot to remove the build directory of my library. I've also had to remove and reinstall the C++ Toolkit, the platform SDK and the .NET Framework SDK and modify msvccompiler.py and my environment variables according to: http://www.vrplumber.com/programming/mstoolkit/index.html but finally it did work. And Peter, your solution worked perfectly. A great alternative to installing all the MS libraries. Cheers, alex From bill.mill at gmail.com Thu Jan 18 17:59:52 2007 From: bill.mill at gmail.com (Bill Mill) Date: 18 Jan 2007 14:59:52 -0800 Subject: Regex Question In-Reply-To: References: <1168976209.504793.51890@38g2000cwa.googlegroups.com> Message-ID: <1169161192.284820.196970@m58g2000cwm.googlegroups.com> Gabriel Genellina wrote: > At Tuesday 16/1/2007 16:36, Bill Mill wrote: > > > > py> import re > > > py> rgx = re.compile('1?') > > > py> rgx.search('a1').groups() > > > (None,) > > > py> rgx = re.compile('(1)+') > > > py> rgx.search('a1').groups() > > > >But shouldn't the ? be greedy, and thus prefer the one match to the > >zero? This is my sticking point - I've seen that plus works, and this > >just confuses me more. > > Perhaps you have misunderstood what search does. > search( pattern, string[, flags]) > Scan through string looking for a location where the regular > expression pattern produces a match > > '1?' means 0 or 1 times '1', i.e., nothing or a single '1'. > At the start of the target string, 'a1', we have nothing, so the re > matches, and returns that occurrence. It doesnt matter that a few > characters later there is *another* match, even if it is longer; once > a match is found, the scan is done. > If you want "the longest match of all possible matches along the > string", you should use findall() instead of search(). > That is exactly what I misunderstood. Thank you very much. -Bill Mill bill.mill at gmail.com From vpolukcht at gmail.com Thu Jan 18 04:49:27 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 18 Jan 2007 01:49:27 -0800 Subject: One more regular expressions question Message-ID: <1169113767.320500.71200@11g2000cwr.googlegroups.com> I have a couple of strings like: Unassigned Number (1) 32 No Route To Destination (3) 12 Normal call clearing (16) 2654 User busy (17) 630 No user respond (18) 5 User alerting no answer (19) 16 Call rejected (21) 3 Destination out of order (27) 1 Invalid number format (28) 32 Normal unspecified (31) 32 No channel available (34) 2 Temporary failure (41) 11 Switching equipment congestion (42) 4 Resource unavailable unspecified (47) 2 Bearer capability not authorized (57) 73 Incomp. dest. / Non-existent CUG (88) 1 Recovery on timer expiry (102) 2 Interworking, unspecified (127) 5 I need to get: Error code (value in brackets) - Value - Message. My actual problem is i can't get how to include space, comma, slash. From smusnmrNOSPAM at yahoo.com Wed Jan 10 02:25:16 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Wed, 10 Jan 2007 08:25:16 +0100 Subject: how to clean sys.path References: Message-ID: Thank you Laszlo! Take care, siggi "Laszlo Nagy" schrieb im Newsbeitrag news:mailman.2489.1168367359.32031.python-list at python.org... > >> >> So far, I know only the command >>>sys.path.append(r'c:....etc...'), but >> how to delete or insert at the beginning of the list, I know not. >> > You can delete a slice. For example, > > del sys.path[2:5] > > More about slicing: http://docs.python.org/ref/slicings.html > sys.path is a regular list. List methods: > http://docs.python.org/tut/node7.html > > Best, > > Laszlo > From steven.bethard at gmail.com Sun Jan 28 00:35:30 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 27 Jan 2007 22:35:30 -0700 Subject: distutils, sdist and tests In-Reply-To: References: Message-ID: Robert Kern wrote: > Steven Bethard wrote: >> Robert Kern wrote: >>> Steven Bethard wrote: >>>> How do I get distutils to include my testing module in just the "sdist" >>>> distribution? >>> Use a MANIFEST. >>> >>> http://docs.python.org/dist/source-dist.html > > Also, I just noted this tidbit: > > """If you don't supply an explicit list of files (or instructions on how to > generate one), the sdist command puts a minimal default set into the source > distribution: > ... > * anything that looks like a test script: test/test*.py (currently, the > Distutils don't do anything with test scripts except include them in source > distributions, but in the future there will be a standard for testing Python > module distributions) > ... > """ > > So you can just stick test_argparse.py into a test/ directory. Having tested > this, it appears to work (see below). Yeah, I was trying to avoid having to put it in a test/ directory. When they're in the same directory, I can just run test_argparse.py and it tests the local one instead of the one I have installed in site-packages. When it's in a test/ directory, running test/test_argparse.py tests the one in site-packages. I did try putting test_argparse.py in a test/ directory though, and it doesn't seem to solve the problem -- test_argparse.py gets put into site-packages with the "bdist" command: > python setup.py sdist running sdist warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list) writing manifest file 'MANIFEST' creating argparse-0.6.0 creating argparse-0.6.0\test copying files to argparse-0.6.0... copying README.txt -> argparse-0.6.0 copying argparse.py -> argparse-0.6.0 copying setup.py -> argparse-0.6.0 copying test\test_argparse.py -> argparse-0.6.0\test creating 'dist\argparse-0.6.0.zip' and adding 'argparse-0.6.0' to it adding 'argparse-0.6.0\argparse.py' adding 'argparse-0.6.0\PKG-INFO' adding 'argparse-0.6.0\README.txt' adding 'argparse-0.6.0\setup.py' adding 'argparse-0.6.0\test\test_argparse.py' removing 'argparse-0.6.0' (and everything under it) > python setup.py bdist_dumb running bdist_dumb running build running build_py installing to build\bdist.win32\dumb running install running install_lib creating build\bdist.win32\dumb creating build\bdist.win32\dumb\Program Files creating build\bdist.win32\dumb\Program Files\Python creating build\bdist.win32\dumb\Program Files\Python\Lib creating build\bdist.win32\dumb\Program Files\Python\Lib\site-packages copying build\lib\argparse.py -> build\bdist.win32\dumb\Program Files\Python\Lib\site-packages copying build\lib\test_argparse.py -> build\bdist.win32\dumb\Program Files\Python\Lib\site-packages byte-compiling build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\argparse.py to argparse.pyc byte-compiling build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\test_argparse.py to test_argparse.pyc running install_egg_info Writing build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\argparse-0.6.0-py2.5.egg-info creating 'dist\argparse-0.6.0.win32.zip' and adding '.' to it adding 'Program Files\Python\Lib\site-packages\argparse-0.6.0-py2.5.egg-info' adding 'Program Files\Python\Lib\site-packages\argparse.py' adding 'Program Files\Python\Lib\site-packages\argparse.pyc' adding 'Program Files\Python\Lib\site-packages\test_argparse.py' adding 'Program Files\Python\Lib\site-packages\test_argparse.pyc' removing 'build\bdist.win32\dumb' (and everything under it) >> Using a MANIFEST appears to do the same thing as putting "test_argparse" >> into py_modules -- that is, it puts "test_argparse.py" into both "sdist" >> and "bdist" distributions. In "bdist" distributions it gets installed to >> the site-packages directory like any other module. > > Are you sure that you don't have changes left over in your setup.py when you > tested that? Yep. (Though I still cleared everything out and tried it again.) Here's what I got using an unmodified setup.py and the MANIFEST.in you suggested. Note that the "bdist" version is putting test_argparse.py into site-packages. > type MANIFEST.in include PKG-INFO include *.txt include *.py > python setup.py sdist running sdist reading manifest template 'MANIFEST.in' warning: no files found matching 'PKG-INFO' writing manifest file 'MANIFEST' creating argparse-0.6.0 copying files to argparse-0.6.0... copying LICENSE.txt -> argparse-0.6.0 copying README.txt -> argparse-0.6.0 copying argparse.py -> argparse-0.6.0 copying setup.py -> argparse-0.6.0 copying test_argparse.py -> argparse-0.6.0 creating 'dist\argparse-0.6.0.zip' and adding 'argparse-0.6.0' to it adding 'argparse-0.6.0\argparse.py' adding 'argparse-0.6.0\LICENSE.txt' adding 'argparse-0.6.0\PKG-INFO' adding 'argparse-0.6.0\README.txt' adding 'argparse-0.6.0\setup.py' adding 'argparse-0.6.0\test_argparse.py' removing 'argparse-0.6.0' (and everything under it) > python setup.py bdist_dumb running bdist_dumb running build running build_py installing to build\bdist.win32\dumb running install running install_lib creating build\bdist.win32\dumb creating build\bdist.win32\dumb\Program Files creating build\bdist.win32\dumb\Program Files\Python creating build\bdist.win32\dumb\Program Files\Python\Lib creating build\bdist.win32\dumb\Program Files\Python\Lib\site-packages copying build\lib\argparse.py -> build\bdist.win32\dumb\Program Files\Python\Lib\site-packages copying build\lib\test_argparse.py -> build\bdist.win32\dumb\Program Files\Python\Lib\site-packages byte-compiling build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\argparse.py to argparse.pyc byte-compiling build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\test_argparse.py to test_argparse.pyc running install_egg_info Writing build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\argparse-0.6.0-py2.5.egg-info creating 'dist\argparse-0.6.0.win32.zip' and adding '.' to it adding 'Program Files\Python\Lib\site-packages\argparse-0.6.0-py2.5.egg-info' adding 'Program Files\Python\Lib\site-packages\argparse.py' adding 'Program Files\Python\Lib\site-packages\argparse.pyc' adding 'Program Files\Python\Lib\site-packages\test_argparse.py' adding 'Program Files\Python\Lib\site-packages\test_argparse.pyc' removing 'build\bdist.win32\dumb' (and everything under it) STeVe From jason at tishler.net Wed Jan 24 07:43:55 2007 From: jason at tishler.net (Jason Tishler) Date: Wed, 24 Jan 2007 07:43:55 -0500 Subject: sys.path issue in cygwin In-Reply-To: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> References: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> Message-ID: <20070124124355.GA1308@tishler.net> Wang, On Wed, Jan 24, 2007 at 04:14:48PM +0800, Wang Shuhao wrote: > I successfully built and installed Python 2.2.3 in cygwin. > [snip] > Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is > installed in /usr/local/lib/python2.2.3. The result of the issue is > that when you run a program python can't find the module. So what I > really want to know is where these path came from and how to fix it. Why not use the Python that is part of the standard Cygwin distribution? Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From weekender_ny at yahoo.com Mon Jan 15 23:46:45 2007 From: weekender_ny at yahoo.com (John) Date: 15 Jan 2007 20:46:45 -0800 Subject: html + javascript automations = [mechanize + ?? ] or something else? In-Reply-To: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> Message-ID: <1168922805.176693.149060@q2g2000cwa.googlegroups.com> I am curious about the webbrowser module. I can open up firefox using webbrowser.open(), but can one control it? Say enter a login / passwd on a webpage? Send keystrokes to firefox? mouse clicks? Thanks, --j John wrote: > I have to write a spyder for a webpage that uses html + javascript. I > had it written using mechanize > but the authors of the webpage now use a lot of javascript. Mechanize > can no longer do the job. > Does anyone know how I could automate my spyder to understand > javascript? Is there a way > to control a browser like firefox from python itself? How about IE? > That way, we do not have > to go thru something like mechanize? > > Thanks in advance for your help/comments, > --j From paddy3118 at netscape.net Fri Jan 5 01:20:51 2007 From: paddy3118 at netscape.net (Paddy) Date: 4 Jan 2007 22:20:51 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1167974907.497878.61070@i15g2000cwa.googlegroups.com> Message-ID: <1167978050.971481.111880@q40g2000cwq.googlegroups.com> belinda thom wrote: > On Jan 4, 2007, at 9:28 PM, Carl Banks wrote: > > > jeremito wrote: > >> I am writing a class that is intended to be subclassed. What is the > >> proper way to indicate that a sub class must override a method? > > > > You can't (easily). > > > > If your subclass doesn't override a method, then you'll get a big fat > > AttributeError when someone tries to call it. But this doesn't stop > > someone from defining a subclass that fails to override the method. > > Only when it's called will the error show up. You can, as others have > > noted, define a method that raises NotImplementedError. But this > > still > > doesn't stop someone from defining a subclass that fails to override > > the method. The error still only occurs when the method is called. > > > > There are some advantages to using NotImplementedError: > > > > 1. It documents the fact that a method needs to be overridden > > 2. It lets tools such as pylint know that this is an abstract method > > 3. It results in a more informative error message > > > > But, in the end, if someone wants to define a class that defiantly > > refuses to declare a method, you can't stop them. > > This is the con of a dynamic language... In a language that has statements to force the user to over-ride a method when a class is sub-classed, what is to stop the lazy sub-classer from doing the equivalent of: define override_me(self, ...): pass And so get code through the compiler,, allowing them to 'meet their targets'? - Paddy. From bdesth.quelquechose at free.quelquepart.fr Wed Jan 24 15:13:44 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Jan 2007 21:13:44 +0100 Subject: Thoughts on using isinstance In-Reply-To: References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> Message-ID: <45b7b73b$0$391$426a74cc@news.free.fr> Matthew Woodcraft a ?crit : > abcd wrote: > >>Well my example function was simply taking a string and printing, but >>most of my cases would be expecting a list, dictionary or some other >>custom object. Still propose not to validate the type of data being >>passed in? > > > > There are many people here who will indeed suggest that you're still > best off not validating. > > There are various points to consider: > > - Not adding the validation code saves a certain amount of effort. Yes > - Not adding the validation code avoids one source of possible bugs. Yes > - Not adding the validation code can make your code more readable, in > that there's that much less uninteresting code for your readers to > skip before they get to the meat. Yes > - Adding the validation code can make your code more readable, in that > it can be clearer to the readers what kind of values are being > handled. This is better expressed in the docstring. And if it's in the docstring, you can't be blamed for misuse. > - If you validate, you can raise an exception from the start of your > function with a fairly explicit message. If you don't validate, > you're likely to end up with an exception whose message is something > like 'iteration over non-sequence', and it might be raised from some > function nested several levels deeper in. And what is the stack backtrace for, actually ? > The latter can be harder for the user of your function to debug (in > particular, it may not be easy to see that the problem was an invalid > parameter to your function rather than a bug in your function itself, > or corrupt data elsewhere in the system). docstrings and unit-tests should make it clear. > - If you don't validate, your function will accept anything that > behaves sufficiently like a list/dictionary/custom-object for its > purposes. Yes > You may consider this an advantage or a disadvantage. To some extent > it depends on the circumstances in which the function is used: if > someone passes a not-quite-a-file (say) to a function expecting a > file, is it more likely that this is because of a subtle bug that > they'll be pleased to learn about early, or that they wanted the > function to 'do the obvious thing' with it? Python's POV on this is quite clear IMHO. Now if one want to have to declare everything three times and write layers and layers of adapters and wrappers, well, he knows where to find Java !-) > - In particular, suppose your function expects a list and someone > passes a string when they should have passed a list containing only > that string. If you don't validate, the function is likely to process > the string the same way as it would process a list containing a > number of single-character strings. Yes. This is a very common Python gotcha. And one that is usually quite easy to spot and fix, even manually (let's not talk about unit-tests). > This might well lead to your program apparently completing > successfully but giving the wrong result (which is usually the kind > of error you most want to avoid). Compared to what C or C++ can do to your system, this is still a pretty minor bug - and probably one of the most likely to be detected very early (did I talk about unit tests ?). From vpat at fastwebnet.it Tue Jan 23 06:26:22 2007 From: vpat at fastwebnet.it (Pat) Date: 23 Jan 2007 03:26:22 -0800 Subject: I need suggests Message-ID: <1169551582.196591.48140@v45g2000cwv.googlegroups.com> I have to do a big programm. Could someone give me some suggests about IDE (on Linux) and books to learn. From Art at Arthurian.com Mon Jan 29 13:14:18 2007 From: Art at Arthurian.com (Frank Arthur) Date: Mon, 29 Jan 2007 13:14:18 -0500 Subject: Excellent Interview with Dennis D'Souza, full of laughs References: <1170083292.991070.79560@v33g2000cwv.googlegroups.com> Message-ID: Real funny? Holocaust Deniers Convention in Iran? Sick, sick Islamists! wrote in message news:1170083292.991070.79560 at v33g2000cwv.googlegroups.com... > http://a1135.g.akamai.net/f/1135/18227/1h/cchannel.download.akamai.com/ > 18227/podcast/PORTLAND-OR/KPOJ-AM/1-23-07%20POJ-cast.mp3? From gagsl-py at yahoo.com.ar Fri Jan 19 14:50:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 16:50:26 -0300 Subject: Asyncore select statement problem In-Reply-To: <1169228524.810461.51160@a75g2000cwd.googlegroups.com> References: <1169075120.491855.103200@q2g2000cwa.googlegroups.com> <1169228524.810461.51160@a75g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20070119164445.03eade68@yahoo.com.ar> At Friday 19/1/2007 14:42, JamesHoward wrote: >Thank you for the responses. I have learned considerably more about >how Asyncore works because of it. > >The problem that I see is that Asyncore's poll function does not seem >to be thread safe. From what I can tell, I am calling >dispatcher.close() properly and the dispatchers are removed from >asyncore's global map (all except the server itself). However, it >seems like the error happens when the poll function gets the file >descriptors to run select on and then the thread ticks and removes them >from the global map. After this the select call is made, but the file >descriptors are not valid anymore. > >I guess I have two questions as a result. First, is this a problem >that anyone else has had and second is there a fix for it? I have >tried looking for Asyncore thread safe topics in Google, but without >much luck. If needed I think making the poll function atomic in the >asyncore module might fix this problem, but I wanted to see what other >people thought first. Usually asyncore is used with only one thread - that's one of the reasons of using it btw. You can spawn other working threads, but they don't usually interact with the networking stuff directly. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jairodsl at gmail.com Sat Jan 13 19:48:31 2007 From: jairodsl at gmail.com (jairodsl) Date: 13 Jan 2007 16:48:31 -0800 Subject: Comparing a matrix (list[][]) ? In-Reply-To: References: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> Message-ID: <1168735711.257634.306140@m58g2000cwm.googlegroups.com> Ok, the main idea is compare each element with others elements, and go saving the minus element positive and his position (X,Y) in the matrix, of course min function dont let me save this position (X,Y). I dont know if its possible do that with min function. jDSL Roberto Bonvallet wrote: > > What output are you expecting from your example matrix? If you are expecting > it to be 5 (the smallest positive element), using "min" is the way to do it: > > >>> matrix = [[9, 8, 12, 15], > ... [0, 11, 15, 18], > ... [0, 0, 10, 13], > ... [0, 0, 0, 5]] > >>> min(min(x for x in row if x > 0) for row in matrix) > 5 > > -- > Roberto Bonvallet From jrpfinch at gmail.com Fri Jan 12 09:24:48 2007 From: jrpfinch at gmail.com (jrpfinch) Date: 12 Jan 2007 06:24:48 -0800 Subject: Newbie imap lib question Message-ID: <1168611888.009894.271190@51g2000cwl.googlegroups.com> I have three messages in my inbox. Why does messageCount = gServer.select('INBOX') not just return OK and 3. See below for examples - seems to be completely random how many threes it returns. The documentation for imaplib seems sparse. Does anybody have any good links? Many thanks, Jon messageCount = 0 : OK 1 : ['3'] messageCount = 0 : OK 1 : ['3', '3', '3'] messageCount = 0 : OK 1 : [None] messageCount = 0 : OK 1 : ['3', '3'] From nospam.notospam at gmail.com Sat Jan 20 02:16:18 2007 From: nospam.notospam at gmail.com (Drew) Date: 19 Jan 2007 23:16:18 -0800 Subject: multiple file deletes using ftp.delete Message-ID: <1169277378.015620.208910@51g2000cwl.googlegroups.com> Hi all I'm fairly new to python so please forgive my lack of comprehension of the obvious. I'm writing a script to ftp files to a server. This script will run weekly. Part of the script first deletes the previous weeks files. The problem is I'm never sure of the exact number and full name of the files that need to be deleted. All the files start with the same string but have different extensions (eg drew.1 drew.2 drew.tmp drew.hlp). So I was wondering if anybody knows how to use a wild card similar to * in UNIX to do the delete? Something like: ftp.delete("drew.*") Any help or suggestions would be greatly appreciated. Drew Dowling From consmash at gmail.com Tue Jan 23 13:28:00 2007 From: consmash at gmail.com (consmash at gmail.com) Date: 23 Jan 2007 10:28:00 -0800 Subject: Reading character from keyboard In-Reply-To: References: Message-ID: <1169576879.920810.306490@q2g2000cwa.googlegroups.com> Tommy Grav napisal(a): > A very simple question. I would like to read a single character from the > keyboard (y or n). I have tried to look in my Python books and a google > search, but have come up empty. I am sure the info s out there, but I > guess I am unable to find the right question or search keyword :o/ > > Any hints or help appreciated > Cheers > Tommy Actually, if you want to read only one character from keyboard, you will need to use terminal operations rather than plain input stream. Unfortunately this is rather not portable solution. For Windows you have to import msvcrt, on Unices curses module. The latter code is quite similar. Example: import msvcrt def prompt(msg='Your choice: ', options={'y': True, 'n': False}): while True: print msg key = msvcrt.getch() choice = str(key).lower() if options.has_key(choice): break print 'You entered wrong key! Enter again.' return options[choice] print prompt() and 'Good for you.' or 'Bad Luck.' From tiedon_jano at hotmail.com Wed Jan 3 04:59:59 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Wed, 03 Jan 2007 09:59:59 GMT Subject: import order or cross import In-Reply-To: References: Message-ID: Roland Hedberg kirjoitti: > Hi! > > I'm having a bit of a problem with import. > > I'm writing a marshalling system that based on a specification will > create one or more files containing mostly class definitions. > > If there are more than one file created (and there are reasons for > creating more than one file in some instances) then they will import > each other since there may be or is interdependencies in between them. > > And this is where the going gets tough. > > Let's assume I have the following files: > > ------------- ONE.py -------------------- > > import TWO > > class Car: > def __init__(self): > self.color = None > > def set_color(self,v): > if isinstance(v,TWO.Black) or isinstance(v,TWO.White): > self.color = v > > class BaseColor: > def __init__(self): > pass > def __str__(self): > return self.color > > if __name__ == "__main__": > car = Car() > color = TWO.Black() > car.set_color(color) > print car.color > > -------------- TWO.py ------------------- > > import ONE > > class Black(ONE.BaseColor): > color = "Black" > def __init__(self): > ONE.BaseColor.__init__(self) > > class White(ONE.BaseColor): > color = "White" > def __init__(self): > ONE.BaseColor.__init__(self) > > ----------------------------------------- > > Now, running ONE.py causes no problem it will print "Black", but running > TWO.py I get: > AttributeError: 'module' object has no attribute 'BaseColor' > > So, how can this be solved if it can be ? > > To join ONE.py and TWO.py into one file could be a solution if there > where no other conditions (non-language based) that prevented it. > > -- Roland > Maybe I'm missing something, but why is the class BaseColor in file ONE.py and not in TWO.py? Cheers, Jussi From tim.one at comcast.net Tue Jan 9 15:43:54 2007 From: tim.one at comcast.net (Tim Peters) Date: Tue, 09 Jan 2007 14:43:54 -0600 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: [Tim Peters] ... >|> Well, just about any technical statement can be misleading if not >|> qualified to such an extent that the only people who can still >|> understand it knew it to begin with <0.8 wink>. The most dubious >|> statement here to my eyes is the intro's "exactness carries over >|> into arithmetic". It takes a world of additional words to explain >|> exactly what it is about the example given (0.1 + 0.1 + 0.1 - 0.3 = >|> 0 exactly in decimal fp, but not in binary fp) that does, and does >|> not, generalize. Roughly, it does generalize to one important >|> real-life use-case: adding and subtracting any number of decimal >|> quantities delivers the exact decimal result, /provided/ that >|> precision is set high enough that no rounding occurs. [Nick Maclaren] > Precisely. There is one other such statement, too: "Decimal numbers > can be represented exactly." What it MEANS is that numbers with a > short representation in decimal can be represented exactly in decimal, > which is tautologous, but many people READ it to say that numbers that > they are interested in can be represented exactly in decimal. Such as > pi, sqrt(2), 1/3 and so on .... Huh. I don't read it that way. If it said "numbers can be ..." I might, but reading that way seems to requires effort to overlook the "decimal" in "decimal numbers can be ...". [attribution lost] >|>> and how is decimal no better than binary? >|> Basically, they both lose info when rounding does occur. For >|> example, > Yes, but there are two ways in which binary is superior. Let's skip > the superior 'smoothness', as being too arcane an issue for this > group, With 28 decimal digits used by default, few apps would care about this anyway. > and deal with the other. In binary, calculating the mid-point > of two numbers (a very common operation) is guaranteed to be within > the range defined by those numbers, or to over/under-flow. > > Neither (x+y)/2.0 nor (x/2.0+y/2.0) are necessarily within the range > (x,y) in decimal, even for the most respectable values of x and y. > This was a MAJOR "gotcha" in the days before binary became standard, > and will clearly return with decimal. I view this as being an instance of "lose info when rounding does occur". For example, >>> import decimal as d >>> s = d.Decimal("." + "9" * d.getcontext().prec) >>> s Decimal("0.9999999999999999999999999999") >>> (s+s)/2 Decimal("1.000000000000000000000000000") >>> s/2 + s/2 Decimal("1.000000000000000000000000000") "The problems" there are due to rounding error: >>> s/2 # "the problem" in s/2+s/2 is that s/2 rounds up to exactly 1/2 Decimal("0.5000000000000000000000000000") >>> s+s # "the problem" in (s+s)/2 is that s+s rounds up to exactly 2 Decimal("2.000000000000000000000000000") It's always something ;-) From nogradi at gmail.com Thu Jan 25 18:43:58 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 26 Jan 2007 00:43:58 +0100 Subject: [ANN] markup.py 1.6 Message-ID: <5f56302b0701251543k53f757ccode696257e25bb893@mail.gmail.com> The new 1.6 release of markup.py is available for download: http://sourceforge.net/project/showfiles.php?group_id=161108 What is it? Markup.py is an intuitive, lightweight, easy-to-use, customizable and pythonic HTML/XML generator. Where is the documentation? http://markup.sourceforge.net/ Why is it called markup.py and not markup? This way it's easier to search for it online and also shows that it's a single module. Also note that the former Markup project of Edgewall changed its name to Genshi in the meantime. Please send comment/feedback/bugs/etc to nogradi at gmail.com From fart at brain.org Tue Jan 30 09:56:07 2007 From: fart at brain.org (brainfart) Date: Tue, 30 Jan 2007 06:56:07 -0800 Subject: KEEP YOUR MOUTH SHUT Re: Did The Chinese Violate Any Treaties? In-Reply-To: <1169260616.079301.149020@51g2000cwl.googlegroups.com> References: <45c523e1.95039880@news.giganews.com> <1169260616.079301.149020@51g2000cwl.googlegroups.com> Message-ID: thermate at india.com wrote... > In this evil regime of George W Bush, you better keep your mouth > shut about international treaties. Many more finger will point at > you if you even point one finger at others. I'm not sure if there is a treaty regarding such tests, and if there is I doubt China signed it and the USA only signed it after it had already conducted such tests and collected all the data it needs to ensure a reliable anti-satellite weapon system. Just like how the USA called for a worldwide nuclear test ban after it had already tested enough atomic bombs to gather all possible information on nuclear explosions, so the only ones affected by such bans are the up and coming world powers who missed the opportunity to conduct basic scientific research in those areas before the ban took effect. As for this particular test, it is China's way of telling us to go fuck ourselves if we think we have any say about China's reconquest of Taiwan. As an American, I can tell you that there is no way we are going to support Taiwan if it means the destruction of our satellite infrastructure and thus our way of life. Half of America would drive off cliffs as their GPS navigators stopped working, and the other half would quickly surrender to the Chinese in exchange for restoring cellular telephone service. From Thomas.Ploch at gmx.net Sun Jan 7 09:02:15 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 15:02:15 +0100 Subject: I want to learn In-Reply-To: <1168174097.252001.71130@s80g2000cwa.googlegroups.com> References: <1168174097.252001.71130@s80g2000cwa.googlegroups.com> Message-ID: <45A0FD67.4070104@gmx.net> joeyslistings at yahoo.com schrieb: > Hi, > > I have been "programming" in the .net environment and ide for a few > years and I am looking to make the switch over to python. I have > absolutely no python experience whatsoever. I am looking for a python > guru who has instant messenger or gtalk or whatever who can meet me > online in the mornings, give me some direction for the day and then > answer some questions here and there online throughout the day. So you are looking for a person (no, a guru), that stays by your side the whole day, gives you answers and helps you learning python. This is a ridiculous request. If you want to learn python, you should start with visiting http://www.diveintopython.org/ and read it. If you have previous programming experience, this is the place to start. > Sorry to interrupt the group but since all python gurus appear to be > happily at work on the next level apps at google nobody responded to > my craigslist ads. You can always ask your questions here on the list, there are enough people that are willing to help. Thomas From ironfroggy at gmail.com Wed Jan 17 21:19:52 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 17 Jan 2007 21:19:52 -0500 Subject: [Python-Dev] Deletion order when leaving a scope? In-Reply-To: <45AEC612.1030001@hastings.org> References: <45AEC612.1030001@hastings.org> Message-ID: <76fd5acf0701171819l542db814h593913d4010d62a2@mail.gmail.com> Absolutely an irrelevent side effect, especially when you take into consideration the 4 and counting alternative implementations of the language. None the less, I can explain why it is as it is, keeping in mind its not like that on purpose, its just how it is. Locals are optimized into an array for fast lookup. Every name assigned to in a function is known as a local in that function and this internal array holds its reference. It is simply a product of the array indexes and deletion order being the same, 0 to N. On 1/17/07, Larry Hastings wrote: > > > > I just ran a quickie experiment and determined: when leaving a scope, > variables are deleted FIFO, aka in the same order they were created. This > surprised me; I'd expected them to be deleted LIFO, aka last first. Why is > it thus? Is this behavior an important feature or an irrelevant > side-effect? > > Cheers, > > > larry > > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > http://mail.python.org/mailman/options/python-dev/ironfroggy%40gmail.com > > > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From ziga.seilnacht at gmail.com Tue Jan 2 20:00:26 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 2 Jan 2007 17:00:26 -0800 Subject: Python embedded interpreter: how to initialize the interpreter ? References: <1167573333.723607.199480@v33g2000cwv.googlegroups.com> Message-ID: <1167786026.593197.101780@42g2000cwt.googlegroups.com> ycollet at freesurf.fr wrote: > Hello, > > I've written a C embedded application. I want to open a python gui > application in my C program but when I do : > > PyRun_String( "import gui.py", file_input, pDictionary, pDictionary ); > > the interpreter emits an error: tkinter module not defined > > What script must I load to initialize the embedded python interpreter > so as I have the same modules in the python command line and in the > python embedded interpreter ? /usr/lib/python2.4/*.py ?? > > Yann COLLETTE Did you call the Py_Initialize() function before trying to execute that statement? Note also that you might have to Py_SetProgramName(somepath) before calling Py_Initialize(). See the documentation for details: http://docs.python.org/ext/embedding.html http://docs.python.org/api/embedding.html Hope this helps, Ziga From felipe.lessa at gmail.com Wed Jan 3 19:36:20 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 3 Jan 2007 22:36:20 -0200 Subject: static object In-Reply-To: <459c306c$0$314$426a74cc@news.free.fr> References: <459c306c$0$314$426a74cc@news.free.fr> Message-ID: On 1/3/07, meelab wrote: > I am looking for a way to create a "static object" or a "static class" - > terms might be inappropriate - having for instance: An example will speak better than me: class Card(object): __cards = {} def __init__(self, number, suit): self.number, self.suit = number, suit def __new__(cls, number, suit): try: return cls.__cards[(number, suit)] except KeyError: obj = object.__new__(cls, number, suit) cls.__cartas[(number, suit)] = obj return obj -- Felipe. From libintr at gmail.com Fri Jan 12 11:48:16 2007 From: libintr at gmail.com (lee) Date: 12 Jan 2007 08:48:16 -0800 Subject: modules...n methods Message-ID: <1168620496.520506.296330@q2g2000cwa.googlegroups.com> First of all thnx guys for ur cover on ma questions....Ok some more then...whats the way to read the sourcecode of methods and built in functions? From paul at boddie.org.uk Fri Jan 12 09:08:38 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Jan 2007 06:08:38 -0800 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: <1168610918.587465.197740@51g2000cwl.googlegroups.com> Konrad Hinsen wrote: > > That's one more project... It seems that there is significant > interest in parallel computing in Python. Perhaps we should start a > special interest group? Not so much in order to work on a single > project; I believe that at the current state of parallel computing we > still need many different approaches to be tried. But an exchange of > experience could well be useful for all of us. I think a special interest group might be productive, but I've seen varying levels of special interest in the different mailing lists associated with such groups: the Web-SIG list started with enthusiasm, produced a cascade of messages around WSGI, then dried up; the XML-SIG list seems to be a sorry indication of how Python's XML scene has drifted onto other matters; other such groups have also lost their momentum. It seems to me that a more useful first step would be to create an overview of the different modules and put it on the python.org Wiki: http://wiki.python.org/moin/FrontPage http://wiki.python.org/moin/UsefulModules (a reasonable entry point) If no-one beats me to it, I may write something up over the weekend. Paul From phil at riverbankcomputing.co.uk Tue Jan 23 07:04:26 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 23 Jan 2007 12:04:26 +0000 Subject: PyQt4 strangeness In-Reply-To: References: Message-ID: <200701231204.26654.phil@riverbankcomputing.co.uk> On Tuesday 23 January 2007 10:31 am, Tina I wrote: > I'm trying to 'convert' my self from Qt3 to Qt4 (it rocks!) and one > thing seem strange: > With Qt3 I usually did "from qt import *", but this does not seem to > work with Qt4. I have to use "from PyQt4 import QtGui , QtCore" and also > have to use "QtCore.something". > > Like when connecting a button: > > self.connect(self.ui.testButton, QtCore.SIGNAL("clicked()"), > self.doSomething) > > Anyone know why this is? Or am I missing something very basic here? (I'm > still very much a noob I guess) > > I'm using the Debian packages by the way. The module structure of PyQt reflects the library structure of Qt. Qt4 has different libraries to Qt3 so PyQt4 has different modules to PyQt3. The top level PyQt4 module ensures that PyQt3, PyQt4 (and eventually PyQt5) can all be installed side by side in the same site-packages directory. The style of import statement you use is up to you. All of the PyQt4 examples adopt the style you describe, but you can achieve the equivalent of your current practice by doing the following instead... from PyQt4.Qt import * Phil From gherron at islandtraining.com Tue Jan 23 03:05:33 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 23 Jan 2007 00:05:33 -0800 Subject: How to use dynamic properties? <-- Noob In-Reply-To: References: Message-ID: <45B5C1CD.6010009@islandtraining.com> Sean Schertell wrote: > person.name = 'Joe' > person.age = 20 > person.sex = 'm' > > info_I_need = name > > print person.info_I_need > > # How can I make it print 'Joe' ? > > > Sean > > > :::: DataFly.Net :::: > Complete Web Services > http://www.datafly.net > > Like this: info_I_need = 'name' print getattr(person, info_I_need) Related to getattr are setattr and hasattr. Gary Herron From robert.kern at gmail.com Thu Jan 4 13:54:10 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Jan 2007 12:54:10 -0600 Subject: Set type? In-Reply-To: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> References: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> Message-ID: _ wrote: > How do you check to see if a variable is a set? I would like to use > > if type(var) is types.SetType: > blah > > but that is not available in types module. I am using 2.4 In [1627]: type(set()) is set Out[1627]: True -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From nagle at animats.com Fri Jan 12 18:02:10 2007 From: nagle at animats.com (John Nagle) Date: Fri, 12 Jan 2007 23:02:10 GMT Subject: More M2Crypto issues. Not big ones, though. Message-ID: A list of small problems and bugs in the current M2Crypto: I need to look at SSL certificates in some detail, so this is all about the access functions for certificates. Bugs: 1. Off by one error at "X509.get_ext_count()". Reports eight extensions on a certificate that only has seven. get_ext_at works for extensions 0..6, then returns an undefined for the nonexistent #7. Test against "https://www.verisign.com". Entered into Bugzilla as #7717. 3. /M2Crypto/SSL/Connection.py:147: DeprecationWarning: Old style callback, use cb_func(ok, store) instead return m2.ssl_connect(self.ssl) (Also reported, in Polish, here: http://www.mail-archive.com/pld-devel-pl at lists.pld-linux.org/msg12433.html) Entered into Bugzilla as #7718. 4. "close()" on an SSL socket that's just finished certificate negotiation hangs, at least on Windows. "del" does not hang, but I don't know if there's a leak problem. Not enough info yet to file a bug report. I might be doing something wrong there. Any known "close" issues? Other issues: 1. X509.X509_name.__getattr__: Field retrieval from X.509 name items with x509_name_by_nid retrieves only first instance of field, not all instances. Really should return a list. The same key is used more than once very frequently; these keys aren't unique. It's tempting to treat these things like a hash, but they don't really work that way. As for simply iterating through the name elements, there's no direct way to just get the elements one at a time. X509_Name has an "entry_count" method, but no way to get the Nth entry. As a workaround, I'm converting the X508_name to a string with subjectstr = peer.get_subject().as_text( flags=(m2.XN_FLAG_RFC2253 | m2.ASN1_STRFLGS_UTF8_CONVERT) & ~m2.XN_FLAG_DUMP_UNKNOWN_FIELDS) # in RFC2253 format This is safely parseable. While the default format doesn't have escapes around the delimiter characters, with these flags, entries are comma-separated with backslash escapes where necessary. This works, unlike the "server()" function in Python's built-in SSL, which returns a debug format that has the same characters as delimiters and text. 2. Unclear if M2Crypto's X.509 interface is UTF-8 compatible. OpenSSL will return info in UTF-8 if you use the ASN1_STRFLGS_UTF8_CONVERT flag on as_text, but unclear if the M2 glue code handles this correctly. Haven't found a UTF8 cert to test it on yet. Other than that, I'm having relatively good results with M2Crypto. John Nagle From sean at datafly.net Fri Jan 26 19:01:25 2007 From: sean at datafly.net (Sean Schertell) Date: Sat, 27 Jan 2007 09:01:25 +0900 Subject: Off-Topic Posts In-Reply-To: <1169852537.508485.13260@v33g2000cwv.googlegroups.com> References: <1169821615.198847.237790@m58g2000cwm.googlegroups.com> <1169852010.083168.81900@h3g2000cwc.googlegroups.com> <1169852537.508485.13260@v33g2000cwv.googlegroups.com> Message-ID: <8FF0B818-AD0B-4743-8D95-A84A7955F532@datafly.net> Hey Genius -- I'm probably further to the left and even more vehemently opposed to the Bush/Cheney regime than you are. But could you *please* take your unwelcome ranting elsewhere? You're not winning any converts here. And you're alienating your ideological allies to boot. Give it a rest, m'kay? Sean P.S. Printing letters in all-caps and using extra exclamation points doesn't necessarily make your argument any more compelling. On Jan 27, 2007, at 8:02 AM, thermate at india.com wrote: > What did Dick Faced Cheney told Honorable Senator Patrick Leahy ? > "Fuck > yourself". > So much for politeness and vulgarity at the top level. > > Proof: > http://www.capitolhillblue.com/news2/2007/01/the_madness_of.html > > On Jan 26, 2:53 pm, therm... at india.com wrote: >> Yeah, listen to wise counsel of klein. As a member of conquered races >> and still under occupation, namely Jewish, French, German, Japanese, >> Korean ... dont mess in the crimes of the anglo-saxon yanks. You >> should >> remember the beating you got from the Anglo-Saxon Yanks and just keep >> quiet ... As for the lunatics off their meds, its also true that 911 >> was a grand optical illusion and thus within the charter of this >> group >> to study ... After all, one of its proponent is the former head of >> Star >> Wars, Dr Bob Bowman from MIT and Caltech ... Do you have a degree >> from >> those prestigious institutes or did you manage to get any of your >> kids >> into one of them ??? As for vulgarity, its the mark of patriotism ... >> the constitutional amendments guarantee it and Herbert Walker Bush >> was >> a strongly suspected pedophile ... there is a video called conspiracy >> of silence, watch it on video.google.com and download with before the >> fascist bureau of incompetence bastards (running around like crazy >> rats >> to confiscate pentagon videos on that day in destruction of evidence) >> try to sabotage the google servers ... they are part of the crime and >> complicit in it. If they were competent, we would see one consistent >> theory coming out from that bureau to explain all significant >> events on >> that day. Now dont forget the SHITTY job done by FEMA and NIST. There >> are gaping holes in their work. >> >> Hey Kinch, if you are jewish, did you forget that England was the >> first >> country to expel the Jews. >> >> If you forget your status as conquered races, then you are in >> delusion, >> not anyone else. >> >> The final balance of power provided against the anglos will be by >> Slavs. Hurray to Vladimir Putin, and Mikhail Khodorkovsky in a >> Siberian >> jail. >> >> On Jan 26, 1:13 pm, Richard J Kinch wrote: >> >>> alex writes: >>>> I have only just joined this group, but have noticed a >>>> significant rise >>>> in off-topic posts that really detract from what is otherwise an >>>> excellent place to learn and talk about optics.This has nothing >>>> to do with sci.optics. Recent days have seen this stuff >>> being broadcast mechanically into all sorts of groups. > > -- > http://mail.python.org/mailman/listinfo/python-list :::: DataFly.Net :::: Complete Web Services http://www.datafly.net From deets at nospam.web.de Sun Jan 28 09:08:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 28 Jan 2007 15:08:12 +0100 Subject: Locking access to all data members In-Reply-To: <1169976708.934441.213770@h3g2000cwc.googlegroups.com> References: <1169976708.934441.213770@h3g2000cwc.googlegroups.com> Message-ID: <523p32F1mbcmcU1@mid.uni-berlin.de> gooli schrieb: > I have a class with a lot of attributes whose objects are accessed > from multiple threads. I would like to synchronize the access to all > the attributes, i.e. acquire a lock, return the value, release the > lock (in a finally clause). > > Is there a way to do that without turning each attribute into a > property and manually wrapping each property with the locking code? > > How about classes bound with SQLAlchemy? Is it possible to do that for > those too? > > Example of a class I would like to wrap: > > class Job(object): > def __init__(self, itemType): > self.id = self.idSequence > self.itemType = itemType > self.status = "waiting" > self.createDate = None > self.hostName = None > self.progress = 0 > self.items = [] > You can use a metaclass or decorators to put the locking code in place for all methods. I'm not sure though if that interferes with SQLAlchemy. Diez From zion at ee.oulu.fi Fri Jan 26 01:39:30 2007 From: zion at ee.oulu.fi (Simo Hosio) Date: Fri, 26 Jan 2007 08:39:30 +0200 (EET) Subject: problems with pyzeroconf and linux Message-ID: Hi all, I am trying to get pyzeroconf (http://sourceforge.net/projects/pyzeroconf) running on my machine but having trouble... Running the Zeroconf.py file seems to register the service, but is unable to find it. (same situation than in http://www.nabble.com/pyzeroconf-on-linux...-t481215.html, but differenet cause, I'm sure..) """ Multicast DNS Service Discovery for Python, version 0.12 1. Testing registration of a service... Registering service... Registration done. 2. Testing query of service information... Getting ZOE service: None Query done. 3. Testing query of own service... Getting self: None Query done. 4. Testing unregister of service information... Unregister done. """ Running ethereal reveals that there are no responses to the 2) and 3)...The queries are certainly there. I'm runnin this with Ubuntu Dapper in a WLAN network. I am not too familiar with networking in Linux environment, so if anyone has any help on how to get it running, I would appreciate. :) Best Regards, Simo Hosio From cjw at sympatico.ca Tue Jan 30 16:51:49 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 30 Jan 2007 16:51:49 -0500 Subject: Conditional expressions - PEP 308 Message-ID: It would be helpful if the rules of the game were spelled out more clearly. The conditional expression is defined as X if C else Y. We don't know the precedence of the "if" operator. From the little test below, it seem to have a lower precedence than "or". Thus, it is desirable for the user to put the conditional expression in parentheses. Colin W. # condExpr.py # PEP 308 defines a conditional expression as X if C else Y # but we don't know exactly what X is supposed to be. # It doesn't seem to be spelled out in the syntax. def main(): names= ['abc', 'def', '_ghi', 'jkl', '_mno', 'pqrs'] res= '' for w in names: res= res + w if w[0] != '_' else '' z= 1 print 'res1:', res res= '' for w in names: res= res + (w if w[0] != '_' else '') z= 1 print 'res2:', res if __name__ == '__main__': main() Result: [Dbg]>>> res1: pqrs res2: abcdefjklpqrs From thinker at branda.to Mon Jan 15 22:45:40 2007 From: thinker at branda.to (Thinker) Date: Tue, 16 Jan 2007 11:45:40 +0800 Subject: Watch log In-Reply-To: <1168897765.370442.201660@51g2000cwl.googlegroups.com> References: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> <512astF1i9fgbU1@mid.individual.net> <1168897765.370442.201660@51g2000cwl.googlegroups.com> Message-ID: <45AC4A64.90007@branda.to> Salvatore Di Fazio wrote: > Bjoern Schliessmann ha scritto: > > >> Why not read the file continuously and only do something if a new >> line is complete (i. e. a newline char is detected)? >> > > How can I read the file continuously? > > What you want is something like 'tail -f' in linux. If you look into it's source code, you will find it check file periodically. When a read() reach the end of the file, read() will return a empty string. You can try to read data from the file periodically after a EOF. I think it is what you want. -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py From mikael at isy.liu.se Wed Jan 10 10:17:48 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 10 Jan 2007 16:17:48 +0100 Subject: Yield In-Reply-To: <45A502DE.9000901@isy.liu.se> References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> <455c15ca$1@news.eftel.com> <455c1ddf@news.eftel.com> <1163691173.737911.130410@i42g2000cwa.googlegroups.com> <45a3e096$0$8024$3b214f66@tunews.univie.ac.at> <45A502DE.9000901@isy.liu.se> Message-ID: <45A5039C.3070508@isy.liu.se> I wrote: > The definition given there is "In mathematics , a > *prime number* (or a *prime*) is a natural number > that has exactly two (distinct) natural number > divisors ." The important part of the statement is > "exactly two...divisors", which rules out the number 1. Or should I say: Thunderbird made me write:... Those freakin and was not visible before I posted the thing. &%#&%# /MiO From stephan.diehl at gmx.net Mon Jan 29 12:25:28 2007 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 29 Jan 2007 18:25:28 +0100 Subject: next berlin python-group meeting fr., 2.2. Message-ID: after a long (veeerrrryy) long time, I'm pleased to announce our next python meeting in berlin. time: friday 2.2. 7pm place:Cafe & Restaurant UNENDLICH Boetzowstrasse 14 10407 Berlin (Prenzlauer Berg "Boetzowviertel") This is a fun meeting without offical talks. If you haven't done so already, subscribe to http://starship.python.net/cgi-bin/mailman/listinfo/python-berlin for last minute information. If you plan to come, please leave a short notice there, so we know how many people to expect. Cheers Stephan From lamthierry at gmail.com Fri Jan 12 16:38:45 2007 From: lamthierry at gmail.com (Thierry Lam) Date: 12 Jan 2007 13:38:45 -0800 Subject: WMI Python, writing remotely and retrieving env variables values Message-ID: <1168637924.982266.214250@s34g2000cwa.googlegroups.com> I'm using the WMI library for python and I was able to connect to another computer on the network with the following line: c = wmi.WMI(computer="the-network-computer", user="hello", password="hello") Is there a way to write information to a file on that computer? How do I read environment variables, for example SystemDrive? Thierry From m.sloyko at gmail.com Sun Jan 7 18:30:38 2007 From: m.sloyko at gmail.com (Maxim Sloyko) Date: 7 Jan 2007 15:30:38 -0800 Subject: lxml namespaces problem Message-ID: <1168212638.493983.202560@11g2000cwr.googlegroups.com> Hi All! I have a little problem with XML namespaces. In my application I have two XML processors, that process the same document, one after the other. The first one looks for nodes in 'ns1' namespace, and substitutes them, according to some algorithm. After this processor is finished, it is guaranteed that there are no more 'ns1' nodes left in the tree. however 'ns1' namespace dclaration is still there, in the root node (well, I put it there manually). Now, when this namespace is no longer needed, I want to get rid of it, because it confuses some other processors (namely, my browser) So, the question is, how do I do that? del tree.getroot().nsmap['ns1'] does not seem to do the trick :( Thanks in advance and Happy Holidays! From istvan.albert at gmail.com Thu Jan 11 09:54:12 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 11 Jan 2007 06:54:12 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> Message-ID: <1168527252.384422.159880@p59g2000hsd.googlegroups.com> oyekomova wrote: > csvread in Matlab for a very large csv file. Matlab read the file in > 577 seconds. On the other hand, this code below kept running for over 2 > hours. Can this program be made more efficient? FYI There must be something wrong with your setup/program. I work with large csv files as well and I never have performance problems of that magnitude. Make sure you are not doing something else while parsing your data. Parsing 1 million lines with six columns with the program below takes 87 seconds on my laptop. Even your original version with extra slices and all would still only be take about 50% more time. import time, csv, random from numpy import array def make_data(rows=1E6, cols=6): fp = open('data.txt', 'wt') counter = range(cols) for row in xrange( int(rows) ): vals = map(str, [ random.random() for x in counter ] ) fp.write( '%s\n' % ','.join( vals ) ) fp.close() def read_test(): start = time.clock() reader = csv.reader( file('data.txt') ) data = [ map(float, row) for row in reader ] data = array(data, dtype = float) print 'Data size', len(data) print 'Elapsed', time.clock() - start #make_data() read_test() From etatoby at gmail.com Sat Jan 27 11:42:16 2007 From: etatoby at gmail.com (Toby) Date: 27 Jan 2007 16:42:16 GMT Subject: how to remove c++ comments from a cpp file? References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> <1169805244.879280.235660@v45g2000cwv.googlegroups.com> Message-ID: <45bb80e4$0$20806$5fc30a8@news.tiscali.it> Frank Potter wrote: > r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) > f_new=r.sub(ur"",f) >From the documentation: re.MULTILINE When specified [...] the pattern character "$" matches at the end of the string and at the end of each line (immediately preceding each newline). By default [...] "$" matches only at the end of the string. re.DOTALL [...] without this flag, "." will match anything except a newline. So a simple solution to your problem would be: r = re.compile("//.*") f_new = r.sub("", f) Toby From vmalloc at gmail.com Fri Jan 26 04:04:58 2007 From: vmalloc at gmail.com (Rotem) Date: 26 Jan 2007 01:04:58 -0800 Subject: Possible bug in Python 2.5? (Was Re: pdb in python2.5) In-Reply-To: References: <1169717486.230356.79730@l53g2000cwa.googlegroups.com> <1169760673.197226.206540@a75g2000cwd.googlegroups.com> Message-ID: <1169802298.407455.325830@l53g2000cwa.googlegroups.com> > * comp.lang.python is not the place to file bug reports Agreed > * more detail is needed that what's been given so far Agreed. I will investigate further when I get a chance and determine if it's a problem on my end. Thanks a lot! From GatlingGun at gmail.com Tue Jan 30 14:52:24 2007 From: GatlingGun at gmail.com (TOXiC) Date: 30 Jan 2007 11:52:24 -0800 Subject: Find and replace in a file with regular expression Message-ID: <1170186744.322855.253550@j27g2000cwj.googlegroups.com> Hi everyone, First I say that I serched and tryed everything but I cannot figure out how I can do it. I want to open a a file (not necessary a txt) and find and replace a string. I can do it with: import fileinput, string, sys fileQuery = "Text.txt" sourceText = '''SOURCE''' replaceText = '''REPLACE''' def replace(fileName, sourceText, replaceText): file = open(fileName, "r") text = file.read() #Reads the file and assigns the value to a variable file.close() #Closes the file (read session) file = open(fileName, "w") file.write(text.replace(sourceText, replaceText)) file.close() #Closes the file (write session) print "All went well, the modifications are done" replacemachine(fileQuery, sourceText, replaceText) Now all went ok but I'm wondering if it's possible to replace text if / sourceText/ match a regex. Help me please! Thx in advance From tiedon_jano at hotmail.com Sun Jan 7 07:01:30 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 07 Jan 2007 12:01:30 GMT Subject: still struggling, howto use a list-element as a name ? Sory, hit send button to early In-Reply-To: References: <45a01981$0$296$426a74cc@news.free.fr> <441e$45a02246$d443bb3a$24795@news.speedlinq.nl> Message-ID: Stef Mientki kirjoitti: > In this exercise, I don't attempt to write "beautiful" Python code, > but the first thing is to write a simple "user-interface" for non-Pythians. > I understand that standardization about naming conventions is important, > but the purpose here is to serve the user, who has to write and > unerstand this, > therefore IORLW is in the domain always written in capitals, > spaces here makes it lot easier to compare the different actions, > in this domain we're used to 2 spaces etc. > > > thanks again for all your wonderfull help, > cheers, > Stef Mientki I can now understand the reason for the strange-looking function names etc. and think it's reasonable. The application domain is totally alien to me, though, so further explanations won't help me because a lack of the necessary electronic knowledge. Furthermore, as became evident from your web pages, your application is quite extensive which makes your task more difficult in formulating questions because things connected to other things are hard to extract for review. Anyway, happy hacking with Python. Cheers, Jussi From Roka100 at gmail.com Wed Jan 24 06:59:17 2007 From: Roka100 at gmail.com (Jia Lu) Date: 24 Jan 2007 03:59:17 -0800 Subject: Q: Why Python is bad for web from the point of URLs? In-Reply-To: <1169635844.254229.310460@a75g2000cwd.googlegroups.com> References: <1169635844.254229.310460@a75g2000cwd.googlegroups.com> Message-ID: <1169639956.972289.317210@j27g2000cwj.googlegroups.com> But you can do capsulation to them. On 1?24?, ??7:50, "techtonik" wrote: > A: Because you need three modules to parse, edit and reassemble query > string. urlparse, cgi and urllib From vpolukcht at gmail.com Thu Jan 18 05:58:32 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 18 Jan 2007 02:58:32 -0800 Subject: One more regular expressions question In-Reply-To: References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> Message-ID: <1169117912.193536.321260@a75g2000cwd.googlegroups.com> My pattern now is: (?P[^(]+)(?P\d+)\)\s+(?P\d+) And i expect to get: var1 = "Unassigned Number " var2 = "1" var3 = "32" I'm sure my regexp is incorrect, but can't understand where exactly. Regex.debug shows that even the first block is incorrect. Thanks in advance. On Jan 18, 1:15 pm, Roberto Bonvallet wrote: > Victor Polukcht wrote: > > My actual problem is i can't get how to include space, comma, slash.Post here what you have written already, so we can tell you what the > problem is. > > -- > Roberto Bonvallet From pavlovevidence at gmail.com Sun Jan 14 15:04:57 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 14 Jan 2007 12:04:57 -0800 Subject: Is it possible to get whole commandline include redirection.., etc In-Reply-To: <1168643505.949920.154470@a75g2000cwd.googlegroups.com> References: <1168643505.949920.154470@a75g2000cwd.googlegroups.com> Message-ID: <1168805096.858830.94180@v45g2000cwv.googlegroups.com> postindex at gmail.com wrote: > Can I get whole commandline not only argument list. > > 1. When I command like this > $ a.py > filename > 2. sys.argv is returns only argument list > ['a.py'] > > Is there a way to find out 'redirection' information. It's not possible to find the exact command line redirections. However, you can tell whether a standard I/O stream has been redirected or not (kind of) using isattr attribute. For instance, sys.stdin.isatty() returns 1 when it's not being redirected. It's not exact, though. It's possible to redirect to a device that is a tty, and sometimes standard I/O streams will not be ttys even without redirection, such as when run by a script with redirection. (It shouldn't be a problem, since the main use case is to check whether the program should run in interactive mode or not.) Carl Banks From george.sakkis at gmail.com Thu Jan 18 19:40:58 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Jan 2007 16:40:58 -0800 Subject: Iterator length References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> Message-ID: <1169167258.553202.190130@m58g2000cwm.googlegroups.com> bearophileHUGS at lycos.com wrote: > Often I need to tell the len of an iterator, this is a stupid example: > > >>> l = (i for i in xrange(100) if i&1) > > len isn't able to tell it: > > >>> len(l) > Traceback (most recent call last): > File "", line 1, in > TypeError: object of type 'generator' has no len() > > This is a bad solution, it may need too much memory, etc: > > >>> len(list(l)) > > This is a simple solution in a modern Python: > > >>> sum(1 for _ in l) > 50 > > This is a faster solution (and Psyco helps even more): > > def leniter(iterator): > """leniter(iterator): return the length of an iterator, > consuming it.""" > if hasattr(iterator, "__len__"): > return len(iterator) > nelements = 0 > for _ in iterator: > nelements += 1 > return nelements > > Is it a good idea to extend the functionalities of the built-in len > function to cover such situation too? > > Bye, > bearophile Is this a rhetorical question ? If not, try this: >>> x = (i for i in xrange(100) if i&1) >>> if leniter(x): print x.next() George From brochu121 at gmail.com Wed Jan 10 10:43:47 2007 From: brochu121 at gmail.com (david brochu jr) Date: Wed, 10 Jan 2007 10:43:47 -0500 Subject: Using Excel With Python Message-ID: <9583ed900701100743h2310ccc0jc82f64a64aa00df9@mail.gmail.com> Try using ExcelApp.Close(). This should kill the entire application (it might prompt for a Save). -------------- next part -------------- An HTML attachment was scrubbed... URL: From nmm1 at cus.cam.ac.uk Thu Jan 11 05:44:12 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 11 Jan 2007 10:44:12 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Message-ID: In article , robert writes: |> |> Most threads on this planet are not used for number crunching jobs, |> but for "organization of execution". That is true, and it is effectively what POSIX and Microsoft threads are suitable for. With reservations, even there. |> Things like MPI, IPC are just for the area of "small message, big job" |> - typically sci number crunching, where you collect the results "at |> the end of day". Its more a slow network technique. That is completely false. Most dedicated HPC systems use MPI for high levels of message passing over high-speed networks. |> > They use it for the communication, but don't expose it to the |> > programmer. It is therefore easy to put the processes on different |> > CPUs, and get the memory consistency right. |> |> Thus communicated data is "serialized" - not directly used as with |> threads or with custom shared memory techniques like POSH object |> sharing. It is not used as directly with threads as you might think. Even POSIX and Microsoft threads require synchronisation primitives, and threading models like OpenMP and BSP have explicit control. Also, MPI has asynchronous (non-blocking) communication. Regards, Nick Maclaren. From bruno.desthuilliers at websiteburo.com Wed Jan 10 04:42:09 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Wed, 10 Jan 2007 10:42:09 +0100 Subject: Establishing if an Object is Defined In-Reply-To: <1168420616.285450.306460@k58g2000hse.googlegroups.com> References: <1168420616.285450.306460@k58g2000hse.googlegroups.com> Message-ID: <45a4b4e6$0$298$426a34cc@news.free.fr> bg_ie at yahoo.com a ?crit : > Hi, > > The following code works - > > one = 1 > if one == 1: > ok = 1 > print ok > > but this does not, without exception - > > one = 2 Are you competing for the Most Misleading Name Award(tm) ?-) > if one == 1: > ok = 1 > print ok > > How do I establish before printing ok if it actually exists so as to > avoid this exception? The simplest way is to make sure the name will be defined whatever the value of the test: one = 42 # ... ok = (one == 1) print ok As a side note, if you want to check wether a name exists in the current namespace, you can use a try/except block: try: toto print "toto is defined" except NameError: print "toto is not defined" From nmm1 at cus.cam.ac.uk Fri Jan 12 04:29:19 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 12 Jan 2007 09:29:19 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: In article , "Hendrik van Rooyen" writes: |> |> I would have thought that this sort of thing was a natural consequence |> of rounding errors - if I round (or worse truncate) a binary, I can be off |> by at most one, with an expectation of a half of a least significant digit, |> while if I use hex digits, my expectation is around eight, and for decimal |> around five... |> |> So it would seem natural that errors would propagate |> faster on big base systems, AOTBE, but this may be |> a naive view.. Yes, indeed, and that is precisely why the "we must use binary" camp won out. The problem was that computers of the early 1970s were not quite powerful enough to run real applications with simulated floating-point arithmetic. I am one of the half-dozen people who did ANY actual tests on real numerical code, but there may have been some work since! Nowadays, it would be easy, and it would make quite a good PhD. The points to look at would be the base and the rounding rules (including IEEE rounding versus probabilistic versus last bit forced[*]). We know that the use or not of denormalised numbers and the exact details of true rounding make essentially no difference. In a world ruled by reason rather than spin, this investigation would have been done before claiming that decimal floating-point is an adequate replacement for binary for numerical work, but we don't live in such a world. No matter. Almost everyone in the area agrees that decimal floating-point isn't MUCH worse than binary, from a numerical point of view :-) [*] Assuming signed magnitude, calculate the answer truncated towards zero but keep track of whether it is exact. If not, force the last bit to 1. An old, cheap approximation to rounding. Regards, Nick Maclaren. From fuzzyman at gmail.com Tue Jan 2 07:41:52 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 Jan 2007 04:41:52 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167736083.756075.273450@s34g2000cwa.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <1167543262.361311.123700@v33g2000cwv.googlegroups.com> <1167736083.756075.273450@s34g2000cwa.googlegroups.com> Message-ID: <1167741711.955824.26410@v33g2000cwv.googlegroups.com> Ben Sizer wrote: [snip..] > I have no problem with something being configurable, but I do have a > problem with Windows users being forced to jump through unnecessary > hoops that Unix and MacOS users don't have to endure. And I think the > default should be to edit the PATH and allow you to explicitly disallow > this: changing from the current behaviour is the right thing to do > because the current behaviour is wrong, in terms of cross-platform > compatibility and usability. > I strongly agree with these sentiments. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -- > Ben Sizer From bj_666 at gmx.net Mon Jan 29 01:47:19 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 29 Jan 2007 07:47:19 +0100 Subject: decode overwrite variable? References: <21235$45bd8f83$d8a87c2a$18298@NEXICOM.NET> Message-ID: In <21235$45bd8f83$d8a87c2a$18298 at NEXICOM.NET>, Jammer wrote: > Will a failed decode overwrite the variable? > > message = message.decode('iso-8859-1') > or do I need to do > msg = message.decode('iso-8859-1') Why don't you just try? In [2]: a = u'\u2022' In [3]: a = a.decode('iso-8859-1') --------------------------------------------------------------------------- exceptions.UnicodeEncodeError Traceback (most recent call last) /home/marc/ UnicodeEncodeError: 'ascii' codec can't encode character u'\u2022' in position 0: ordinal not in range(128) In [4]: a Out[4]: u'\u2022' Ciao, Marc 'BlackJack' Rintsch From kuldjlevelet at gmail.com Thu Jan 18 06:58:22 2007 From: kuldjlevelet at gmail.com (0k-) Date: 18 Jan 2007 03:58:22 -0800 Subject: classes: need for an explanation Message-ID: <1169121502.779509.138890@m58g2000cwm.googlegroups.com> hello! i started to write a game in python in which i want to implement "dynamically attachable" attributes. my intention is to generalise this and moreover these attributes can be complex, so i'm creating classes to represent these attributes. but somehow i cannot instantiate these attribute classes well... here is the simple outline of my code: class Attr(object): name = "" value = "" def __init__(self, name, value): self.name = name self.value = value # this is just an example, in the real game attrs. are more complex! class TxtAttr(Attr): name = "text" def __init__(self, value): self.value = value class Thing(object): props = {} def __init__(self): self.props["text"] = TxtAttr("something important") t1 = Thing() t2 = Thing() t2.props["text"].value = "another string" print "t1: %s\nt2: %s" % (t1.props["text"].value, t2.props["text"].value) the above code outputs: t1: another string t2: another string so the problem i cannot get through is that both t1 and t2 have the same attr class instance. could somebody please explain me why? :) From nszabolcs at gmail.com Mon Jan 29 18:21:52 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 15:21:52 -0800 Subject: python 2.3 module ref In-Reply-To: <6178735.qJi6sMvOM0@teancum> References: <6178735.qJi6sMvOM0@teancum> Message-ID: <1170112912.468882.251250@a34g2000cwb.googlegroups.com> > any pointers to a 2.3 module ref? also look at: http://rgruet.free.fr/PQR2.3.html#OtherModules when coding for different python versions i can reccommend this quick ref: http://rgruet.free.fr/ (every language feature is colorcoded according to the version when it was included) From martin at v.loewis.de Wed Jan 24 16:51:51 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 24 Jan 2007 22:51:51 +0100 Subject: raise UnicodeError, "label too long" In-Reply-To: <1169675004.099912.79520@v33g2000cwv.googlegroups.com> References: <1169672223.231030.262610@l53g2000cwa.googlegroups.com> <1169675004.099912.79520@v33g2000cwv.googlegroups.com> Message-ID: <45B7D4F7.9020308@v.loewis.de> Flavio schrieb: > What I am doing is very simple: > > I fetch an url (html page) parse it using BeautifulSoup, extract the > links and try to open each of the links, repeating the cycle. > > Beautiful soup converts the html to unicode. That's why when I try to > open the links extracted from the page I get this error. > > This is bad, since some links do contain strings with non-ascii > characters. Please try answering the exact question that Marc asked: what is an example for unicode string that triggers the exception? Regards, Martin From tactics40 at gmail.com Mon Jan 22 19:21:51 2007 From: tactics40 at gmail.com (tac-tics) Date: 22 Jan 2007 16:21:51 -0800 Subject: arrow keys don't work In-Reply-To: References: <1169506381.452422.179070@11g2000cwr.googlegroups.com> Message-ID: <1169511711.594390.167630@11g2000cwr.googlegroups.com> > Have you changed your terminal (either the program itself or its config) > so that it is no longer sending the correct codes? I doubt this is the case. Everything works for the bash shell and common lisp. It's just python acting up. > When you hit the arrow key, what happens? Do you just get nothing at all, > or do you get control characters appearing? e.g. ^Z or similar. udlr yields ^[[A^[[B^[[C^[[D in the interactive python interpreter, but like I said, works like it should outside the Python interpreter. From gagsl-py at yahoo.com.ar Thu Jan 4 22:47:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 00:47:43 -0300 Subject: clarification on open file modes In-Reply-To: References: Message-ID: <7.0.1.0.0.20070105004004.05b3bb08@yahoo.com.ar> At Thursday 4/1/2007 23:46, tubby wrote: >I understand that doing the following on Windows to a binary file (a >jpeg or exe files for example) can cause file corruption, is that correct? > >fp = open(file_name, 'r') >fp.close() > >How can a simple open in read mode corrupt data??? You can't corrupt *that* file if you only open it. But if you *read* it and process the input data, you'll get some garbage. And if you write such data (to the same file or another one), it will be corrupted. Using "rb" or "wb" for binary files won't do any harm on systems where it doesn't matter, and it's the right way on systems where it does. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bdesth.quelquechose at free.quelquepart.fr Sat Jan 6 07:16:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Jan 2007 13:16:46 +0100 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1168041434.385029.55870@38g2000cwa.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1168041434.385029.55870@38g2000cwa.googlegroups.com> Message-ID: <459f8cf8$0$290$426a74cc@news.free.fr> Patrick Down a ?crit : > jeremito wrote: > >>I am writing a class that is intended to be subclassed. What is the >>proper way to indicate that a sub class must override a method? >> (snip) > Decorators to the rescue? (snip convoluted code) What a strange idea... From will at willmcgugan.com Wed Jan 17 07:50:33 2007 From: will at willmcgugan.com (Will McGugan) Date: 17 Jan 2007 04:50:33 -0800 Subject: generate tuples from sequence In-Reply-To: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: <1169038232.198619.139900@v45g2000cwv.googlegroups.com> Will McGugan wrote: > Hi, > > I'd like a generator that takes a sequence and yields tuples containing > n items of the sqeuence, but ignoring the 'odd' items. For example Forgot to add, for my purposes I will always have a sequence with a multiple of n items. Will From nagle at animats.com Fri Jan 5 14:19:06 2007 From: nagle at animats.com (John Nagle) Date: Fri, 05 Jan 2007 19:19:06 GMT Subject: MySQLdb windows binaries for Python 2.5?? Yes, but from a World of Warcraft guild. In-Reply-To: <1168019043.523288.50770@38g2000cwa.googlegroups.com> References: <1162408100.985370.148650@m7g2000cwm.googlegroups.com> <1163238145.257490.144410@b28g2000cwb.googlegroups.com> <1166144355.616642.127080@n67g2000cwd.googlegroups.com> <1168019043.523288.50770@38g2000cwa.googlegroups.com> Message-ID: msj at infoserv.dk wrote: > Anyone have a binary they want to share? > > /Martin > Somebody has an untested one. See http://sourceforge.net/forum/forum.php?thread_id=1571110&forum_id=70461 You have to ask for a copy; they don't want to distribute it and be blamed for problems. There hasn't been a new release of MySQLdb since April 2006, and there's no official support for either Python 2.5 or Windows. Realistically, you have to run Python 2.4 or earlier if you need database access. We dropped back to Python 2.4, with good results. John Nagle From nszabolcs at gmail.com Tue Jan 30 10:08:34 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 30 Jan 2007 07:08:34 -0800 Subject: data design In-Reply-To: <45bf5763$0$22792$426a34cc@news.free.fr> References: <45bf5763$0$22792$426a34cc@news.free.fr> Message-ID: <1170169714.066396.227860@s48g2000cws.googlegroups.com> > The lazy way to do this: have modules that initialize bunches of > objects, attributes holding the data: the object is somehow the row of > the "table", attribute names being the column. This is the way I > proceeded up to now. > Data input this way are almost "configuration data", with 2 big > drawbacks: > - Only a python programmer can fix the file: this cant be called a > configuration file. > - Even for the author, these data aint easy to maintain. > > I feel pretty much ready to change this: > - make these data true text data, easier to read and fix. > - write the module that will make python objects out of these data: > the extra cost should yield ease of use. > > 2 questions arise: > - which kind of text data? > - csv: ok for simple attributes, not easy for lists or complex > data. > - xml: the form wont be easier to read than python code, > but an xml editor could be used, and a formal description > of what is expected can be used. > - how can I make the data-to-object transformation both easy, and able > to spot errors in text data? > > Last, but not least: is there a python lib implementing at least part > of this dream? there is a csv parser and multiple xml parsers in python (eg xml.etree) also there is a ConfigParser module (able to parse .ini like config files) i personally like the python module as config file the most eg if you need a bunch of key-value pairs or lists of data: * python's syntax is pretty nice (dict, tuples and lists or just key=value) * xml is absolutely out of question * csv is very limited * .ini like config file for more complex stuff is not bad but then you can use .py as well. From bruno.desthuilliers at gmail.com Wed Jan 17 07:56:14 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 17 Jan 2007 04:56:14 -0800 Subject: 2.3-2.5 what improved? In-Reply-To: References: Message-ID: <1169038574.260669.194760@s34g2000cwa.googlegroups.com> Robin Becker a ?crit : > A large cgi based web Python-2.3 application needs to be speed improved. > experiments show the following under reasonable testing (these are 2 second > reportlab pdf productions) > > 1) 2.3 --> 2.5 improvement small 1-2% > 2) cgi --> fcgi improvement medium 10-12% > > I sort of remember claims being made about 2.5 being 10% faster than 2.4/2.3 etc > etc. Can anyone say where the speedups were? AFAIK, most of the speedup comes from optimization of the builtin dict type, which is the central data structure in Python. But anyway, as Robert pointed out, using CGI means lauching a new Python process for each and every HTTP request. > Presumably we have a lot of old > cruft that could be improved in some way eg moving loops into comprehensions, > using iterator methods etc. Are those sort of things what we should look at? Consider profiling your code before doing anything else - unless you're planning on wasting your time. From gagsl-py at yahoo.com.ar Tue Jan 2 11:25:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Jan 2007 13:25:55 -0300 Subject: trees, iterations and adding leaves In-Reply-To: References: Message-ID: <7.0.1.0.0.20070102125732.05bfb898@yahoo.com.ar> At Sunday 31/12/2006 14:25, vertigo wrote: >I use nltk package - but it should not matter here. Yes, it does. The framework should provide some form of tree traversal. >So i wanted to 'travel thru my tree' to last node which should be changed: > >>> tree6 = Tree('main', ['sub1', 'sub2']) > >>> subtree = tree6[0] > >>> subtree >'sub1' > >>> subtree = Tree('newsub',[]) > >>> subtree >('newsub': ) > >>> tree6 >('main': 'sub1' 'sub2') >The problem is that subtree is some kind of a new variable (not pointer) >so changing it i will not alter tree6. This, yes, is a general Python question. When you bind something to the name "subtree", it doesn't matter what were "subtree" pointing to before. Read http://effbot.org/zone/python-objects.htm >How to alter tree6 while >'travelling along it's nodes', >without messy referencing as tree6[0][1][0][1][1][1][0].......... ? Without any further knowledge of the Tree objects, you could do something like this: def traverse_tree(tree, *ids): result = tree while ids: key = ids.pop(0) tree = tree[key] return tree and say: traverse_tree(tree6, 0, 1, 0, 1, 1, 1, 0) or traverse_tree(tree6, *[0,1,0,1,1,1,0]) or traverse_tree(tree6, *[0,1,0,1,1])[0] = another_object -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From wolf_tracks at invalid.com Sun Jan 7 14:20:35 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 07 Jan 2007 11:20:35 -0800 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: <1168194009.220437.286210@q40g2000cwq.googlegroups.com> References: <1168194009.220437.286210@q40g2000cwq.googlegroups.com> Message-ID: Gabriel Genellina wrote: > On 7 ene, 13:22, "W. Watson" wrote: > >>>>> https://sourceforge.net/projects/pywin32/ > >> As I understand it, there are two files I'm after: 1. python interpreter, >> and 2. a python editor. It's #2 that I'm having trouble downloading. The >> link is broken. > > The above link should work. Follow the instructions in a previous post. > Note that in the last step, you have to choose a mirror for > downloading; that mirrow might be down or out-of-sync so you might get > an error there. Choose another mirrorr... > > Note that you dont *need* PythonWin in order to use Python on Windows. > The standard Python distribution works fine. Even includes a Python > editor (IDLE) but you can use whichever editor you like to write your > code (even Notepad...) > We seem to be looping. I have the Python interpreter. I would like the pythonwin editor. The download link doesn't work on SourceForge. Where can I get it? If not there, where? If it can't be obtained, then I'll go to the default editor built into python-2.5.msi. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet ""I do not fear death. I had been dead for billions and billions of years before I was born, and had not suffered the slightest inconvenience from it." -- Mark Twain (a nod to evolution) -- Web Page: From ptmcg at austin.rr.com Mon Jan 29 00:20:47 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 28 Jan 2007 21:20:47 -0800 Subject: log parser design question In-Reply-To: References: Message-ID: <1170048047.660118.164850@l53g2000cwa.googlegroups.com> On Jan 27, 10:43 pm, avidfan wrote: > I need to parse a log file using python and I need some advice/wisdom > on the best way to go about it: > > The log file entries will consist of something like this: > > ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled > locked working.lock > status running > status complete > > ID=9009 IID=87234785 execute wait - 01.21.2007 status wait > waiting to lock > status wait > waiting on ID=8688 > > and so on... > For the parsing of this data, here is a pyparsing approach. Once parse, the pyparsing ParseResults data structures can be massaged into a queryable list. See the examples at the end for accessing the individual parsed fields. -- Paul data = """ ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled locked working.lock status running status complete ID=9009 IID=87234785 execute wait - 01.21.2007 status wait waiting to lock status wait waiting on ID=8688 """ from pyparsing import * integer=Word(nums) idref = "ID=" + integer.setResultsName("id") iidref = "IID=" + integer.setResultsName("iid") date = Regex(r"\d\d\.\d\d\.\d{4}") logLabel = Group("execute" + oneOf("begin wait")) logStatus = Group("status" + oneOf("enabled wait")) lockQual = Group("locked" + Word(alphanums+".")) waitingOnQual = Group("waiting on" + idref) statusQual = Group("status" + oneOf("running complete wait")) waitingToLockQual = Group(Literal("waiting to lock")) statusQualifier = statusQual | waitingOnQual | waitingToLockQual | lockQual logEntry = idref + iidref + logLabel.setResultsName("logtype") + "-" \ + date + logStatus.setResultsName("status") \ + ZeroOrMore(statusQualifier).setResultsName("quals") for tokens in logEntry.searchString(data): print tokens print tokens.dump() print tokens.id print tokens.iid print tokens.status print tokens.quals print prints: ['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', '01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], ['status', 'running'], ['status', 'complete']] ['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', '01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], ['status', 'running'], ['status', 'complete']] - id: 8688 - iid: 98889998 - logtype: ['execute', 'begin'] - quals: [['locked', 'working.lock'], ['status', 'running'], ['status', 'complete']] - status: ['status', 'enabled'] 8688 98889998 ['status', 'enabled'] [['locked', 'working.lock'], ['status', 'running'], ['status', 'complete']] ['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', '01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', 'wait'], ['waiting on', 'ID=', '8688']] ['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', '01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', 'wait'], ['waiting on', 'ID=', '8688']] - id: 9009 - iid: 87234785 - logtype: ['execute', 'wait'] - quals: [['waiting to lock'], ['status', 'wait'], ['waiting on', 'ID=', '8688']] - status: ['status', 'wait'] 9009 87234785 ['status', 'wait'] [['waiting to lock'], ['status', 'wait'], ['waiting on', 'ID=', '8688']] From pavlovevidence at gmail.com Wed Jan 10 16:37:38 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 10 Jan 2007 13:37:38 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> <1168048620.409190.85870@v33g2000cwv.googlegroups.com> <1168130960.670978.111850@s34g2000cwa.googlegroups.com> <1168209637.965967.23790@s34g2000cwa.googlegroups.com> <1168443236.166170.265770@77g2000hsv.googlegroups.com> Message-ID: <1168465058.250744.224210@p59g2000hsd.googlegroups.com> Martin Miller wrote: > Carl Banks wrote: > > Because the usage deceptively suggests that it defines a name in the > > local namespace. Failing may be too strong a word, but I've come to > > expect a consistent behavior w.r.t. namespaces, which this violates, so > > I think it qualifies as a failure. > > I don't see how the usage deceptively suggests this at all. In this > case -- your sample code for fun() and fun2() -- all were simply > Pin('aap'). Since no additional namespace argument was supplied, Exactly. In normal Python, to create a global variable in a local context, you must specify the namespace. Normally, variables are always created in the most local context in Python, only. So now you come in with this this spiffy "look, it creates the variable for you!" class, but it completely goes against normal Python behavior by creating the variable in the global namespace even when in a local context. I think that is deceptive and confusing behvaior for something that claims to create variables for you. > > I think programmatically creating variables is fine; I just recommend > > you not use sys._getframe, nor the automagical namespace self-insertion > > class, to do it. > > You've explained some of your worries about sys._getframe. It would > be interesting to hear specifically what it is you don't like about > the idea of namespace self-insertion -- mainly because of the local > namespace limitation? The local namespace thing has nothing to do with it; I would still be very much against this even if it did work for locals. My main problem with this is it saddles the class with behavior that interferes with using it as a normal class. For instance, if you wanted to do something like this: def fun(pin_name): p = Pin(pin_name) do_something_with(p) At least it looks like it works! But it works only with the undesriable side-effect of creating a global variable of some unknown name. It could be no big deal, or it could be a gaping security hole. (Yes, I know you can just pass in an empty namespace. Thanks for that. Nice to know it's at least possible to jump though hoops just to regain normal usage of the class.) The problem here, see, is the hubris of the author in thinking that he can anticipate all possble uses of a class (or at least that he can presume that no user will ever want to use the class in a normal way). Of course, no author can ever anticipate all possible uses of their code, and it's inevitable that users will want to use code in a way the author didn't intend. Most often it's not any hubris on the author's part, but mere ignorance, and is forgivable. But when the author deliberately does extra work to cut the user off from normal usage, then ignorance is no longer a defense: the normal way was considered, and the author sanctimoniously decided on the user's behalf that the user would never want or need normal usage of the class. That is a lot less forgivable. If you want to respect the user, your class is going to have to change. 1. Reprogram the class so that, BY DEFAULT, it works normally, and only inserts itself into a namespace when specifically requested. Then, at least, users can ignore the autoinsertion silliness if they don't want to use it. Plus, it affords better documentation to readers who don't know aren't in on the secret of this Pin class (seeing an "autoinsert=True" passed to the constructor is a clue something's going on). 2. (Better, IMO) Write a well-named function to do it. E.g.: def create_global_Pin_variable(name,namespace=None): if namespace is None: namespace = sys._getframe(1).f_globals namespace[name] = Pin(name) Leave it out of the class. Classes are better off when they only worry about what's going on in their own namespaces. Leave dealing with external namespaces to an external function. The function's name documents the fact that: you're creating a variable, it's global, it's a Pin. You've gotten surprise down to a small as you're going to get it. Carl Banks From laurent.pointal at limsi.fr Wed Jan 10 08:49:33 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 10 Jan 2007 14:49:33 +0100 Subject: maximum number of threads In-Reply-To: References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: Paul Sijben a ?crit : > Gabriel Genellina wrote: >> Simply you can't, as you can't have 10000 open files at once. Computer >> resources are not infinite. > > sure but *how* fast they run out is the issue here > >> Do you really need so many threads? > > I might be able to do with a few less but I still need many. > > I have done a quick test. > > on WinXP I can create 1030 threads > on Fedora Core 6 I can only create 301 (both python2.4 and 2.5) > > now the 301 is rather low I'd say. This is a system configurable limit (up to a maximum). See ulimit man pages. test ulimit -a to see what are the current limits, and try with ulimit -u 2000 to modify the maximum number of user process (AFAIK each thread use a process entry on Linux) > > Paul > From walter at livinglogic.de Wed Jan 31 11:47:39 2007 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 31 Jan 2007 17:47:39 +0100 Subject: Unicode error handler In-Reply-To: <1170217309.125918.214060@v33g2000cwv.googlegroups.com> References: <1170217309.125918.214060@v33g2000cwv.googlegroups.com> Message-ID: <45C0C82B.5080507@livinglogic.de> Hieu.D.Hoang at gmail.com wrote: > On Jan 30, 11:28 pm, Walter D?rwald wrote: > >> codecs.register_error("transliterate", transliterate) >> >> Walter > > Really, really slick solution. > Though, why was it [:1], not [0]? ;-) No particular reason, unicodedata.normalize("NFD", ...) should never return an empty string. > And one more thing: >> def transliterate(exc): >> if not isinstance(exc, UnicodeEncodeError): >> raise TypeError("don'ty know how to handle %r" % r) > I don't understand what %r and r are and where they are from. The man > 3 printf page doesn't have %r formatting. %r means format the repr() result, and r was supposed to be exc. ;) Servus, Walter From paddy3118 at netscape.net Wed Jan 24 16:53:19 2007 From: paddy3118 at netscape.net (Paddy) Date: 24 Jan 2007 13:53:19 -0800 Subject: The reliability of python threads In-Reply-To: References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> Message-ID: <1169675599.502726.5070@a34g2000cwb.googlegroups.com> On Jan 24, 6:43 pm, "Carl J. Van Arsdall" wrote: > Chris Mellon wrote: > > On 24 Jan 2007 18:21:38 GMT, Nick Maclaren wrote: > > >> [snip] > > > I'm aware of the issues with the POSIX threading model. I still stand > > by my statement - bringing up the problems with the provability of > > correctness in the POSIX model amounts to FUD in a discussion of > > actual problems with actual code. > > > Logic and programming errors in user code are far more likely to be > > the cause of random errors in a threaded program than theoretical > > (I've never come across a case in practice) issues with the POSIX > > standard. > Yea, typically I would think that. The problem I am seeing is > incredibly intermittent. Like a simple pyro server that gives me a > problem maybe every three or four months. Just something funky will > happen to the state of the whole thing, some bad data, i'm having an > issue tracking it down and some more experienced programmers mentioned > that its most likely a race condition. THe thing is, I'm really not > doing anything too crazy, so i'm having difficult tracking it down. I > had heard in the past that there may be issues with threads, so I > thought to investigate this side of things. > > It still proves difficult, but reassurance of the threading model helps > me focus my efforts. > > -carl Three to four months before `strange errors`? I'd spend some time correlating logs; not just for your program, but for everything running on the server. Then I'd expect to cut my losses and arrange to safely re-start the program every TWO months. (I'd arrange the re-start after collecting logs but before their analysis. Life is too short). - Paddy. From robert.kern at gmail.com Thu Jan 11 18:27:22 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 Jan 2007 17:27:22 -0600 Subject: Intellectual Property Talk at PyCon In-Reply-To: References: Message-ID: VanL wrote: > - What it means to incorporate GPL'd modules into your own code I don't have any suggestions for other material to cover, but I'd like to express my interest in keeping this in your agenda. This is an issue that crops up again and again with ill-informed opinions all around. Of course, it would be nice if what you say agrees with my opinions on the subject, but I'll let you slide if you at least say something sensible. ;-) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From paul.sijben at xs4all.nl Wed Jan 10 06:41:38 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 12:41:38 +0100 Subject: maximum number of threads In-Reply-To: References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: <45A4D0F2.40001@xs4all.nl> Gabriel Genellina wrote: > > Simply you can't, as you can't have 10000 open files at once. Computer > resources are not infinite. sure but *how* fast they run out is the issue here > Do you really need so many threads? I might be able to do with a few less but I still need many. I have done a quick test. on WinXP I can create 1030 threads on Fedora Core 6 I can only create 301 (both python2.4 and 2.5) now the 301 is rather low I'd say. Paul From gagsl-py at yahoo.com.ar Fri Jan 19 11:05:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 13:05:46 -0300 Subject: Why do I have to call del explicitly for com objects? References: <1169210578.544593.310100@v45g2000cwv.googlegroups.com> Message-ID: escribi? en el mensaje news:1169210578.544593.310100 at v45g2000cwv.googlegroups.com... > I'm creating objects in my python script belonging to a COM object > which I dispatch using win32com.client.DispatchEx. Hence, dllhost.dll > is the concerned process. The problem is that the objects destructor > within the com object is not called if the object lives past a certain > number of seconds. For example, this function will not call the > destructor concerned with obj unless the sleep is commented out. > > def fnction: > obj = comobj.createACertainObject() > obj.doStuff() > sleep(10) > obj.doMoreStuff() > #del obj I don't understand the case. del does not invoke a destructor, just decrements the object's reference count. When the rc reaches zero, the object is a candidate for GC. That is, "some time in the future", the GC would destroy it (unless it's part of a circular reference chain...) So, *inside* your function, there is a reference held by the local variable obj. It is decremented automatically when you exit the function (and obj gets out of scope) or if you explicitely use del. You can use sys.getrefcount() to see how many references an object has. (The output is +1 because getrefcount() has a temporary reference to the object too). py> x="Hello World" py> sys.getrefcount(x) 2 See how many references your obj have. After calling doStuff or doMoreStuff, you can have more references if those functions store `self` somewhere, or pass it to another method that does so. > It seems to me that the GC forgets about obj after a certain amount of > time. I can force the destructor to be called using del obj at the end > of my function, but why do I have to call this explicitly? If del obj works at the end, exiting the function should work too. Both ways you decrement the rc. There is something *more* in here. -- Gabriel Genellina From nmm1 at cus.cam.ac.uk Thu Jan 11 18:47:17 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 11 Jan 2007 23:47:17 GMT Subject: Rational Numbers References: Message-ID: In article , Facundo Batista writes: |> Noud Aldenhoven wrote: |> |> > When I was programming in a mathematical project I began to wonder if python |> > supports rational numbers[1]. In a language like magma[2] it's not such a |> > problem. Does python supports something simular? |> |> Python does not have rational numbers. |> |> There's a (rejected) PEP about this, PEP-239: |> |> http://www.python.org/dev/peps/pep-0239/ |> |> Maybe you also want to read the section "Why not rational?" of |> PEP-327... |> |> http://www.python.org/dev/peps/pep-0327/#why-not-rational Oh, God. Decimal delusions again :-( There are good arguments for not having a rational type, but the idea that decimal floating-point is in any way a replacement is cuckoo. The desirable properties that rationals and decimal arithmetic provide are both genuine and are almost entirely different .... There are also perfectly good representations that don't have the performance implications mentioned: fixed and floating slash arithmetic. They are mathematically quite interesting, and have some desirable properties not shared by any floating-point format: e.g. if the result is theoretically a rational with small numerator and denominator, then they are very likely to return it. I implemented fixed slash once, and it is very easy to do - all it needs is a GCD routine - like rational, it would be straightforward to add to Python as an extension type. Regards, Nick Maclaren. From jstroud at mbi.ucla.edu Sat Jan 20 18:59:41 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 20 Jan 2007 15:59:41 -0800 Subject: regexp qns In-Reply-To: <1169269793.713444.152110@a75g2000cwd.googlegroups.com> References: <1169268024.164643.71320@l53g2000cwa.googlegroups.com> <1169269793.713444.152110@a75g2000cwd.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > James Stroud wrote: > >>eight02645999 at yahoo.com wrote: >> >>>hi >>>suppose i have a string like >>> >>>test1?test2t-test3*test4*test5$test6#test7*test8 >>> >>>how can i construct the regexp to get test3*test4*test5 and >>>test7*test8, ie, i want to match * and the words before and after? >>>thanks >>> >> >> >>py> import re >>py> s = 'test1?test2t-test3*test4*test5$test6#test7*test8' >>py> r = re.compile(r'(test\d(?:\*test\d)+)') >>py> r.findall(s) >>['test3*test4*test5', 'test7*test8'] >> >>James > > > thanks ! > I check the regexp doc it says: > """ > (?:...) > A non-grouping version of regular parentheses. Matches whatever > regular expression is inside the parentheses, but the substring matched > by the group cannot be retrieved after performing a match or referenced > later in the pattern. > """ > but i could not understand this : r'(test\d(?:\*test\d)+)'. which > parenthesis is it referring to? Sorry, could you explain the solution ? > thanks > The outer parentheses are the grouping operator. These are saved and accessible from a match object via group() or groups() methods. The "\d" part matches a single digit 0-1. The (?:....) construct is used to make a non-grouping operator that is not itself remembered for access through the group() or groups() methods. The expression can also reference earlier groups, but not groups specified with the non-grouping operator. You may want to note that this is the most specific regular expression that would match your given example. James From paddy3118 at netscape.net Sat Jan 6 12:07:38 2007 From: paddy3118 at netscape.net (Paddy) Date: 6 Jan 2007 09:07:38 -0800 Subject: Python re expr from Perl to Python In-Reply-To: References: Message-ID: <1168103258.602286.146100@42g2000cwt.googlegroups.com> Michael M. wrote: > In Perl, it was: > > > ## Example: "Abc | def | ghi | jkl" > ## -> "Abc ghi jkl" > ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st > pipe). > $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; > > ## -- remove [ and ] in text > $na =~ s/\[//g; > $na =~ s/\]//g; > # print "DEB: \"$na\"\n"; > > > # input string > na="Abc | def | ghi | jkl [gugu]" > # output > na="Abc ghi jkl gugu" > > > How is it done in Python? Here is how to do it without regexps in python. The first and last line below are all that are needed. The others show intermediate expressions that lead to the result. >>> from itertools import groupby >>> na="Abc | def | ghi | jkl [gugu]" >>> [(g[0], ''.join(g[1])) for g in groupby(na, lambda c: c not in ' \t|[]')] [(True, 'Abc'), (False, ' | '), (True, 'def'), (False, ' | '), (True, 'ghi'), (False, ' | '), (True, 'jkl'), (False, ' ['), (True, 'gugu'), (False, ']')] >>> [''.join(g[1]) for g in groupby(na, lambda c: c not in ' \t|[]') if g[0]] ['Abc', 'def', 'ghi', 'jkl', 'gugu'] >>> ' '.join(''.join(g[1]) for g in groupby(na, lambda c: c not in ' \t|[]') if g[0]) 'Abc def ghi jkl gugu' >>> - Paddy. From skip at pobox.com Wed Jan 24 16:14:36 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 Jan 2007 15:14:36 -0600 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <17847.52284.446369.999461@montanaro.dyndns.org> John> Python is the only major open source project I've encountered John> where there's so much hostility to bug reports. You're misinterpreting lack of time (or itches that need scratching by the people willing to do the work) for hostility. Lest you think that there is no activity on bugs, scan the python-checkins mailing list archive: http://mail.python.org/pipermail/python-checkins/ Grepping through the January mbox archive I see 96 different bug ids mentioned in the checkins. For December I see 116 different ids. I could go back farther, but I'll let you do that. Skip From tomerfiliba at gmail.com Thu Jan 25 06:42:54 2007 From: tomerfiliba at gmail.com (gangesmaster) Date: 25 Jan 2007 03:42:54 -0800 Subject: free variables /cell objects question In-Reply-To: References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> Message-ID: <1169725374.504546.153890@v33g2000cwv.googlegroups.com> no, it has nothing to do with "i" being global. >>> tuple(lambda: i for i in range(10))[0]() 9 >>> tuple(lambda: i for i in range(10))[1]() 9 what i see as a bug is this code not working as expected: >>> def make_foos(names): ... funcs = [] ... for n in names: ... def foo(): ... print "my name is", n ... funcs.append(foo) ... return funcs ... >>> foos = make_foos(["hello", "world", "spam", "bacon"]) >>> foos[0]() my name is bacon >>> foos[1]() my name is bacon >>> foos[2]() my name is bacon >>> i have to create yet another closure, make_foo, so that the name is correctly bound to the object, rather than the frame's slot: >>> def make_foo(name): ... def foo(): ... print "my name is", name ... return foo ... >>> def make_foos(names): ... return [make_foo(n) for n in names] ... >>> foos = make_foos(["hello", "world", "spam", "bacon"]) >>> foos[0]() my name is hello >>> foos[1]() my name is world >>> foos[2]() my name is spam -tomer On Jan 24, 2:46 am, "Terry Reedy" wrote: > "gangesmaster" wrote in messagenews:1169563580.634000.122540 at v45g2000cwv.googlegroups.com... > | so this is why [lambda: i for i in range(10)] will always return 9. > > No, it returns a list of 10 identical functions which each return the > current (when executed) global (module) variable i. Except for names, > 'lambda:i' abbreviates 'def f(): return i'. > > >>> a=[lambda: i for i in range(10)] > >>> i=42 > >>> for j in range(10): print a[j]()42 > 42 > 42 > 42 > 42 > 42 > 42 > 42 > 42 > 42 > > >>> for i in range(10): print a[i]()0 > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > > >>> del i > >>> for j in range(10): print a[j]()Traceback (most recent call last): > File "", line 1, in -toplevel- > for j in range(10): print a[j]() > File "", line 1, in > a=[lambda: i for i in range(10)] > NameError: global name 'i' is not defined > > | imho that's a bug, not a feature. > > The developers now think it a mistake to let the list comp variable 'leak' > into the global scope. It leads to the sort of confusion that you > repeated. In Py3, the leak will be plugged, so one will get an exception, > as in the last example, unless i (or whatever) is defined outside the list > comp. > > Terry Jan Reedy From wolf_tracks at invalid.com Sat Jan 6 02:54:14 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 06 Jan 2007 07:54:14 GMT Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: Laszlo Nagy wrote: > W. Watson wrote: >> What do I download to use Python with MX XP Pro on an ASUS 4 year old >> motherboard? I would guess a good book source for starters would be >> the O'Reilly book. >> > You mean Microsoft XP Pro? > > For a beginner, the motherboard does not really matter. First of all, > you should download Python itself: > > http://www.python.org/download/ > > or more probably: > > http://www.python.org/ftp/python/2.5/python-2.5.msi > > Then you should download a good editor. There are many, listed here: > http://wiki.python.org/moin/PythonEditors > Under Windows, for a beginner, I would recommend pythonwin, but you can > decide. > > Finally, you can start practicing. A book is always good. You can read > online tutorials too: > > http://docs.python.org/tut/ > http://www.awaretek.com/tutorials.html > > > Regards, > > Laszlo > Many thanks. I've been impressed lately what one finds in Wikipedia. The first such occurrence was when I find all the release dates for a photo software package that I use. Not even the mfger had that! Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet ""I do not fear death. I had been dead for billions and billions of years before I was born, and had not suffered the slightest inconvenience from it." -- Mark Twain (a nod to evolution) -- Web Page: From paul.rudin at ntlworld.com Sun Jan 14 01:06:59 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Sun, 14 Jan 2007 06:06:59 +0000 Subject: mod_python and Content-Type References: <8764bbb6jt.fsf@rudin.co.uk> <1168740637.544535.113490@38g2000cwa.googlegroups.com> Message-ID: <87wt3q9m64.fsf@rudin.co.uk> "Graham Dumpleton" writes: > All headers which come from the client are available through the > 'headers_in' > attribute of the request object. Eg. > > def handler(req): > ct = req.headers_in.get('Content-Type') > ... Thanks - it's even mentioned in the mod_python manual. Don't know how I missed it :( From hat at se-126.se.wtb.tue.nl Wed Jan 17 07:02:55 2007 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 17 Jan 2007 13:02:55 +0100 Subject: Distributed computation of jobs (was: Parallel Python) References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: On 2007-01-12, robert wrote: >> >> [1] http://www.python.org/pypi/parallel > > I'd be interested in an overview. > For ease of use a major criterion for me would be a pure python > solution, which also does the job of starting and controlling the > other process(es) automatically right (by default) on common > platforms. Let me add a few cents to the discussion with this announcement: About three years ago, I wrote two Python modules, one called 'exec_proxy', which uses ssh to run another exec_proxy instance at a remote machine, thus providing ligh-weight transparent access to a machine across a network. The idea behind this module was/is that by just using ssh you have network transparency, much more light weight than most other distributed modules where you have to start deamons at all machines. Recently, the 'rthread' module was announced which takes the same approach (it seems from the announcement). I have not compared both modules with each other. The more interesting Python module called 'batchlib' lies on top of the former (or any other module that provides transparency across the network). It handles distribution of computation jobs in the form of a 'start-computation' and 'get-results' pair of functions. That is, you give it a set of machines it may use, you say to the entry-point, compute for me this-and-this function with this-and-this parameters, and batchlib does the rest. (that is, it finds a free machine, copies the parameters over the network, runs the job, the result is transported back, and you can get the result of a computation by using the same (uniq) identification given by you when the job was given to batchlib.) We used it as computation backend for optimization problems, but since 'computation job' may mean anything, the module should be very generically applicable. Compared to most other parallel/distributed modules, I think that the other modules more-or-less compare with exec_proxy (that is, they stop with transparent network access), where exec_proxy was designed to have minimal impact on required infra structure (ie just ssh or rsh which is generally already available) and thus without many of the features available from the other modules. Batchlib starts where exec_proxy ends, namely lifting network primitives to the level of providing a simple way of doing distributed computations (in the case of exec_proxy, without adding network infra structure such as deamons). Until now, both modules were used in-house, and it was not clear what we wanted to do further with the software. Recently, we have decided that we have no further use for this software (we think we want to move into a different direction), clearing the way to release this software to the community. You can get the software from my home page http://seweb.se.wtb.tue.nl/~hat Both packages can be downloaded, and include documentation and an example. The bad news is that I will not be able to do further development of these modules. The code is 'end-of-life' for us. Maybe you find the software useful, Albert From facundo at taniquetil.com.ar Thu Jan 25 13:09:29 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 25 Jan 2007 18:09:29 +0000 (UTC) Subject: Email attachments References: Message-ID: Steve Holden wrote: > I'm having some trouble getting attachments right for all recipients, > and it seems like Apple's mail.app is the pickiest client at the moment. > It doesn't handle attachments that both Thunderbird and Outlook find > perfectly acceptable. The following code works ok with Thunderbird and mail.app (at least with all the mail I usually sent). A friend of mine reports that he (with mail.app can see that he has an attachment, open it, etc.) ----------------------------------- import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders class MailSender: '''Envia un mail con archivos attached.''' def __init__(self, server, remitente, to): self.server = server self.remitente = remitente self.to = to assert type(self.to)==list def envia(self, subject, text, files=[]): assert type(files)==list msg = MIMEMultipart() msg['From'] = self.remitente msg['To'] = COMMASPACE.join(self.to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(file,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(self.server) smtp.sendmail(self.remitente, self.to, msg.as_string()) smtp.close() return ----------------------------------- Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From sjmachin at lexicon.net Mon Jan 15 03:06:48 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2007 00:06:48 -0800 Subject: How naive is Python? In-Reply-To: References: Message-ID: <1168848408.785931.285160@q2g2000cwa.googlegroups.com> skip at pobox.com wrote: > John> How naive (in the sense that compiler people use the term) is the > John> current Python system? For example: > > John> def foo() : > John> s = "This is a test" > John> return(s) > > John> s2 = foo() > > John> How many times does the string get copied? > > Never. s and s2 just refer to the same object (strings are immutable). > Executing this: > > def foo() : > print id("This is a test") > s = "This is a test" > print id(s) > return(s) > > s2 = foo() > print id(s2) > > prints the same value three times. > > John> Or, for example: > > John> s1 = "Test1" > John> s2 = "Test2" > John> s3 = "Test3" > John> s = s1 + s2 + s3 > > John> Any redundant copies performed, or is that case optimized? > > Not optimized. You can see that using the dis module: > > 4 0 LOAD_CONST 1 ('Test1') > 3 STORE_FAST 0 (s1) > > 5 6 LOAD_CONST 2 ('Test2') > 9 STORE_FAST 1 (s2) > > 6 12 LOAD_CONST 3 ('Test3') > 15 STORE_FAST 2 (s3) > > 7 18 LOAD_FAST 0 (s1) > 21 LOAD_FAST 1 (s2) > 24 BINARY_ADD > 25 LOAD_FAST 2 (s3) > 28 BINARY_ADD > 29 STORE_FAST 3 (s) > 32 LOAD_CONST 0 (None) > 35 RETURN_VALUE > > The BINARY_ADD opcode creates a new string. > > John> How about this? > > John> kcount = 1000 > John> s = '' > John> for i in range(kcount) : > John> s += str(i) + ' ' > > John> Is this O(N) or O(N^2) because of recopying of "s"? > > O(N). Here's a demonstration of that: > > #!/usr/bin/env python > > from __future__ import division > > def foo(kcount): > s = '' > for i in xrange(kcount) : > s += str(i) + ' ' > > import time > > for i in xrange(5,25): > t = time.time() > foo(2**i) > t = time.time() - t > print 2**i, t, t/2**i > > On my laptop t roughly doubles for each iteration and prints around 5e-06 > for t/2**i in all cases. Sorry, Skip, but I find that very hard to believe. The foo() function would take quadratic time if it were merely adding on pieces of constant size -- however len(str(i)) is not a constant, it is O(log10(i)), so the time should be super-quadratic. Following are the results I got with Python 2.5, Windows XP Pro, 3.2Ghz Intel dual-core processor with the last line changed to print i, 2**i, t, t/2**i coz I can't do log2() in my head :-) [snip] 18 262144 0.889999866486 3.39508005709e-006 19 524288 3.21900010109 6.13975544184e-006 20 1048576 12.2969999313 1.17273330034e-005 21 2097152 54.25 2.58684158325e-005 22 4194304 229.0 5.45978546143e-005 [k/b interrupt] Cheers, John From duncan.booth at invalid.invalid Tue Jan 23 07:11:31 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jan 2007 12:11:31 GMT Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> Message-ID: "gangesmaster" wrote: > what problem does the cell object solve? The closure represents the variable, not the object. So if x is rebound to a different object your inner function g() will now access the new object. If the object itself was passed to MAKE_CLOSURE then g would only ever see the value of x from the instant when g was defined. >>> def f(x): def g(): print "x is", x g() x += 1 g() >>> f(1) x is 1 x is 2 From rschroev_nospam_ml at fastmail.fm Sat Jan 20 10:52:13 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 20 Jan 2007 15:52:13 GMT Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: <7xirf2w8vi.fsf@ruckus.brouhaha.com> References: <7xirf2w8vi.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schreef: > No. Top posting has always been an aberrance. It first appeared in > Usenet when Usenet (a word whose etymology comes from "Unix" and > "network") started attracting Microsoft Windows users, who were in the > habit of using Windows products that top-posted. That happened fairly > far along in Usenet's evolution Yep. The time when things started to go wrong is sometimes pinpointed as september 1993 and referred to as "Eternal September" (http://en.wikipedia.org/wiki/Eternal_September). -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From bj_666 at gmx.net Fri Jan 12 02:21:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 12 Jan 2007 08:21:05 +0100 Subject: Python nuube needs Unicode help References: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> Message-ID: In , Chris Mellon wrote: > On 11 Jan 2007 13:28:14 -0800, gheissenberger at gmail.com > wrote: > >> > audio="313-20070102144528.wav" grammarSet="G3" rawText="não" >> recValue="{data:CHOICE=NO;}" conf="970" rawText2="" conf2="0" >> transcribedText="não" parsableText="não"/ >> >> Clearly those "nã" are some non-Ascii characters, but how do I get >> print to understand that? >> >> I keep getting: >> "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in >> position 40: >> ordinal not in range(128)" >> > > Find out what encoding the files are in and modify the script to use it. The problem is not the encoding of the files as you see they are decoded to unicode strings by the XML reading part already. Ciao, Marc 'BlackJack' Rintsch From steven.bethard at gmail.com Fri Jan 5 22:08:42 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 05 Jan 2007 20:08:42 -0700 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: Stef Mientki wrote: > Not sure I wrote the subject line correct, > but the examples might explain if not clear [snip] > class pin2: > def __init__ (self, naam): > self.Name = naam > > aap2 = pin2('aap2') # seems completely redundant to me. > print aap2.Name You can use class statements to create your instances with some metaclass trickery. Unlike normal assignments, class statements get access to the name being assigned. So you could write your class like:: >>> class pin(object): ... def __init__(self, name): ... self.name = name ... @classmethod ... def from_class_block(cls, name, bases, block_dict): ... return cls(name) ... And then use class statements to create instances of the ``pin`` class:: >>> class aap: ... __metaclass__ = pin.from_class_block ... >>> print aap.name aap >>> type(aap) Of course, using class statements to create *instances* of a class is confusing. And it's more verbose than simply repeating the name when you call the constructor. But at least it avoids the redundancy. ;-) STeVe From oyekomova at hotmail.com Tue Jan 16 20:33:30 2007 From: oyekomova at hotmail.com (oyekomova) Date: 16 Jan 2007 17:33:30 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168715634.695961.14710@l53g2000cwa.googlegroups.com> Message-ID: <1168997610.819891.173980@11g2000cwr.googlegroups.com> Travis- Yes, I tried your suggestion, but found that it took longer to read a large file. Thanks for your help. Travis E. Oliphant wrote: > oyekomova wrote: > > Thanks to everyone for their excellent suggestions. I was able to > > acheive the following results with all your suggestions. However, I am > > unable to cross file size of 6 million rows. I would appreciate any > > helpful suggestions on avoiding memory errors. None of the solutions > > posted was able to cross this limit. > > Did you try using numpy.fromfile ? > > This will not require you to allocate more memory than needed. If you > specify a count, it will also not have to re-allocate memory in blocks > as the array size grows. > > It's limitation is that it is not a very sophisticated csv reader (it > only understands a single separator (plus line-feeds are typically seen > as a separator). > > -Travis From danielkleinad at gmail.com Wed Jan 24 12:58:24 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Wed, 24 Jan 2007 17:58:24 GMT Subject: Python 2.5 and Zeus Message-ID: Does anyone know if the Zeus IDE is compatible with Python 2.5? I sent an email to Zeus a couple days ago but have not heard anything. Thanks, Dan From Eugene.Antimirov at portaone.com Mon Jan 22 06:09:34 2007 From: Eugene.Antimirov at portaone.com (Eugene Antimirov) Date: Mon, 22 Jan 2007 13:09:34 +0200 Subject: newbie question In-Reply-To: <45B490D0.8020809@portaone.com> References: <618640.79082.qm@web7806.mail.in.yahoo.com> <45B490D0.8020809@portaone.com> Message-ID: <45B49B6E.8040900@portaone.com> Eugene Antimirov wrote: > You've probably missed cursor.commit() ;) Sorry, my bad: conn.commit() is correct one AFAIR. -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer support at portaone.com * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ From fperez.net at gmail.com Mon Jan 8 16:53:03 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Mon, 08 Jan 2007 14:53:03 -0700 Subject: Maybe a little bug of ipython 0.7.3 ? References: <45A2620E.70103@gmail.com> Message-ID: fdu.xiaojf at gmail.com wrote: > I'm new to ipython, and i found it a very cool product. Glad you like it, though in the future I recommend you post on the ipython list. I very rarely scan c.l.py these days, unfortunately. > $ ipython > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] > Type "copyright", "credits" or "license" for more information. > > IPython 0.7.3 -- An enhanced Interactive Python. > > > In [8]: a = range(1000) > > In [9]: a? > Type: list > Base Class: > String Form: [0, 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, 26 <...> 0, 981, 98 > 2, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, > 997, 998, 999] > Namespace: Interactive > Length: 1000 > Docstring: > list() -> new list > list(sequence) -> new list initialized from sequence's items > > *Please note that there is an extra "0" after "**26 <...>", which > doesn't appear for the followling cases:* The 'foo?' feature just gives you a summary of information about an object, and for very long strings, it truncates them in the center, printing only head<...>tail where head and tail are each about 100 characters long. What you are seeing is just an accident of where the truncation happens, that '0' is the last digit in 980 :) Cheers, f From liuwensui at gmail.com Mon Jan 1 13:56:19 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Mon, 1 Jan 2007 13:56:19 -0500 Subject: Wow, Python much faster than MatLab In-Reply-To: References: Message-ID: <1115a2b00701011056l58bf9994w28ef7879fda0ad15@mail.gmail.com> Gerry, I have the similar background as yours, many years using SAS/R. Right now I am trying to pick up python. >From your point, is there anything that can be done with python easily but not with SAS/R? thanks for your insight. wensui On 1/1/07, gblais at cox.net wrote: > We're not so far apart. > > I've used SAS or 25 years, and R/S-PLUS for 10. > > I think you've said it better than I did, though: R requires more attention > (which is often needed). > > I certainly didn't mean that R crashed - just an indictment of how much I > thought I was holding in my head. > > Gerry > -- > http://mail.python.org/mailman/listinfo/python-list > -- WenSui Liu A lousy statistician who happens to know a little programming (http://spaces.msn.com/statcompute/blog) From mtobis at gmail.com Thu Jan 4 20:23:46 2007 From: mtobis at gmail.com (Michael Tobis) Date: 4 Jan 2007 17:23:46 -0800 Subject: Turn off line wrap for lists? In-Reply-To: <1167958863.538291.60820@s34g2000cwa.googlegroups.com> References: <1167958863.538291.60820@s34g2000cwa.googlegroups.com> Message-ID: <1167960226.076110.89340@42g2000cwt.googlegroups.com> _ wrote: > (I did google for this, I promise) > > How do I get python NOT to insert newlines into string representations > of lists when I do something like this: > > strCollector += "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements'] > * 100) It shouldn't and doesn't insert newlines. ###### >>> strCollector = "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements'] * 100) >>> strCollector.split("\n")[0] == strCollector True ###### mt From mirandacascade at yahoo.com Sat Jan 6 20:49:02 2007 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 6 Jan 2007 17:49:02 -0800 Subject: AES256 in PyCrypto Message-ID: <1168134542.337448.261510@s34g2000cwa.googlegroups.com> Attempting to determine whether the PyCrypto package has the capability to perform AES256 encryption. I received the following C# snippet: CryptoProvider provider = new CryptoProvider(); Encrypted_Type password = new Encrypted_Type(); password.EncryptedData = new EncryptedDataType(); password.EncryptedData.EncryptionMethod = new EncryptionMethodType(); password.EncryptedData.EncryptionMethod.Algorithm = "AES256-cbc"; and I was told that it was the setup code for code that later on performs AES256 encryption. I'm assuming that setting the Algorithm property is what informs the system as to the type of encryption to perform. I included the above snippet as a reference point, because I'm attempting to understand how to do something equivalent in Python. Would the following Python code perform AES256 encryption on plainText from Crypto.Cipher import AES x = AES.new(a, AES.MODE_CBC, iv) x.encrypt(plainText) assuming: a = the key value iv = an initialization vector ? If the above Python code does not perform AES256 encryption: a) is there functionality within PyCrypto that allows one to perform AES256 encryption? b) if such functionality does not exist in PyCrypto, does it exist in some other Python package? Operating System: Windows XP Vsn of Python: 2.4 Thank you. From toto at titi.de Sun Jan 21 18:18:38 2007 From: toto at titi.de (laurent rahuel) Date: Mon, 22 Jan 2007 00:18:38 +0100 Subject: Python Windows Editors In-Reply-To: References: Message-ID: <45b3f4fe$0$21144$7a628cd7@news.club-internet.fr> Hi, I guess you could take a look at pydev extension for eclipse and if you wan't an almost straight forward installation, you should consider this link : http://www.easyeclipse.org/site/distributions/python.html Regards, Laurent W. Watson a ?crit : > I downloaded python-2.5.msi and installed it. I believe its editor is > IDE. I understand there's a Win editor called pythonwin. I believe it's > in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this > exe file has just the editor or all of Python. Comments? If not how do I > get the PythonWin editor by itself? > > BTW, one of the features I did not like of IDE is the limited file Print > command. It puts everything in 16pt type, and gives no choice over what > pages should be printed. Maybe there's an option? > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Two laws Newton and Einstein didn't discover: > 1. Time is money. > 2. Matter will be damaged in direct proportion > to its value. From paul.sijben at xs4all.nl Wed Jan 10 06:42:01 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 12:42:01 +0100 Subject: maximum number of threads In-Reply-To: References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> <7.0.1.0.0.20070110064655.0508d0a0@yahoo.com.ar> Message-ID: <45A4D109.809@xs4all.nl> Felipe Almeida Lessa wrote: > Maybe Stackless could help the OP? > http://www.stackless.com/ > thanks I will look into it! From kirby.urner at gmail.com Sat Jan 13 22:17:16 2007 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: 13 Jan 2007 19:17:16 -0800 Subject: Draft Pycon Keynote (a simulation) Message-ID: <1168744636.111293.292120@38g2000cwa.googlegroups.com> [this revision supersedes what I posted to edu-sig earlier today, a few typos fixed. Note that I'm not actually signed up for Pycon at this time, just using it as an exercise to polish my rap. All of the events, persons and institutions mentioned herein are quite real however]. === Although I haven't been invited to keynote in Dallas -- although I did volunteer (given my considerable experience) -- I thought a next best thing would be to lead by example, and encourage other subscribers to draft little keynotey things that would give us a sense of the vision and/or mission and/or state of our snake in our schools, so to speak. I would cite my gigs with Saturday Academy of Silicon Forest, both with the police (George Heuston of HPD), and through Portland State, both outreaches to youth somewhat at risk of corruption and/or losing their way amidst a bewildering wilderness of mirrors. At the police station (West Precinct) we harped on the downside of the Internet, a haven for perps, pervs and predators, especially adult, plus a constant source of temptations, e.g. of pirated goods, which might only serve to get you in trouble with the authorities. But George was uncomfortable with this sustained negative note, all downsides and terrors, when boyz and girlz just wanna have fun with all the new toyz, so if there is *any* safe way to enjoy this bonanza, maybe the police could role model it? They brought in some hired guns: me, of 4D Solutions, and Jerritt Collord, then of linuxfund.org, and long time veteran of North Portland's open source scene (I'm more the old hippie, mostly cut my teeth on closed source offerings in Southeast, am now just getting my second wind, thanks in part to Free Geek and Ron Braithwaite). Jerritt's take was decidely different from the more negatory stuff. He really knew his engineering, and if packets weren't encrypted, and hogged the shared public air, well then he, as a member of said public, wasn't being all that sneaky or outside of his rights if he just opened a few. Sysadmins do the same, and know if wired or wireless dorms use more Bittorrent than Jabber, and which servers enjoy the most traffic. The packets themselves tend to tell you that, by design, as a part of the monitoring infrastructure, which is needed to pinpoint bottlenecks, as well as to cut down on hogging, abuse, taking unfair advantage of resources we share. So there we were, the first day of class, immediately into sniffing packets, thinking about packets, where they come from, where they go, what they do. Enter 'Warriors of the Net', a great cartoon intro, and which I highly recommend to school teachers in Texas, if at all interested in what we in Oregon are into. [pause to show excerpt, with big speaker surround sound, however they do it in Texas http://www.warriorsofthe.net/]. Anyway, the kids found this refreshing: real hackers hacking, not just lecturing on criminal pathologies. George sat in on a few classes and I think he could see where we weren't just training up a new generation of law breakers. We were showing off our hacker subculture as highly ethical, and interested in sharing a growing stockpile of wealth that we ourselves create. We're not thieves. We *own* our code *and* choose to share it with peers. That's the message to youngsters in any case. We want 'em to grow up proud of their heritage. You can grow up to become a freedom loving hacker *and* be tough on crime, if that's what you'd like. Be like George for example, a computer forensics expert in charge of many a crime scene investigation, lots of FBI background. There's no contradiction here. Jerritt and I forked off in different directions after that class. He had a girlfriend in Montana, no obvious ties to Portland. Last we met, he was thinking about Japan. As a Portland native, I stuck with Saturday Academy and plodded along in a more academic vein, working in purer and purer forms of Python, with ever more math in the mix, sometimes to the exclusion of all else. Group theory, number theory, synergetics... burning the midnight oil. I was losing my Jerrittish side, given he wasn't around to reinforce it so directly. I missed the power of our HPD course, even though my more purist stuff got me gigs at Europython in Gothenburg, at the London Knowledge Lab, and as our BDFL's sidekick and Minister of Education at that Shuttleworth summit last April (I'm giving a talk on that meeting, check your program). [ pause to show excerpt of London Knowledge Lab talk -- on second thought, I don't think it's high rez enough. For printed copy, see these relevant links: http://worldgame.blogspot.com/2005/06/europython-2005.html http://www.bfi.org/pythonicmathematics ] Slowly, I've been building up that other side of my body, to where I can talk about Internet protocols, the stack, the heap, with some confidance and gusto. Dr. Sonnenfeld of New Mexico Tech was inspiring, reminding me of the relevance of the homespun, the down and dirty (he studies lightning), the importance of coming down from those mountain peaks on occasion. Dr. Bob Fuller, veteran of the Calculus Reform movement (largely successful) was likewise an inspiration, reminding me not to get lost in the clouds, over lattes in Oregon. This restored sense of balance gives my students more insights into the likes of Twisted, into the nuts and bolts of the Internet itself. Plone... Zope. I'm not being too prejudicial in my teaching them Python, not even in terms of their becoming computer scientists. That's for them to decide. I'm just here to show 'em some ropes, open some doors. wxPython, ODBC to MySQL, IronPython, Mailman... these all could be a "next step" for you, or maybe you're ready to teach them? We encourage peers teaching peers in our models, already the most tried and trusted vector for spreading a global geek culture. My own "next step" has been in the direction of VPython and its promise of easy OpenGL. Like Arthur on Edu-Sig, I see that Ruby is strong in this area, and Ruby toons (animated cartoons by or about Ruby) may well eclipse our snake's chances for more public exposure, if we don't act in concert. I'm thinking of rebranding my own Hypertoons [tm] to 'Anime on Rails' and invading the Japanese market, a pre-emptive strike. [pause for audience laughter Hypertoons: http://wiki.python.org/moin/HyperToons ] Happily though, I think peaceful co-existence with RubyToons is the most likely outcome, just like we in Python Nation already enjoy good relations with our closest long time neighbor, the Republic of Perl. Now, I know you're all wondering about YouTube and Google, and how this all fits with Intel's Viiv. I'd say, on behalf of the Portland Knowledge Lab, that yes, the goal is open source, lots and lots of it, so you can download and splice stuff together with wild abandon, not feeling encumbered by the prospect of lawsuits left and right, because of the blanketly permissive copyrights and licenses we'll be providing as shielding. In this way, our ability to cut and paste video, as easily as we cut and paste source code, will grow by leaps and bounds, to the great advantage of a knowledge based economy such as our own, wherein screencasting, including mathcasting, is an essential ingredient in building up the alphanumeracy skills of our future workforce. However, YouTube and Google Video aren't currently high rez enough to make looking at source code anything but painful. So the challenge is to develop a multi-tiered system of video distribution, and yes, the higher the bandwidth the more likely it'll end up costing you something, if not in terms of actual dollars, then in terms of disk space or rebranding rights. Great works of art (like Valve's Half Life, like Cyan's Uru) still don't come cheaply, and we're happy to pay for it, by and large, including sometimes through Foundation support of the artists. How will Python fit in to our open source video economy? At least one thing is clear: it'll be a lot easier to teach effectively, as will be the other languages. The rest is up to the developers and/or curriculum writers (not always different people). If you like our snake, and want to build in some bindings to your product, open source or proprietary, we hope you'll seriously consider doing so and follow through. Python, like any language, benefits from brand loyalty. Guido has never insulted our intelligence with a second rate offering. Our goal should be to continue his most excellent track record. Thank you and good afternoon. Kirby From gagsl-py at yahoo.com.ar Wed Jan 24 12:47:16 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 14:47:16 -0300 Subject: smtplib starttls gmail example - comments? In-Reply-To: References: <9afea2ac0701240256kae247b3s666be6529362c84e@mail.gmail.com> Message-ID: <7.0.1.0.0.20070124144251.05aeb830@yahoo.com.ar> At Wednesday 24/1/2007 09:12, BJ Swope wrote: >Both examples have included the cardinal sin in smtp... > >They both send the message text followed by new line dot new line. > >The smtp protocol specifically mentions CRLF dot CRLF. Please >please please use \r\n.\r\n in your code... No. The SMTP object takes care of proper message ending (as it should). If you append \r\n.\r\n to the message, or whatever, that will be correctly quoted and sent as part of the message. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jhefferon at smcvt.edu Tue Jan 30 08:07:39 2007 From: jhefferon at smcvt.edu (Jim) Date: 30 Jan 2007 05:07:39 -0800 Subject: error messages containing unicode In-Reply-To: <528sn0F1nhkoiU1@mid.uni-berlin.de> References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> <1170160464.576122.62230@h3g2000cwc.googlegroups.com> <528sn0F1nhkoiU1@mid.uni-berlin.de> Message-ID: <1170162459.577853.282090@l53g2000cwa.googlegroups.com> On Jan 30, 7:41 am, "Diez B. Roggisch" wrote: > >> (2) convert the file name to ASCII before you store it; or > > I need the non-ascii information, though, which is why I included it > > in the error message. > Then convert it to utf-8, or some encoding you know it will be used by your > terminal. Thank you for the suggestion. Remember please that I am asking for a safe way to pull the unicode object from the exception object (derived from a Python built-in), so I can't store it as unicode first and then convert to regular string when I need to print it out-- my exact question is how to get the unicode. So I take your answer to be to refuse to put in a unicode-not-ascii in there in the first place. It then seems to me that you are saying that the best practice is that every function definition should contain a parameter, like so. def openNewFile(fn,errorEncoding='utf-8'): : try: open(fn,'r') except Exception, err raise myException 'unable to open '+fn.encode(errorEncoding,'replace') I guess that beyond that passing those parameters and putting encode on every variable in my routines that occurs in an error message it is ugly, it seems to me that it violates the principle that you should do everything inside the program in unicode and only encode at the instant you need the output, in that the exception object is carrying around an ascii-not-unicode object. Jim From kylotan at gmail.com Mon Jan 8 11:04:27 2007 From: kylotan at gmail.com (Ben Sizer) Date: 8 Jan 2007 08:04:27 -0800 Subject: creating simple Python scripting interfaces via C++ Message-ID: <1168272267.679069.325890@38g2000cwa.googlegroups.com> I have Python embedded in a C++ application (yes, yes, I know, I'd prefer it the other way around too) and essentially need to expose some read-only values and functions to Python so it can be used to script the host application. When scripting a similar app in TCL, it's possible to associate each command with some client data, so that the command can be written in the script as a free function but it actually executes in some sort of context, accessed via the client data pointer in C++. In Python, there doesn't appear to be this mechanism, so I think I'd have to inject the context in another way, either as some sort of module-level global, or as an object, implementing the previously free functions as methods. Is this correct? If so, what is the simplest way of implementing the former method - inserting the pointer to the required context as a long (via PyDict_SetItemString(globals, "context", PyInt_FromLong(pointer)) or similar) and then converting it back in the bound function? And for the latter method, is it possible to make an arbitrary object and then attach methods and the context data? Or will I have to create a whole Python class for this (as in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54352)? I'm not interested in wrapping whole C++ objects at this stage, and libraries like Boost::Python aren't currently an option. I just need a few pointers on doing it the low-level way for now. -- Ben Sizer From http Thu Jan 11 01:25:44 2007 From: http (Paul Rubin) Date: 10 Jan 2007 22:25:44 -0800 Subject: Is there a way to protect a piece of critical code? References: Message-ID: <7xzm8q6pw7.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > am aware of Queue module - the same app uses it for something else. > I dont like too many try -- excepts in the code - I find they confuse > me when I try to read it later - and in this case I cannot block on waiting for > the queue to fill. Do you have multiple threads reading from the same queue? If not then you can use queue.empty() to see whether the queue is empty. If yes, queue.empty isn't reliable (it can return nonempty, and then another thread empties out the queue before you get a chance to read it). But you could always wrap the queue: QUEUE_IS_EMPTY = object() # global sentinel def get_from_queue(queue): try: return queue.get(block=False) except Queue.Empty: return QUEUE_IS_EMPTY Maybe it's worth adding a method like that to the Queue module in the stdlib. From skip at pobox.com Sun Jan 7 14:34:58 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 7 Jan 2007 13:34:58 -0600 Subject: strange for loop construct In-Reply-To: <1168193206.598957.257700@38g2000cwa.googlegroups.com> References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> <12ptf5bl21f2teb@corp.supernews.com> <1168193206.598957.257700@38g2000cwa.googlegroups.com> Message-ID: <17825.19298.34385.363481@montanaro.dyndns.org> Gabriel> Where do you find the "What's new" for previous releases? I Gabriel> have to read them online. Google for what's new site:python.org Skip From gordyt at gmail.com Thu Jan 18 17:07:06 2007 From: gordyt at gmail.com (gordyt) Date: 18 Jan 2007 14:07:06 -0800 Subject: import vs. subdirectory search In-Reply-To: <45AED511.8090307@animats.com> References: <45AED511.8090307@animats.com> Message-ID: <1169158026.677285.165340@11g2000cwr.googlegroups.com> John try this: from M2Crypto import SSL That should put your SSL module in the namespace as you want. --gordy From jjl at pobox.com Thu Jan 4 15:57:05 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 04 Jan 2007 20:57:05 GMT Subject: When argparse will be in the python standard installation References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> <459C008D.5040404@v.loewis.de> <459CBAC8.9060007@v.loewis.de> <64mdnTE_-5Ff3gDYnZ2dnUVZ_q6vnZ2d@comcast.com> Message-ID: <87d55u7bp7.fsf@pobox.com> Steven Bethard writes: > Martin v. L?wis wrote: > > Steven Bethard schrieb: > >> If someone has an idea how to include argparse features into optparse, > >> I'm certainly all for it. But I tried and failed to do this myself, so I > >> don't know how to go about it. > > It's not necessary that the implementation is retained, only that the > > interface is preserved. So if you can come up with an implementation > > that supports all optparse applications, and adds the additional > > features, your implementation could replace the current optparse. > > If you need to make incompatible changes, it would be best if you > > could produce a list of such changes, so that optparse users can > > review them to find out whether they are affected. > > FWIW, here's a short list of issues that could be easily addressed: > > * alias ArgumentParser to OptionParser [...snip long list of proposed aliases and additions...] > Some slightly harder issues: [...] You propose here to attempt to merge optparse and argparse into a single interface (single class, by the sound of it). I stopped reading after a bit, but at least up to that point, all of these issues could (and certainly should, if argparse is added to the stdlib, even in Python 3) be addressed by instead providing both OptionParser and an OptsAndArgsParser class (or whatever you'd call the latter). OptionParser would then support exactly the current optparse.OptionParser interface. OptsAndArgsProcessor would support your new interface. Presumably most of the actual implementation code would be shared. John From bruno.desthuilliers at websiteburo.com Tue Jan 9 03:20:11 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Tue, 09 Jan 2007 09:20:11 +0100 Subject: private variables In-Reply-To: References: Message-ID: <45a35032$0$319$426a34cc@news.free.fr> belinda thom a ?crit : > Hello, > > In what version of python were private variables added? Which private variables ? From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 12:56:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 18:56:46 +0100 Subject: Why less emphasis on private data? In-Reply-To: <7xmz4v11jq.fsf@ruckus.brouhaha.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: <45a12e20$0$300$426a74cc@news.free.fr> Paul Rubin a ?crit : > "Felipe Almeida Lessa" writes: > >>What is the chance of having to inherit from two classes from >>different modules but with exactly the same name *and* the same >>instance variable name? >> >>Of course you're being very pessimistic or extremely unlucky. > > > If you want to write bug-free code, pessimism is the name of the game. Not to pretend my own code is always totally bug-free, but I found that, with languages like Python, I usually got better results starting with the simplest possible implementation, and only then adding some 'defensive' boilerplate where it makes sens (that is mostly resources acquisition/release) - an approach that I would certainly not advocate when it comes to coding in C... From nszabolcs at gmail.com Mon Jan 29 18:09:29 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 15:09:29 -0800 Subject: [Boost.Graph] graph.vertices property creates new objects In-Reply-To: <1170095798.778605.30310@q2g2000cwa.googlegroups.com> References: <1170095798.778605.30310@q2g2000cwa.googlegroups.com> Message-ID: <1170112169.645867.326130@j27g2000cwj.googlegroups.com> > It seems that the vertices iterator creates new vertex objects every > time instead of iterating over the existing ones. This essentially i don't know much about bgl, but this is possible since vertices are most likely not stored as python objects inside boost > prevents, among other things, storing vertices as keys in a dictionary > since the hashes of the stored and the new vertex differ although they > compare equal. Is this really what's happening, and if so, why ? that sounds bad, fortunately __hash__ can be overriden so even if id() differs hash() can be the same for the same vertex. if __hash__ is not handled then it's a bug in bgl imho. From wolf_tracks at invalid.com Sun Jan 21 15:32:21 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 21 Jan 2007 20:32:21 GMT Subject: Python Windows Editors Message-ID: I downloaded python-2.5.msi and installed it. I believe its editor is IDE. I understand there's a Win editor called pythonwin. I believe it's in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this exe file has just the editor or all of Python. Comments? If not how do I get the PythonWin editor by itself? BTW, one of the features I did not like of IDE is the limited file Print command. It puts everything in 16pt type, and gives no choice over what pages should be printed. Maybe there's an option? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Two laws Newton and Einstein didn't discover: 1. Time is money. 2. Matter will be damaged in direct proportion to its value. -- Web Page: From 12cc104 at gmail.com Mon Jan 8 02:57:00 2007 From: 12cc104 at gmail.com (proctor) Date: 7 Jan 2007 23:57:00 -0800 Subject: regex question References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> Message-ID: <1168243020.304940.212700@42g2000cwt.googlegroups.com> Paul McGuire wrote: > "proctor" <12cc104 at gmail.com> wrote in message > news:<1168232001.377605.236270 at 11g2000cwr.googlegroups.com>... > > hello, > > > > i hope this is the correct place... > > > > i have an issue with some regex code i wonder if you have any insight: > > > > ================ > > There's nothing actually *wrong* wth your regex. The problem is your > misunderstanding of raw string notation. In building up your regex, do not > start the string with "r'" and end it with a "'". > > def makeRE(w): > print w + " length = " + str(len(w)) > # reString = "r'" + w[:1] > reString = w[:1] > w = w[1:] > if len(w) > 0: > for c in (w): > reString += "|" + c > # reString += "'" > print "reString = " + reString > return reString > > Or even better: > > def makeRE(w): > print w + " length = " + str(len(w)) > reString = "|".join(list(w)) > return reString > > Raw string notation is intended to be used when the string literal is in > your Python code itself, for example, this is a typical use for raw strings: > > ipAddrRe = r'\d{1,3}(\.\d{1,3}){3}' > > If I didn't have raw string notation to use, I'd have to double up all the > backslashes, as: > > ipAddrRe = '\\d{1,3}(\\.\\d{1,3}){3}' > > But no matter which way I create the string, it does not actually start with > "r'" and end with "'", those are just notations for literals that are part > of your Python source. > > Does this give you a better idea of what is happening? > > -- Paul yes! thanks so much. it does work now...however, one more question: when i type: rx_a = re.compile(r'a|b|c') it works correctly! shouldn't: rx_a = re.compile(makeRE(test)) give the same result since makeRE(test)) returns the string "r'a|b|c'" are you saying that the "r'" and "'" are being interpreted differently in the second case than in the first? if so, how would i go about using raw string notation in such a circumstance (perhaps if i need to escape "\b" or the like)? do i have to double up in this case? proctor. From not at set.se Thu Jan 25 15:43:43 2007 From: not at set.se (Daniel) Date: Thu, 25 Jan 2007 21:43:43 +0100 Subject: running applications in python References: <1169746124.376610.139420@13g2000cwe.googlegroups.com> Message-ID: 2007-01-25 18:28:44 lee wrote in message <1169746124.376610.139420 at 13g2000cwe.googlegroups.com> > how can i run or open a windows application from the python prompt?for > e.g.mediaplayer opening,folder acess etc Here's another way of doing it: import os TheCommandIwantTorun = '"C:\Program\Windows Media Player\wmplayer. exe"' #saves the command to a string os.system(TheCommandIwantTorun) #runs TheCommandIwantTorun in the command prompt (windows) From deets at nospam.web.de Wed Jan 17 12:03:26 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Jan 2007 18:03:26 +0100 Subject: predefined empty base class ?? References: <1169053011.399278.290980@a75g2000cwd.googlegroups.com> Message-ID: <51736uF1icq18U1@mid.uni-berlin.de> > is there an predefined empty base class > which I can instanziate to have an > container i can copy attributes in? No, but you can always do class Foo(object): pass foo = Foo() foo.attribute = value Diez From horpner at yahoo.com Wed Jan 24 16:08:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 24 Jan 2007 21:08:27 GMT Subject: Static variables References: Message-ID: On 2007-01-24, Florian Lindner wrote: > does python have static variables? I mean function-local > variables that keep their state between invocations of the > function. Yup. Here's a nice way. I don't how recent your Python must be to support this, though. >>> def foo(x): ... print foo.static_n, x ... foo.static_n += 1 ... >>> foo.static_n = 0 >>> for i in range(5): ... foo("?") ... 0 ? 1 ? 2 ? 3 ? 4 ? If you need to use an earlier version, then a "boxed" value stored as a keyword parameter will also work. >>> def foo(x, s=[0]): ... print s[0], x ... s[0] += 1 ... >>> for i in range(5): ... foo("!") ... 0 ! 1 ! 2 ! 3 ! 4 ! The latter is not as nice, since your "static" variable is easy to clobber by passing something into the function. -- Neil Cerutti From vithi99 at hotmail.com Wed Jan 31 20:17:10 2007 From: vithi99 at hotmail.com (vithi) Date: 31 Jan 2007 17:17:10 -0800 Subject: win32com.client In-Reply-To: References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> Message-ID: <1170292629.986774.88240@a34g2000cwb.googlegroups.com> This is not I was looking for. There is a module call "win32com.client" in python some people used it If any body know about it let me know. On Jan 31, 1:45 pm, Gary Herron wrote: > vithi wrote: > > Hi > > Any one tell me where I can get (or download) python modules win32com > > or win32com.client because I have to use "Dispatch" thanks > > You want the "python for windows" extension, available from > http://sourceforge.net/projects/pywin32/ > > Gary Herron From gagsl-py at yahoo.com.ar Thu Jan 11 21:57:11 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 23:57:11 -0300 Subject: RotatingFileHandler + subprocess module problems In-Reply-To: <7a9c25c20701111059q1186377nde4021eaf768d345@mail.gmail.com > References: <7a9c25c20701111059q1186377nde4021eaf768d345@mail.gmail.com> Message-ID: <7.0.1.0.0.20070111231652.05977e10@yahoo.com.ar> At Thursday 11/1/2007 15:59, Stephen Hansen wrote: >If I run app1, and then app2, it all works fine. Specifically, the >apps are logging correctly and I can see with Process Explorer that >each has a handle to the appropriate files. > >However, I have a setting to make App2 run App1 in the background >for convienance. This is using the subprocess module. When this >setting is on, App2 will die horribly the first time that the >doRollover comes along: specifically it gets a permission denied >error when it tries to rename App2.log to App2.log.1 > >After doing some debugging, it appears that App1 (if started by App2 >using the subprocess module) has a handle to App2.log /somehow/. It >never starts it, or touches it (verified through debug messages), >but seems to inherit it. That's subprocess fault. You menctioned Process Explorer, it appears you're using Windows. Using subprocess, the child process always inherits all file handles from its parent. This may or may not be desirable, and in your case, it's not. App1 inherits the open file handle to App2.log. Inside subprocess.py, near line 789, there is a call to CreateProcess; its 5th parameter is called bInheritHandles and it's set to 1. The comment "must inherit handles to pass std handles" is wrong AFAIK, and setting STARTF_USESTDHANDLES in startupinfo should be enough. (It may be that some lines above, STARTF_USESTDHANDLES is not correctly set). I'll try to investigate a bit more and file a bug report or a patch. In the meantime, you could replace that 1 in CreateProcess by a 0. Specially if you don't use PIPE or redirects, your problem should go away. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jeffrey at fro.man Wed Jan 31 10:56:56 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Wed, 31 Jan 2007 07:56:56 -0800 Subject: another newbie question: why should you use "*args" ? References: <4b4a3$45c0b94c$83aef404$20934@news1.tudelft.nl> Message-ID: <12s1f2ahudim196@corp.supernews.com> stef wrote: >> And one note more. Just to be more pythonic you shouldn't use form >> range(len(blabla)). Instead use: >> >> for i in list: >> ....blabla... >> >> > I would love that, > but please tell me how (I need an integer counter for something else too): for index, item in enumerate(args): ... Jeffrey From bill.scherer at verizonwireless.com Tue Jan 16 10:40:01 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Tue, 16 Jan 2007 10:40:01 -0500 Subject: Search Queue In-Reply-To: References: Message-ID: <45ACF1D1.8090904@verizonwireless.com> abcd wrote: >I have a class such as... > >id = 0 >class Foo: > def __init__(self, data): > self.id = id > id += 1 > self.data = data > >And I am storing them in a Queue.Queue... > >import Queue >q = Queue.Queue() >q.put(Foo('blah')) >q.put(Foo('hello world')) >q.put(Foo('test')) > >how can I search "q" for an instance of Foo which has 'id' equal to say >2? Typically a queue only lets you put and get, not really search. > >Thanks. > > > You could iterate through q.queue. Something like: for instance in q.queue: if instance.id == 2: print 'found it!" But, you mess around with the internals of a Queue instance at your own peril! From rrr at ronadam.com Mon Jan 15 22:01:35 2007 From: rrr at ronadam.com (Ron Adam) Date: Mon, 15 Jan 2007 21:01:35 -0600 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> References: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> Message-ID: Calvin Spealman wrote: > On 1/15/07, Steven D'Aprano wrote: >> On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote: >> >>> assert foo(0x10) == 0 # Assertions are much better tests than prints :-) >> I dispute that assertion (pun intended). > > Hah! > >> Firstly, print statements work even if you pass the -O (optimize) flag >> to Python. Your asserts don't. > > This is true, but the concept can be adapted to a things like an > assert_() function. > >> Secondly, a bare assertion like that gives you very little information: it >> just tells you that it failed: >> >>>>> x = 1 >>>>> assert x == 0 >> Traceback (most recent call last): >> File "", line 1, in ? >> AssertionError >> >> To provide the same information that print provides, you need something >> like this: >> >> assert x == 0, "x == %s not 0" % x > > What information would I need to know if my test passed? Nothing, I > say. I only want to know when the tests fail, especially as I add more > of them. Having no output is a great way to know nothing puked. > >> Thirdly, and most importantly, assert and print aren't alternatives, >> but complementary tools. Assertions are good for automated testing and >> simple data validation, where you already know what values you should >> have. Printing is good for interactively exploring your data when you're >> uncertain about the values you might get: sometimes it is hard to know >> what you should be asserting until you've seen what results your function >> returns. > > True, but I intended my statement as a nudge towards more proper > testing. Even when testing things out, I often use an assert rather > than a print, to verify some condition. There have been times where I would like assert to be a little more assertive than it is. :-) ie.. not being able to turn them off with the -0/-00 switches, and having them generate a more verbose traceback. Maybe have an alternative 'warn' as an alternative debugging version that could be set to ignore, soft (print to log), and hard (raise an error). An assert statement is a little clearer than an if...raise... in cases where you want to raise a value exception of some type. But I'm probably in the minority on this one. Ron From Thomas.Ploch at gmx.net Fri Jan 5 12:47:48 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 18:47:48 +0100 Subject: Dividing integers...Convert to float first? In-Reply-To: <459E8C77.3020603@rpath.com> References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> <459E8C77.3020603@rpath.com> Message-ID: <459E8F44.5090209@gmx.net> Jonathan Smith schrieb: > Thomas Ploch wrote: >> redefined.horizons at gmail.com schrieb: >>> I'm still pretty new to Python. I'm writing a function that accepts >>> thre integers as arguments. I need to divide the first integer by te >>> second integer, and get a float as a result. I don't want the caller of >>> the function to have to pass floats instead of integers. How do I >>> convert the arguments passed to the function into floats before I do >>> the division? Is this necessary, or is their a better way? >>> >>> Thanks, >>> >>> Scott Huey >>> >> >> Yes, it is necessary. If you divide two integers, the result will be an >> integer. >> >> >>> 1/2 >> 0 >> >> You need the function float() -> float because a division between >> integers and floats will have floats as their results >> >> >>> float(1)/2 >> 0.5 > > >>>> from __future__ import division >>>> 1/2 > 0.5 > > -smithj > aahh, I have been tought so many things about python that are actually so old, that I am starting to feel embarrassed. That brings me to the point, that learning a language X at university always brings you to a point where you know (almost) everything, but in reality know nothing because course material is too old... Thomas From duncan.booth at invalid.invalid Sun Jan 7 14:34:04 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jan 2007 19:34:04 GMT Subject: urlib.quote gives KeyError in Python 2.4.4 but workin 2.3.5 References: <1168195697.483795.71160@38g2000cwa.googlegroups.com> Message-ID: "nyenyec" wrote: > but it seems to work in Python 2.3.5 > > Python 2.3.5 (#1, Aug 19 2006, 21:31:42) > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys, urllib >>>> print sys.version > 2.3.5 (#1, Aug 19 2006, 21:31:42) > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] >>>> urllib.quote(u'\xe9') > '%E9' 'seems to' is correct: it should *probably* have given you '%C3%E9'. > > Is this a known bug? > > What's the workaround? UTF-8 encode the url before quoting it. *Some* web servers may not expect utf-8 encoding. utf-8 is the recommended encoding, but unfortunately it isn't actually required, so a few (mostly old) servers may expect something else. If so, use the appropriate encoding for the server. From ricli576 at student.liu.se Sat Jan 20 01:57:37 2007 From: ricli576 at student.liu.se (Rickard Lindberg) Date: 19 Jan 2007 22:57:37 -0800 Subject: Match 2 words in a line of file In-Reply-To: References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> <1169172954.107365.133950@51g2000cwl.googlegroups.com> <1169175299.490994.244700@51g2000cwl.googlegroups.com> Message-ID: <1169276257.512909.92380@v45g2000cwv.googlegroups.com> Daniel Klein wrote: > 2) This can be resolved with > > templine = ' ' + line + ' ' > if ' ' + word1 + ' ' in templine and ' ' + word2 + ' ' in templine: But then you will still have a problem to match the word "foo" in a string like "bar (foo)". From skip at pobox.com Tue Jan 30 15:03:51 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 30 Jan 2007 14:03:51 -0600 Subject: MoinMoin In-Reply-To: <3b8vr2tj0nc2hra616pm96m2turqm0v0vg@4ax.com> References: <3b8vr2tj0nc2hra616pm96m2turqm0v0vg@4ax.com> Message-ID: <17855.42151.790841.792538@montanaro.dyndns.org> Dan> Is it fair game to ask questions about MoinMoin here? Dan> If not, can someone recommend a resource please? Yes, however moin-user at lists.sourceforge.net will probably yield more responses: https://lists.sourceforge.net/lists/listinfo/moin-user I've had problems getting my posts to appear there recently though. I've been using the gmane interface instead: http://dir.gmane.org/gmane.comp.web.wiki.moin.general Skip From letezo at fw.hu Wed Jan 31 04:15:25 2007 From: letezo at fw.hu (=?iso-8859-2?q?L=E9tez=F5?=) Date: Wed, 31 Jan 2007 10:15:25 +0100 Subject: Retrieve keywords a internet domain name In-Reply-To: <1170233775.215834.14340@a34g2000cwb.googlegroups.com> References: <1170233775.215834.14340@a34g2000cwb.googlegroups.com> Message-ID: <200701311015.25453.letezo@fw.hu> > Also, does anyone know where I can find a decent dictionary that I can > use to verify if a word is a valid English word? Debian packages such as openoffice, ispell, aspell may contain a word list. You can search google for +english +"word list" or something similar. Viktor From rubbish at jabnet.uk.com Wed Jan 31 12:05:17 2007 From: rubbish at jabnet.uk.com (Stew Pid) Date: Wed, 31 Jan 2007 17:05:17 +0000 Subject: What is the dummy statement that do nothing in Python? References: Message-ID: On Wed, 31 Jan 2007 11:49:53 -0500, Dongsheng Ruan wrote: > I remember that in python there is some kind of dummy statement that just > holds space and does nothing. > > I want it to hold the place after a something like if a>b: do nothing > > I can't just leave the space blank after if statement because there will be > error message. > > Does anybody know what to insert there? > > Thanks! pass From horpner at yahoo.com Tue Jan 23 11:46:48 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Jan 2007 16:46:48 GMT Subject: match nested parenthesis References: <1169521381.814119.27020@11g2000cwr.googlegroups.com> Message-ID: On 2007-01-23, s99999999s2003 at yahoo.com wrote: > hi > i wish to find an reg exp for matching nested parenthesis of > varying level like > string = It is not possible, because the set of strings containing balanced parenthesis is not regular. Python re's aren't *really* regular expressions, so you might be able to hack something up using extensions (I'm not sure if it's been proven that you can'). I believe regexes are the wrong tool for the job. > "somewords1(words(somewords2)-(some(some)words3)somestuff)somestuff" > and be able to evaluate the pair starting from the inner > most(the deepest level) , ie (some) up till the outer most. > What is a good reg exp to do this? or is simple string > manipulations enough? Write a context free grammar and a recognizer for that grammar, instead. Python developers haven't been able to agree on any such module to include in the standard distribution yet, unfortunately. But fortunately (consequently), there are tons of nice parser and scanner generators available on the net. Try pyparsing for a start, as it's a recent, maintained package with excellent support on this group at the moment. Or just compose your own little function by hand. A stack-based solution (implemented using a list as a stack) should be easy enough. -- Neil Cerutti And now the sequence of events in no particular order. --Dan Rather -- Posted via a free Usenet account from http://www.teranews.com From svenrech at gmx.de Thu Jan 18 08:29:56 2007 From: svenrech at gmx.de (Sven Rech) Date: Thu, 18 Jan 2007 14:29:56 +0100 Subject: python embedding and threads Message-ID: <45AF7654.1030509@gmx.de> Hi, I'm the author of an application written in C, which should now be extended with a python plugin system. It already works very good, but I now have a problem: Threading functionality within the python modules, that my C app loads and calls, doesn't work. This means, the threads do not run (the same python code works correct if I just start it with the normal python interpreter). Is there something I must be aware of, if I want to use (python) threads with embedded python? (for example call a special function or something like that) Bye From pwatson at redlinepy.com Tue Jan 30 18:09:58 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 30 Jan 2007 17:09:58 -0600 Subject: PythonCard In-Reply-To: <1170193549.583822.156450@k78g2000cwa.googlegroups.com> References: <1170193549.583822.156450@k78g2000cwa.googlegroups.com> Message-ID: <52a1i6F1np2dcU1@mid.individual.net> Tequila wrote: > I'm having some trouble starting PythonCard on my PC. > > I've downloaded and ran python-2.5.msi to install Python on my > machine. And PythonCard-0.8.2.win32.exe to install PythonCard. > > When I try to run the program I get the following error: > ====================================== > C:\Python25\Lib\site-packages\PythonCard\tools > \codeEditor>codeEditor.py > Traceback (most recent call last): > File "C:\Python25\Lib\site-packages\PythonCard\tools\codeEditor > \codeEditor.py", line 13, in > from PythonCard import about, configuration, dialog, log, menu, > model, resource, util > File "C:\Python25\lib\site-packages\PythonCard\about.py", line 8, in > > import wx > ImportError: No module named wx > ====================================== > > Does anyone know what the problem might be? > > Thanks, > Tequila It would appear that you need to install wxPython also. http://www.wxpython.org/ From reedobrien at gmail.com Thu Jan 11 11:05:13 2007 From: reedobrien at gmail.com (reed) Date: 11 Jan 2007 08:05:13 -0800 Subject: Progress count in terminal (Mac OS X) In-Reply-To: References: <9079A3B8-47A8-495A-BFAE-09A603CFB819@mac.com> Message-ID: <1168531513.198600.59420@k58g2000hse.googlegroups.com> > > for i in range(100): > > sys.stdout.write( "\r" + "count ", i,) >> sys.stdout.flush() > > print # done maybe Tommy Grav wrote: > This certainly does work when running the interpreter interactively, > but when inserted into a script it seems to buffer the print statement > and not write it out to the terminal. How can I force the print > statement > to not buffer the output? > > Cheers > Tommy > > On Jan 11, 2007, at 9:22 AM, Fredrik Lundh wrote: > > > Tommy Grav : > > > >> I have a program that does a lot of iterations and would like > >> to follow its progress by having it print out the current iteration > >> number as it progresses. How do I do this so that it appears > >> like a counter that increases in the same place in the terminal > >> window? I am using python2.5 on a Mac OSX and its terminal > >> tcsh window. > > > > print a carriage return before, and no line feed after, each line: > > > > for i in range(100): > > print "\r" + "count", i, > > print # done > > > > > > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list From almondb at gmail.com Tue Jan 9 00:09:41 2007 From: almondb at gmail.com (Brian) Date: 8 Jan 2007 21:09:41 -0800 Subject: Getting started with Crystal Reports...little help in the far court. In-Reply-To: <1168293388.349793.256790@s80g2000cwa.googlegroups.com> References: <1168293388.349793.256790@s80g2000cwa.googlegroups.com> Message-ID: <1168319381.190806.38690@s34g2000cwa.googlegroups.com> Mudcat wrote: > I am not that familiar with Crystal Reports, but having read some other > posts I know that the way to integrate the API with Python is through > the COM interface provide by win32all. .... > Any pointers in the right direction would be helpful. Like Armury, I worked on Crystal stuff quite a long time ago. Here's a script I was able to dig up. Edited to protect the innocent. ;-) import sys from win32com.client import Dispatch app = Dispatch('CrystalRunTime.Application') rep = app.OpenReport('foo.rpt') tbl = rep.Database.Tables.Item(1) prop = tbl.ConnectionProperties('Password') prop.Value = sys.argv[1] prop = tbl.ConnectionProperties('Data Source') prop.Value = 'server' # tbl.TestConnectivity() should return 1 # clear and set 3 parameters params = rep.ParameterFields p1 = params(1) p2 = params(2) p3 = params(3) for param in (p1,p2,p3): param.ClearCurrentValueAndRange() p1.AddCurrentValue(123) p2.AddCurrentValue(456) p3.AddCurrentValue('12/31/99') rep.PrintOut(promptUser=False) From exarkun at divmod.com Mon Jan 29 16:04:56 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 29 Jan 2007 16:04:56 -0500 Subject: Executing Javascript, then reading value In-Reply-To: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> Message-ID: <20070129210456.25807.494023925.divmod.quotient.2701@ohm> On 29 Jan 2007 12:44:07 -0800, Melih Onvural wrote: >I need to execute some javascript and then read the value as part of a >program that I am writing. I am currently doing something like this: Python doesn't include a JavaScript runtime. You might look into the stand-alone Spidermonkey runtime. However, it lacks the DOM APIs, so it may not be able to run the JavaScript you are interested in running. There are a couple other JavaScript runtimes available, at least. If Spidermonkey is not suitable, you might look into one of them. Jean-Paul From paul at boddie.org.uk Tue Jan 30 11:27:09 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 30 Jan 2007 08:27:09 -0800 Subject: Please take me off the list In-Reply-To: References: Message-ID: <1170174428.224923.5500@p10g2000cwp.googlegroups.com> On 30 Jan, 16:33, Mikael Olofsson wrote: > > http://mail.python.org/mailman/listinfo/python-list See also the Tutor mailing list, which might be a bit better for starting to learn Python, should you (Daniel) decide to change your mind. Here's the mailing list's Web page: http://mail.python.org/mailman/listinfo/tutor If you haven't seen much information for beginners, take a look at these pages for some references: http://www.python.org/about/gettingstarted/ http://wiki.python.org/moin/BeginnersGuide Paul P.S. There does seem to be a lot of information, especially in the upper regions of the python.org Wiki, which is either incoherent or which gives the signal that hacking on the Python interpreter itself is what everyone should be wanting to do. Before it became "immutable" I was tempted to give the Wiki front page an overhaul, just to link more prominently to stuff like tutorials as well as the more active reference pages, but I suppose we're stuck with the current "back door" overview (along with semi-personal requests pages) for the time being. From bjourne at gmail.com Tue Jan 16 11:37:06 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 16 Jan 2007 17:37:06 +0100 Subject: Conflicting needs for __init__ method In-Reply-To: References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <740c3aec0701160837r33340866w5ddef3e09a0de537@mail.gmail.com> On 1/16/07, Steven D'Aprano wrote: > On Tue, 16 Jan 2007 08:54:09 +1100, Ben Finney wrote: > Think of built-ins like str() and int(). I suggest that people would be > *really* unhappy if we needed to do this: > > str.from_int(45) > str.from_float(45.0) > str.from_list([45, 45.5]) > etc. > > Why do you consider that Rationals are different from built-ins in this > regard? I would solve that with: import rational rational.rational(45) rational.rational(45.0) rational.rational([45, 45.5]) def rational(obj): initers = [(int, from_int), (basestring, from_str), (list, from_list)] for obj_type, initer in initers: if isinstance(obj, obj_type): return initer(obj) raise ValueError("Can not create a rational from a %r" % type(obj).__name__) -- mvh Bj?rn From Roberto.Bonvallet at cern.ch Thu Jan 18 05:38:35 2007 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Thu, 18 Jan 2007 10:38:35 +0000 (UTC) Subject: DOTALL not working as expected References: Message-ID: Stefan Palme wrote: >> using the "re" module of Python (2.3 and 2.4), I tried the following: >> >> import re >> print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL) >> > Just noticed, that it works when *compiling* the pattern: > > import re > p = re.compile('X.*?Y', re.DOTALL) > print re.sub(p, 'Z', 'Xab\ncdY') > > Still the question - my fault or a bug? Your fault. According to the documentation [1], the re.sub function takes a count as a fourth argument, not the compilation flags. [1] http://docs.python.org/lib/node46.html Cheers, -- Roberto Bonvallet From podi.ex at gmail.com Tue Jan 2 19:05:33 2007 From: podi.ex at gmail.com (Podi) Date: 2 Jan 2007 16:05:33 -0800 Subject: array of class References: <459ad4f7$0$293$426a34cc@news.free.fr> <1167777053.152492.3460@v33g2000cwv.googlegroups.com> <459ae31f$0$294$426a74cc@news.free.fr> Message-ID: <1167782733.743870.228760@k21g2000cwa.googlegroups.com> > > Or more compactly: > > > > words = [Word(w) for w in 'this is probably what you want'.split()] > > print words > > I didn't want to introduce yet some more "confusing" stuff !-) Indeed, the for loop is perfectly fine and totally readable. Let's save the "confusing stuff" to the Perl folks. From rweth at cisco.com Sat Jan 6 17:31:45 2007 From: rweth at cisco.com (rweth) Date: Sat, 06 Jan 2007 14:31:45 -0800 Subject: search mail by date with imaplib In-Reply-To: References: Message-ID: <1168122706.122766@sj-nntpcache-1.cisco.com> Jean-Paul Calderone wrote: > On Sat, 06 Jan 2007 11:49:17 -0800, rweth wrote: >> csselo at gmail.com wrote: >>> Hi >>> I am looking for a code sample which searches mail by date with imaplib >>> >>> example: >>> get email from 01.01.2007 to now >>> >>> how can I change imaplib search parameters? >>> >> So I had to do the same thing a few years back. I love python but >> seriously every author spends less than 1/10 of 1% on doc ! >> >> Well So do I .. so take it with a grain of salt. Here is what I did, >> MANY YEARS AGO .. I don't even have a IMAP account anymore >> >> t,data = M.uid("SEARCH",None,'(FROM blahblah)') >> luid = string.split(data[0]) >> for uid in luid: >> t,d = M.uid("FETCH",uid,"(BODY[HEADER.FIELDS (DATE SUBJECT TO)])") >> date = d[0][1] >> >> This will get you the dates .. and you can write your own >> filter off that .. it's trivial. What isn't so great is >> getting every piece of mail and then searching for the needle's in >> the haystack. >> >> So I guess this is plan c (just in case you don't get a better answer). >> I will watch this one for a "plan a | b" answer. >> > > The SEARCH command supports quite a few kinds of criteria. Several which > may be relevant here are BEFORE, SINCE, SENTBEFORE, and SENTSINCE. Using > Twisted's IMAP4 code, you can format a query like this: > > >>> from twisted.mail.imap4 import Query > >>> Query(after='01-Jan-2007') > '(AFTER "01-Jan-2007")' > >>> > > Since documentation was brought up, I'll point out Query's docs too, since > that might help shed some further light on what's possible. > > http://twistedmatrix.com/documents/current/api/twisted.mail.imap4.html#twisted.mail.imap4.Query > > > Jean-Paul Wow looks like twisted took Imap4 and made it better! I think I had better read up on twisted .. this looks quite good (Plan A for sure). From larry.bates at websafe.com Mon Jan 8 15:06:12 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 08 Jan 2007 14:06:12 -0600 Subject: Execute binary code In-Reply-To: <1168284300.638111.191440@38g2000cwa.googlegroups.com> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> Message-ID: citronelu at yahoo.com wrote: > Is it possible to execute a binary string stored within a python script > as executable code ? > > The script is run under Windows, and the binary code (a full executable > file) is stored in a variable in the script. > > I know I can use os.system() or os.popen() to run an external file, but > these functions take as argument a string evaluated as command-line. > > I also know I could save the binary code as a temporary file, execute > it and delete it afterwards, but this is not an alternative. > > Thanks. > What you are asking is a virus/trojan "like" program. There's no reason you shouldn't be able to write the code to TEMP directory and execute it. -Larry From smusnmrNOSPAM at yahoo.com Sat Jan 20 12:54:12 2007 From: smusnmrNOSPAM at yahoo.com (Siggi) Date: Sat, 20 Jan 2007 18:54:12 +0100 Subject: Win GUI application: avoiding DOS console Message-ID: Hi all, how do I avoid the DOS console show-up when starting a WinXP GUI application with mouseclick on the respective Python file? I had this with my previous Python installation; it is very simple, something with a "-i" somewhere in the open command of the MS Windows data types "PY" and "PYW". But after a new Python installation, this was lost, and I cannot find the instruction what to do. Please help! Thanks, siggi From svithi at gmail.com Sat Jan 6 23:24:31 2007 From: svithi at gmail.com (vinthan) Date: 6 Jan 2007 20:24:31 -0800 Subject: How to write code to get focuse the application which is open from server Message-ID: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> hi, I am new to python. I have to write test cases in python. An application is open in the desk top ( application writen in .Net) I have to write code to get focuse the application and click on the link which in the one side and it will load the map on the other and I have to check map is loaded. Any one tell me how do I use Dispatch or any other method to write a code. From daniele.varrazzo at gmail.com Wed Jan 31 08:45:46 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 31 Jan 2007 05:45:46 -0800 Subject: Help needed on config files In-Reply-To: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> References: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> Message-ID: <1170251146.519602.118130@v33g2000cwv.googlegroups.com> On Jan 31, 11:04 am, "jvdb" wrote: > Hi there, > > I am quite new on python programming and need some help on solving my > problem.. > > I have to make a (python) program which deletes files from > directories. I don't think deleting, etc. is the problem. The problem > is that the directories where i have to delete them are 'dynamic'/ > subject to change. So what i thought is to make a config file > containing an identifier (useful for myself) and there the directory. > something like: > [PROJECTx] > > [PROJECTy] > > > I have already seen that there are sorts of modules where you can read > a config file, but only when you know the key.. Can someone help me > out on this? The configfile can be altered in time (as there are more > projects coming where i have to delete files on a scheduled basis). The classes defined in the ConfigParser module contain a 'sections()' method that do what you need. http://docs.python.org/lib/module-ConfigParser.html Daniele From rocky at panix.com Thu Jan 25 14:15:43 2007 From: rocky at panix.com (R. Bernstein) Date: 25 Jan 2007 14:15:43 -0500 Subject: Possible bug in Python 2.5? (Was Re: pdb in python2.5) References: <1169717486.230356.79730@l53g2000cwa.googlegroups.com> Message-ID: I'd like to change my assessment of whether the problem encountered is a pdb bug or not. It could be a bug in Python. (Right now it is only known to be a bug in version 2.5.) For a given traceback t, the question is whether t.tb_frame.f_lineno can ever be different from t.tb_lineno. Still, for now in pydb CVS, I've worked around this by checking. rocky at panix.com (R. Bernstein) writes: > "Rotem" writes: > > > Hi, > > > > Maybe I'm repeating a previous post (please correct me if I am). > > > > I've tried the following code in python 2.5 (r25:51908, Oct 6 2006, > > 15:22:41) > > example: > > > > from __future__ import with_statement > > import threading > > > > def f(): > > l = threading.Lock() > > with l: > > print "hello" > > raise Exception("error") > > print "world" > > > > try: > > f() > > except: > > import pdb > > pdb.pm() > > > > This fails because pdb.pm() attempts to access sys.last_traceback which > > is not assigned. > > Recent releases of pydb (http://bashdb.sf.net/pydb) don't suffer this > problem. (But see below.) > > > Trying: > > pdb.post_mortem(sys.exc_traceback) > > > > Yields the following: > > > test.py(9)f() > > -> print "world" > > (Pdb) > > > > the 'w' command yields a similar output, which implies that the > > exception was thrown from the wrong line. > > the traceback module is better, yielding correct results (displays line > > 8 instead of 9). > > > > Has anyone encountered this behavior? > > Yes, this seems to be a bug in pdb. It is using the traceback's f_line > instance variable rather than the tb_lineno instance variable. I guess > these two values are usually the same. In fact, I haven't been able to > come up with a Python 2.4 situtation where they are different. (If > someone can, I'd appreciate it if you'd send me a small example so I > can put it in the pydb regression tests.) Even in 2.5, it's kind of > hard to get a case where they are different. If I remove the "with", > the problem goes away. > > It was also bug in pydb, but I've just committed in CVS the fix for > this > > > > is pdb broken? > > Best as I can tell pdb isn't all that well maintained. (Had it been, I > probably wouldn't have devoted the time to pydb that I have been.) > > > I get similar results for larger/more complex pieces of code. > > > > > Thanks in advance, > > > > Rotem From nagle at animats.com Tue Jan 16 23:51:18 2007 From: nagle at animats.com (John Nagle) Date: Tue, 16 Jan 2007 20:51:18 -0800 Subject: Does class patching actually work In-Reply-To: References: Message-ID: James Stroud wrote: > John Nagle wrote: >> The intent of this is to replace method open_https of class URLopener >> with a local, patched version. >> >> Does that actually work? When I've tried to do that in other code, it >> seems to have no effect. In fact, I can write >> >> URLopener.open_https = None >> >> and nothing changes. My mistake. Confusion between import a.b c = foo and import a b.c = foo which result in different namespaces. John Nagle From martinglobal at gmail.com Mon Jan 29 16:42:21 2007 From: martinglobal at gmail.com (Martin Global) Date: 29 Jan 2007 13:42:21 -0800 Subject: We sell to everyone!!! Government, Wholesalers, Distributers, Entreprenuers.....www.martin-global.com Message-ID: <1170106941.457739.34520@a75g2000cwd.googlegroups.com> Martin Global is one of North America's leading importers of goods manufactured and produced throughout Asia. We are distinctively unique from other importers, as we have one of North America's largest networks linking our organization directly to thousands of manufacturers and suppliers in Asia and throughout the world. We at Martin Global are proud of our reputation for excellence: a reputation based on our commitment to the highest manufacturing and ethical standards. At Martin Global, all of our business relationships with customers, suppliers, manufacturers and employees rest on a foundation of integrity and trust. Mission Statement Martin Global puts the needs of its clients first! We strive to establish long-term personal relationships built upon clients' trust in our ability to provide superior products at competitive prices. Whether you're a large corporation, government entity or a sole proprietor, we take these relationships very seriously and we believe that our success is measured by the success of our clients and their return business. Inquiries always welcomed. Your message will responded to within 8 hours. Regards, Donovan Martin Martin Global www.martin-global.com From bignose+hates-spam at benfinney.id.au Wed Jan 31 18:40:05 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Feb 2007 10:40:05 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> <1170284969.902118.155570@l53g2000cwa.googlegroups.com> Message-ID: <878xfivk8a.fsf@benfinney.id.au> "manstey" writes: > However, the problem is now that I can also write: > >>> insOref.Chapter=67 > but we want to disallow this, as insOref.Chapter must remain = > insProperty Then don't do that. Python allows any name to be reassigned to any value, with the attitude of "we're all consenting adults here". It's better to document[0] the correct behaviour of your code, rather than trying to prevent stupid mistakes. [0]: and unit tests, that explicitly check the behaviour of the code, and get run all the time during development of the code, are the best way of documenting behaviour unambiguously. -- \ "Buy not what you want, but what you need; what you do not need | `\ is expensive at a penny." -- Cato, 234-149 BC, Relique | _o__) | Ben Finney From vpolukcht at gmail.com Thu Jan 18 07:00:09 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 18 Jan 2007 04:00:09 -0800 Subject: One more regular expressions question In-Reply-To: <1169120317.437211.73660@m58g2000cwm.googlegroups.com> References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> <1169120317.437211.73660@m58g2000cwm.googlegroups.com> Message-ID: <1169121609.571152.214850@11g2000cwr.googlegroups.com> Great thanks. You post helped me so much! My resulting regexp is: "(?P^(.*)\s*)\(((?P\d+))\)\s+((?P\d+))" On Jan 18, 2:38 pm, "Daniele Varrazzo" wrote: > Victor Polukcht wrote: > > I have a couple of strings like: > > > Unassigned Number (1) 32 > [...] > > Interworking, unspecified (127) 5 > > > I need to get: > > Error code (value in brackets) - Value - Message. > > > My actual problem is i can't get how to include space, comma, slash.Probably you have some escaping problem. The substitution: > > re.sub(r"^(.*)\s*\((\d+)\)\s+(\d+)", r'\2 - \3 - \1', row) > > does the required job (where "row" is one of your lines) > > To match a special character, such as "(", you need to escape it with a > "\", because it has a special meaning in the regexp syntax. Because "\" > is the escaping mechanism for Python strings too, you better use raw > strings to specify the pattern. > > Other special character/groups matching patterns, such as "\s" to > specify whitespaces, are documented, together with everything else you > need, athttp://docs.python.org/lib/re-syntax.html > > HTH > > Daniele From ejohnso9 at earthlink.net Thu Jan 11 13:50:20 2007 From: ejohnso9 at earthlink.net (ej) Date: 11 Jan 2007 10:50:20 -0800 Subject: subclassing a module: misleading(?) error message In-Reply-To: <1167946286.988570.216110@i15g2000cwa.googlegroups.com> References: <459d687a$1@nntp.zianet.com> <1167946286.988570.216110@i15g2000cwa.googlegroups.com> Message-ID: <1168541420.185412.211380@o58g2000hsb.googlegroups.com> Carl Banks wrote: A good explanation I have not been able to get back to news lately - lot going on, but thank you for your time to explain that to me. It mostly makes pretty good sense to me, but I will have to study metaclasses further. ;) Thanks, -ej From danielkleinad at gmail.com Tue Jan 30 14:20:51 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Tue, 30 Jan 2007 19:20:51 GMT Subject: strip question References: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> Message-ID: On 26 Jan 2007 21:33:47 -0800, eight02645999 at yahoo.com wrote: >hi >can someone explain strip() for these : >[code] >>>> x='www.example.com' >>>> x.strip('cmowz.') >'example' >[/code] > >when i did this: >[code] >>>> x = 'abcd,words.words' >>>> x.strip(',.') >'abcd,words.words' >[/code] > >it does not strip off "," and "." .Why is this so? >thanks If you only have a couple of characters to deal with then use replace(). Otherwise use string.translate() : >>> import string >>> x = 'abcd,words.words' >>> transform = string.maketrans(',.','..') >>> x = string.translate(x, transform) >>> x = x.replace('.','') >>> x 'abcdwordswords'' Dan From andrea.massa at gmail.com Tue Jan 9 04:43:41 2007 From: andrea.massa at gmail.com (Nuke) Date: 9 Jan 2007 01:43:41 -0800 Subject: formattazione cifra con decimali In-Reply-To: <1168335548.504284.287150@q40g2000cwq.googlegroups.com> References: <1168335548.504284.287150@q40g2000cwq.googlegroups.com> Message-ID: <1168335821.473566.220190@38g2000cwa.googlegroups.com> Nuke ha scritto: > Ho cercato un poco sulla documentazione di python senza trovare una > risposta soddisfacente al mio problema, quindi spero di trovare un > aiuto qui. > Ho creato un programmino che mi fa alcuni calcoli e riepiloghi > personali e vorrei visualizzare i totali numerici in euro con la > formattazione comprensiva dei separatori decimali. > > Per esempio ho un totale scritto attualmente cos?: 50320,12 e > vorrei che si visualizzasse cosi: 50.320,12 > > esiste gi? una qualche funzione che mi formatta il numero (o la > stringa eventualmente) in questo modo? > > Grazie a chi sapr? darmi una risposta in merito. Sorry for the language, i think the group was in italian language... sorry :( I try to explain my problem in english: I need to visualize a number (or a string of that number) using the decimal separator. i have this number visualized: 50320,12 and i need that the visualization of this number is: 50.320,13. There is a function that directly convert the number (or the string) ? Thank in advance, and sorry again for the language used before. From ccardelli at iv-srl.it Mon Jan 29 03:43:44 2007 From: ccardelli at iv-srl.it (ccardelli at iv-srl.it) Date: 29 Jan 2007 00:43:44 -0800 Subject: SpecTix Message-ID: <1170060224.678000.185560@h3g2000cwc.googlegroups.com> Hi all. I'd like to test the SpecTix package (GUI generation for TK). I have read somewhere that it can generate GUI code for python, but the download location (http://starship.python.net/crew/mike/Spectix/) is inactive. Could someone provide a copy of the package or suggest an alternate download site? Latest version seems to be 1.2a3-1.4. Thank you. From fccoelho at gmail.com Wed Jan 24 16:43:24 2007 From: fccoelho at gmail.com (Flavio) Date: 24 Jan 2007 13:43:24 -0800 Subject: raise UnicodeError, "label too long" References: <1169672223.231030.262610@l53g2000cwa.googlegroups.com> Message-ID: <1169675004.099912.79520@v33g2000cwv.googlegroups.com> What I am doing is very simple: I fetch an url (html page) parse it using BeautifulSoup, extract the links and try to open each of the links, repeating the cycle. Beautiful soup converts the html to unicode. That's why when I try to open the links extracted from the page I get this error. This is bad, since some links do contain strings with non-ascii characters. thanks, Fl?vio Marc 'BlackJack' Rintsch escreveu: > In <1169672223.231030.262610 at l53g2000cwa.googlegroups.com>, Flavio wrote: > > > Hi I am havin a problem with urllib2.urlopen. > > > > I get this error when I try to pass a unicode to it. > > > > raise UnicodeError, "label too long" > > > > is this problem avoidable? no browser or programs such as wget seem to > > have a problem with these strings. > > What exactly are you doing? How does a (unicode?) string look like that > triggers this exception? > > Ciao, > Marc 'BlackJack' Rintsch From joshua at eeinternet.com Wed Jan 24 17:57:53 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 24 Jan 2007 13:57:53 -0900 Subject: Beginners Tutorial in PDF Format? References: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net><1169415358.277431.130640@s34g2000cwa.googlegroups.com> Message-ID: <45b7d7cb$0$24391$88260bb3@free.teranews.com> W. Watson wrote: >>> http://docs.python.org/download.html >> >> Try again. The first url goes to this page: >> Download Python 2.5 Documentation (19 September 2006): To download an >> archive containing all the documents for this version of Python in one >> of various formats [pdf included, you can choose between Letter/A4]. >> Below, it says "These documents are not available for download >> individually." >> > There is nothing there with the title "Python 2.5 Documentation". Really? At http://docs.python.org/download.html the header across says "Download Python 2.5 Documentation (19 September 2006)" and the links for downloading are, for example, http://docs.python.org/ftp/python/doc/2.5/pdf-letter-2.5.zip "2.5" occurs twice in that URL. I think that's a pretty good indicator that it is a download for version 2.5. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From horpner at yahoo.com Sat Jan 27 02:26:19 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 27 Jan 2007 07:26:19 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> <12rl5mq4nnqoea0@corp.supernews.com> Message-ID: On 2007-01-27, Thomas Dickey wrote: > Neil Cerutti wrote: >> I don't really expect it to work, but if anything will, that >> is it. Curses supports only ASCII and a some special symbol >> codes defined by curses. > > un - no. Curses supports whatever the flavor of curses you > have does. Often that's the 8-bit flavor of ncurses, but the > limitation is definitely in the python configuration. Thanks for the clarification. I was going by the some Python documentation, but I did notice contradictory information in other discussion. The 8-bit ncurses is supposed to support iso-8859-1 through iso-8859-15, i.e., all the byle encodings. I don't know why Python's bindings don't work. -- Neil Cerutti From tomas at fancy.org Wed Jan 3 13:36:56 2007 From: tomas at fancy.org (Tom Plunket) Date: Wed, 03 Jan 2007 10:36:56 -0800 Subject: A python library to convert RTF into PDF ? References: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> Message-ID: <5stnp25m2uffc4n5k7g9e68hk2l85u4fmm@4ax.com> leonel.gayard at gmail.com wrote: > So, what library can I use to convert from RTF to PDF ? GPL / BSD > Libraries are welcome. If you could write to LaTeX files instead, you could then just use pdflatex that comes with all of the LaTeX distributions. -tom! -- From bob at passcal.nmt.edu Tue Jan 2 18:43:37 2007 From: bob at passcal.nmt.edu (Bob Greschke) Date: Tue, 2 Jan 2007 16:43:37 -0700 Subject: Need old pywin32/win32all for Win95 Message-ID: <3pudnVzXD-m3cwfYnZ2dnUVZ_qCmnZ2d@nmt.edu> Does anyone have an old version of this? I've got some old OEM stuff that will only handle Win95 because of some custom hardware drivers. The build 200 on sourceforge of pywin32 isn't old enough. I'm trying to get pyserial up and running. Python/Tkinter does OK at 233MHz! :) Thanks! Bob From robert.kern at gmail.com Sat Jan 20 19:36:11 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 20 Jan 2007 18:36:11 -0600 Subject: scipy.optimize.lbfgsb help please!!! In-Reply-To: References: Message-ID: mclaugb wrote: > " x, f, d = lbfgsb.fmin_l_bfgs_b(Permmin, x0, Jacobi, params, > bounds=[(.001,100),(-50,-.001)] , maxfun=500) > File "C:\Python24\lib\site-packages\scipy\optimize\lbfgsb.py", line 197, > in fmin_l_bfgs_b > isave, dsave) > ValueError: failed to initialize intent(inout) array -- expected elsize=8 > but got 4 -- input 'l' not compatible to 'd'" And also tell us your platform. I suspect this is a 64-bit problem. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at holdenweb.com Tue Jan 30 00:00:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Jan 2007 05:00:25 +0000 Subject: Off-Topic Posts In-Reply-To: <1170084373.204141.279900@v45g2000cwv.googlegroups.com> References: <1169821615.198847.237790@m58g2000cwm.googlegroups.com> <1169852283.740452.87800@m58g2000cwm.googlegroups.com> <1170084373.204141.279900@v45g2000cwv.googlegroups.com> Message-ID: thermate at india.com wrote: > On Jan 27, 1:31 pm, Jim Klein wrote: >> I'm not one of the conquered races, I'm Swiss. We are the bankers to >> the conquerers. :-) > > Exactly, Honorable J Klein, (although my reference was a general one, > you have entered the thread, so I will pick the swiss case) more like > tributaries to the conquerers ... I I suppose I'd be a fascist if I suggested that you are posting this crap inappropriately and you should piss off to where you were appreciated (if any such cyber-place exists)? sigh ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From webmaster at cacradicalgrace.org Wed Jan 3 17:15:58 2007 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Wed, 03 Jan 2007 15:15:58 -0700 Subject: Iterate through list two items at a time References: Message-ID: Gabriel Genellina wrote: > b=iter(a) > for x in b: > y=b.next() > print x,y > So as not to choke on odd-length lists, you could try a = [1,2,3,4,5,6,7] b = iter(a) for x in b: try: y=b.next() except StopIteration: y=None print x,y Substitute in whatever for y=None that you like. Cheers, Cliff From http Thu Jan 25 07:57:15 2007 From: http (Paul Rubin) Date: 25 Jan 2007 04:57:15 -0800 Subject: While loop with "or"? Please help! References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> <45b8a31d$0$2401$426a74cc@news.free.fr> Message-ID: <7xlkjrtgb8.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > > while?not?usrinp.lower()?in?"yn": > > But note that 'in' performs a substring search and therefore "yn" and "" > would be accepted as valid answers, too. Oh right, that's a recent change to the language, I think. OK: while?not?usrinp.lower()?in?list("yn"): ... From sjdevnull at yahoo.com Wed Jan 3 04:57:01 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 3 Jan 2007 01:57:01 -0800 Subject: Synchronization methodology In-Reply-To: References: Message-ID: <1167818221.856368.38210@42g2000cwt.googlegroups.com> Chris Ashurst wrote: > Hi, I'm coming in from a despised Java background Consider strongly the fact that Python supports multiple process solutions well, so you're not stuck having to use multithreaded solutions in every circumstance (but can still use them when necessary). From martin at v.loewis.de Fri Jan 5 04:25:28 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Jan 2007 10:25:28 +0100 Subject: PyType_IsSubtype () In-Reply-To: <1167986947.735415.99970@s34g2000cwa.googlegroups.com> References: <1167986947.735415.99970@s34g2000cwa.googlegroups.com> Message-ID: <459E1988.8060807@v.loewis.de> Sheldon schrieb: > Can anyone tell me what this error mean: > #0 0x4008376e in PyType_IsSubtype () from /usr/lib/libpython2.3.so.1.0 It's not an error. It is just a frame from the backtrace. To understand the crash better, one would need to see more frames from the backtrace. Ideally, one would run the program in a debugger to analyse it further. Regards, Martin From gandalf at designaproduct.biz Tue Jan 9 13:25:35 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 09 Jan 2007 19:25:35 +0100 Subject: Question about using "with" In-Reply-To: References: Message-ID: <45A3DE1F.4020909@designaproduct.biz> > > 591 > ./cat.py cat.py > File "./cat.py", line 6 > with open(sys.argv[nn]) as f: > ^ > SyntaxError: invalid syntax > 592 > > > This example came from http://docs.python.org/tut/node10.html down in > section 8.7 > > Am I missing something? > Are you using python 2.5? The with statement is not available before 2.5. Laszlo From chris at kateandchris.net Fri Jan 5 17:45:45 2007 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 5 Jan 2007 17:45:45 -0500 Subject: Newbie XML SAX Parsing: How do I ignore an invalid token? In-Reply-To: <1168033818.692201.183790@11g2000cwr.googlegroups.com> References: <1168033818.692201.183790@11g2000cwr.googlegroups.com> Message-ID: <20070105224545.GA2177@kateandchris.net> What exactly is invalid about the XML fragment you provided? It seems to parse correctly with ElementTree: >>> from xml.etree import ElementTree as ET >>> e = ET.fromstring(""" ... ... ... Tampa ... A great city ^^ and place to live ... ... ... Clearwater ... Beautiful beaches ... ... ... """) >>> print ET.tostring(e) Tampa A great city ^^ and place to live Clearwater Beautiful beaches >>> Do you have invalid characters? unclosed tags? The solution to each of these problems is different. More info will solicit better solutions. -Chris On Fri, Jan 05, 2007 at 01:50:18PM -0800, scott at crybabymaternity.com wrote: > I've got an XML feed from a vendor that is not well-formed, and having > them change it is not an option. I'm trying to figure out how to > create an error-handler that will ignore the invalid token and continue > on. > > The file is large, so I'd prefer not to put it all in memory or save it > off and strip out the bad characters before I parse it. > > I've included one of the problematic characters in a small XML snippet > below. > > I'm new to Python, and I don't know how to accomplish this. Any help is > greatly appreciated! > > ----------------------------------------------------------------- > > Here is my code: > > from xml.sax import make_parser > from xml.sax.handler import ContentHandler > import StringIO > > class ErrorHandler: > def __init__(self, parser): > self.parser = parser > def warning(self, msg): > print '*** (ErrorHandler.warning) msg:', msg > def error(self, msg): > print '*** (ErrorHandler.error) msg:', msg > def fatalError(self, msg): > print msg > > class ContentHandler(ContentHandler): > def __init__ (self): > pass > def startElement(self, name, attrs): > pass > def characters (self, ch): > pass > def endElement(self, name): > pass > > xmlstr = """ > > > Tampa > A great city  and place to live > > > Clearwater > Beautiful beaches > > > """ > parser = make_parser() > curHandler = ContentHandler() > errorHandler = ErrorHandler(parser) > parser.setContentHandler(curHandler) > parser.setErrorHandler(errorHandler) > parser.parse(StringIO.StringIO(xmlstr)) > > -- > http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Fri Jan 12 03:27:06 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 Jan 2007 09:27:06 +0100 Subject: Python nuube needs Unicode help References: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> Message-ID: gheissenberger at gmail.com wrote: > HELP! > Guy who was here before me wrote a script to parse files in Python. > > Includes line: > print u According to your other posts 'u' seems to be an instance of a custom Utterance class with a __str__() method that accidentally returns unicode. Try changing the print statement to print unicode(u) If you're lucky, it works. Otherwise we need a piece of the actual code. To give you an idea what a self-contained demonstration of your problem might look like: >>> class Utterance(object): ... def __str__(self): return u"???" ... >>> u = Utterance() >>> print u Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) >>> print unicode(u) ??? Peter From smithj at rpath.com Fri Jan 5 12:35:51 2007 From: smithj at rpath.com (Jonathan Smith) Date: Fri, 05 Jan 2007 12:35:51 -0500 Subject: Dividing integers...Convert to float first? In-Reply-To: <459E8B5C.6020804@gmx.net> References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> Message-ID: <459E8C77.3020603@rpath.com> Thomas Ploch wrote: > redefined.horizons at gmail.com schrieb: >> I'm still pretty new to Python. I'm writing a function that accepts >> thre integers as arguments. I need to divide the first integer by te >> second integer, and get a float as a result. I don't want the caller of >> the function to have to pass floats instead of integers. How do I >> convert the arguments passed to the function into floats before I do >> the division? Is this necessary, or is their a better way? >> >> Thanks, >> >> Scott Huey >> > > Yes, it is necessary. If you divide two integers, the result will be an > integer. > > >>> 1/2 > 0 > > You need the function float() -> float because a division between > integers and floats will have floats as their results > > >>> float(1)/2 > 0.5 >>> from __future__ import division >>> 1/2 0.5 -smithj From gatti at dsdata.it Thu Jan 25 05:47:44 2007 From: gatti at dsdata.it (gatti at dsdata.it) Date: 25 Jan 2007 02:47:44 -0800 Subject: Do I need Python to run Blender correctly? In-Reply-To: References: Message-ID: <1169722064.189055.61620@v45g2000cwv.googlegroups.com> On Jan 25, 9:25 am, "AKA gray asphalt" wrote: > I downloaded Blender but there was no link for python. Am I on the right > track? Don't worry, Blender includes its own bundled Python interpreter, which is usually one version behind; just leave it alone. Lorenzo Gatti From scott at crybabymaternity.com Fri Jan 5 16:50:18 2007 From: scott at crybabymaternity.com (scott at crybabymaternity.com) Date: 5 Jan 2007 13:50:18 -0800 Subject: Newbie XML SAX Parsing: How do I ignore an invalid token? Message-ID: <1168033818.692201.183790@11g2000cwr.googlegroups.com> I've got an XML feed from a vendor that is not well-formed, and having them change it is not an option. I'm trying to figure out how to create an error-handler that will ignore the invalid token and continue on. The file is large, so I'd prefer not to put it all in memory or save it off and strip out the bad characters before I parse it. I've included one of the problematic characters in a small XML snippet below. I'm new to Python, and I don't know how to accomplish this. Any help is greatly appreciated! ----------------------------------------------------------------- Here is my code: from xml.sax import make_parser from xml.sax.handler import ContentHandler import StringIO class ErrorHandler: def __init__(self, parser): self.parser = parser def warning(self, msg): print '*** (ErrorHandler.warning) msg:', msg def error(self, msg): print '*** (ErrorHandler.error) msg:', msg def fatalError(self, msg): print msg class ContentHandler(ContentHandler): def __init__ (self): pass def startElement(self, name, attrs): pass def characters (self, ch): pass def endElement(self, name): pass xmlstr = """ Tampa A great city and place to live Clearwater Beautiful beaches """ parser = make_parser() curHandler = ContentHandler() errorHandler = ErrorHandler(parser) parser.setContentHandler(curHandler) parser.setErrorHandler(errorHandler) parser.parse(StringIO.StringIO(xmlstr)) From mike.klaas at gmail.com Thu Jan 25 01:00:53 2007 From: mike.klaas at gmail.com (Klaas) Date: 24 Jan 2007 22:00:53 -0800 Subject: The reliability of python threads In-Reply-To: <7x8xfr6h0j.fsf@ruckus.brouhaha.com> References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169683654.672020.136820@q2g2000cwa.googlegroups.com> <7xveiwklt0.fsf@ruckus.brouhaha.com> <1169687269.885833.285410@a34g2000cwb.googlegroups.com> <7x8xfr6h0j.fsf@ruckus.brouhaha.com> Message-ID: <1169704852.974111.51380@q2g2000cwa.googlegroups.com> On Jan 24, 5:18 pm, Paul Rubin wrote: > "Klaas" writes: > > CPython is more that "a particular implementation" of python, > It's precisely a particular implementation of Python. Other > implementations include Jython, PyPy, and IronPython. I did not deny that it is an implementation of Python. I deny that it is but an implementation of Python. Jython: several versions behind, used primariy for interfacing with java PyPy: years away from being a practical platform for replacing CPython IronPython: best example you've given, but still probably three or four orders of magnitude less significant that CPython > > and the GIL is more than an "artifact". It is a central tenet of > > threaded python programming. > If it's a central tenet of threaded python programming, why is it not > mentioned at all in the language or library manual? The same reason why IE CSS quirks are not delineated in the HTML 4.01 spec. This doesn't mean that they aren't central to css web programming (they are). How could the GIL, which limits the number of threads in which python code can be run in a single process to one, NOT be a central part of threaded python programming? > The threading > module documentation describes the right way to handle thread > synchronization in Python, and that module implements traditional > locking approaches without reference to the GIL. No-one has argued that the GIL should be used instead of threading-based locking. How could they? The two concepts are not interchangeable and while they affect each other, are two different things entirely. In the post you responded to and quoted I said: > > I don't advocate relying on the GIL to manage shared data when > > threading, -Mike From techtonik at gmail.com Wed Jan 24 05:50:44 2007 From: techtonik at gmail.com (techtonik) Date: 24 Jan 2007 02:50:44 -0800 Subject: Q: Why Python is bad for web from the point of URLs? Message-ID: <1169635844.254229.310460@a75g2000cwd.googlegroups.com> A: Because you need three modules to parse, edit and reassemble query string. urlparse, cgi and urllib From gagsl-py at yahoo.com.ar Wed Jan 24 13:05:11 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 15:05:11 -0300 Subject: Thoughts on using isinstance In-Reply-To: <1169659264.605545.211000@s48g2000cws.googlegroups.com> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> <1169659264.605545.211000@s48g2000cws.googlegroups.com> Message-ID: <7.0.1.0.0.20070124144844.05aebd88@yahoo.com.ar> At Wednesday 24/1/2007 14:21, abcd wrote: > >Yes because usually you don't expect a list or dictionary but some object > > that *acts* like a list or dictionary. Or you even expect just some > > aspects of the type's behavior. For example that it is something you can > > iterate over. > > > > Ciao, > > Marc 'BlackJack' Rintsch > >good point. is there place that documents what methods/attrs I should >check for on an object? for example, if its a list that I expect I >should verify the object that is passed in has a ??? function? etc. Don't insist on checking! :) Just try to use the object - you'll get an exception at first invalid usage. By example, a lot of functions take a file parameter to output something on it. Usually the *only* method called is write(). So any object with a write() method (taking a single string argument) would be fine; StringIO are an example. Checking if the argument is an instance of the file type would make that impossible. Anyway, sometimes it's ok to check in advance - but please consider to check the *behavior* you expect, not the exact instance type. In the example above, you can validate that fileobject has a write attribute: getattr(fileobject, "write"). But I'd only do that if I have a good reason (perhaps if the file is used after some lengthy calculation,and I want to be sure that I will be able to store the result) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bearophileHUGS at lycos.com Thu Jan 25 04:51:56 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Jan 2007 01:51:56 -0800 Subject: Fast Imaging for Webserver In-Reply-To: <1169712298.439101.171730@l53g2000cwa.googlegroups.com> References: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> <1169712298.439101.171730@l53g2000cwa.googlegroups.com> Message-ID: <1169718716.772895.220490@v45g2000cwv.googlegroups.com> Paul McGuire: > before you start replacing PIL, or > optimizing CherryPy, or other possible performance-improving efforts, > you should profile the within-request processing, find the bottleneck, > and take care of that first. Good advice. Among the tests, the OP can also try to change the antialiasing type of PIL, going to the nearest neighbor, and doing some transfer timings again. It may help find where the bottleneck is. Bye, bearophile From vinay_sajip at yahoo.co.uk Tue Jan 23 05:01:24 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 23 Jan 2007 02:01:24 -0800 Subject: selective logger disable/enable References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> <1169349399.938121.238430@38g2000cwa.googlegroups.com> <1169395276.181654.160810@a75g2000cwd.googlegroups.com> <1169437763.213781.163660@38g2000cwa.googlegroups.com> <1169442596.209314.162410@s34g2000cwa.googlegroups.com> <1169531341.221067.205500@11g2000cwr.googlegroups.com> Message-ID: <1169546484.370874.253890@a75g2000cwd.googlegroups.com> Gary Jefferson wrote: > Vinay Sajip wrote: > > > > BTW I would also advise reading PEP-282 to understand more about the > > logging approach. > > > You've been most helpful, Vinay. The PEP section on Filters states > that I can do what I've been trying to do with filters, but doesn't > provide enough information to do it (or, at least, I'm too thick to > guess at how it would work by looking at the API and PEP and trying a > dozen different ways). Luckily, the examples you point to from your > original package do provide enough info; log_test15.py held the key. > > I still feel like it would be more intuitive if filters were inherited > down the hierarchy instead of having to go through the extra steps of > getting at the root handler first, but I'm sure there are good reasons > for not doing this. > > One more question, is there any way to get the list of all named > loggers (from the Manager, perhaps)? Or... maybe I don't need this, > either, as MatchFilter (log_test18.py) seems to do what I was thinking > I need the list of logger names for... most excellent. > > Thanks, > Gary > > BTW, the python logging module is one of the best readily available > loggers I've come across in any language. Thanks. Glad the tests/examples (log_testxx.py) helped. When I get a chance, I will try to work some of them into the docs... Best regards, Vinay Sajip From indy90 at gmail.com Thu Jan 25 16:27:53 2007 From: indy90 at gmail.com (Indy) Date: Thu, 25 Jan 2007 23:27:53 +0200 Subject: Fwd: asyncore.dispatcher.handle_read In-Reply-To: <725281c20701251327n761a2c15ib34788b613f3932f@mail.gmail.com> References: <1169748481.260540.58640@k78g2000cwa.googlegroups.com> <725281c20701251327n761a2c15ib34788b613f3932f@mail.gmail.com> Message-ID: <725281c20701251327o7dd32093q209bcd6c29627386@mail.gmail.com> ---------- Forwarded message ---------- From: Indy Date: Jan 25, 2007 11:27 PM Subject: Re: asyncore.dispatcher.handle_read To: Jordan OK, problem fixed. Thanks anyway :-) On 25 Jan 2007 10:08:01 -0800, Jordan wrote: > That was not entirely helpful, it's way more likely a mistake you made > in subclassing dispatcher than a problem within asycore itself (that > ended up sounding a lot more mean/angry than intended, sorry ?_? ), > you really need to show us what changes you made to asyncore.dispatcher > if you want help. Good luck. > > Cheers, > Jordan > > On Jan 25, 12:18 pm, Indy wrote: > > Greetings. > > > > I am writing an asynchronous server, and I use the standard library's > > module asyncore. > > I subclass asyncore.dispatcher. handle_accept works just right, that > > is, when a client socket makes a request to connect to my server > > socket, things that I set in handle_accept definition, happen. So, it > > is OK. But, the problem is that handle_read does not work as expected. > > Things I set in handle_read definition, do not happen when a client > > socket sends me data. Why? Is this a known problem? Please, can you > > help me? > > Thanks a lot, in advance. > > > > Best regards, > > Aristotelis Mikropoulos > > > > -- > > Programs must be written for people to read, and only incidentally for > > machines to execute. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Programs must be written for people to read, and only incidentally for machines to execute. -- Programs must be written for people to read, and only incidentally for machines to execute. From horpner at yahoo.com Thu Jan 4 13:13:10 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 4 Jan 2007 19:13:10 +0100 Subject: Sorting on multiple values, some ascending, some descending References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> Message-ID: On 2007-01-04, Peter Otten <__peter__ at web.de> wrote: > Neil Cerutti wrote: >> Another trick is to factor the key application out of the >> sort. This may be a good idea if when you want to minimize the >> number of times your key function is called. >> >> The idea is to mangle the list temporarily so you can use an >> unkeyed sort, and then unmangle the sorted data. Here's a >> silly example using a phone directory that's not stored in a >> format that's easy to sort. > > No need to jump through these hoops; list.sort(key=keyfunc) > calls keyfunc() exactly once per list item: > >>>> from random import shuffle >>>> items = range(-5, 10) >>>> shuffle(items) >>>> count = 0 >>>> def key(value): > ... global count > ... count += 1 > ... return abs(value) > ... >>>> items.sort(key=key) >>>> count > 15 Thanks for the correction! That's very useful information. -- Neil Cerutti From S.Mientki-nospam at mailbox.kun.nl Wed Jan 3 14:50:54 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 03 Jan 2007 20:50:54 +0100 Subject: list/dictionary as case statement ? In-Reply-To: References: <71pmp2tq1klma5urhkfiv8bpq6u8sgtj06@4ax.com> <501r8sF1dp76aU1@mid.individual.net> Message-ID: Tom Plunket wrote: > Bjoern Schliessmann wrote: > >> Intels aren't RISC, are they? > > Not the ones in PCs. The OP didn't specify the CPU that's being used, > however. > Well it was meant for a small micro-controller, the PIC-14-series, e.g. PIC16F877. I already build a simulator for this device in Delphi, but it seemed a nice idea, and a good exercise for me, to see how this could be done in Python. And thanks to you all, I've the core (not the pheripherals) working now, and my experience with Python are very positive. The main advantages of the simulator in Python are: - very elegant and lean code - the treshold of Python is much lower (in my opinion, simulators only live when more people are involved) The main disadvantages (I think, not yet tested) - the speed is much lower - the GUI is much more complex For those who are interested, The rough code of the Python code can be seen here (I might have committed a mortal sin, by changing "self" into "S" ??) http://oase.uci.kun.nl/~mientki/download/cpu2.txt btw, as I'm a total newbie, any comment is welcome !! The Delphi simulator can be seen here http://oase.uci.kun.nl/~mientki/data_www/pic/jalss/jalss.html thanks again, for all your fast and very adequate responses !! cheers, Stef Mientki From gagsl-py at yahoo.com.ar Tue Jan 23 21:33:12 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Jan 2007 23:33:12 -0300 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <7.0.1.0.0.20070123232314.03588c40@yahoo.com.ar> At Tuesday 23/1/2007 22:50, John Nagle wrote: > The major complaint I have about Python is that the packages >which connect it to other software components all seem to have >serious problems. As long as you don't need to talk to anything >outside the Python world, you're fine. But once you do, things >go downhill. That appears to be your situation. >MySQLdb has version and platform compatibility >problems. Which, specifically? >So does M2Crypto. Both of them are third-party libraries maintained by volunteer people (and I could ask why do you menction M2Crypto specifically?) >The built-in SSL support is weak. >Even basic sockets don't quite work right; the socket module >encapsulates the timeout mechanism but doesn't get it right. I use several packages connecting to the "outside Python" world without problems. If you have these specific problems, perhaps you could try to fix them? Get funding to make them fixed? Do the funding yourself? > In the Perl, Java, PHP, and C/C++ worlds, the equivalent >functions just work. That's because, in those worlds, either the >development team for the language or the development team >for the subsystem takes responsibility for making them work. >Only Python doesn't do that. I think that it was done because *someone* was sponsoring the development (like IBM, Sun, and others). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rw at smsnet.pl Wed Jan 24 16:19:28 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 24 Jan 2007 22:19:28 +0100 Subject: module email References: Message-ID: <874pqgf7hb.fsf@smsnet.pl> "Sergey Dorofeev" writes: > Hello. > > Why does not work? [...] > m=email.message.Message() [...] > p2=email.message.Message() > p2.set_type("message/rfc822") > p2.set_payload(m) Payload is a _list_ of Message objects (is_multipart() == True) or a _string_ object (is_multipart() == False) but never just Message object. http://docs.python.org/lib/module-email.message.html -- HTH, Rob From danb_83 at yahoo.com Sat Jan 13 13:52:05 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Jan 2007 10:52:05 -0800 Subject: HTML Calendar code In-Reply-To: <0001HW.C1CED6FB000CC50DF0407648@News.Individual.DE> References: <0001HW.C1CED6FB000CC50DF0407648@News.Individual.DE> Message-ID: <1168714324.437746.272060@l53g2000cwa.googlegroups.com> On Jan 13, 11:35 am, Kajsa Anka wrote: > Before I re-invent something I would like to ask if there exists some code > that can be used for create the HTML code for a calendar which I then can > include on a web page. > > The module in the standard library can create a calendar but I would like > display my schedule. > > My idea is that it would read a simple text file and then create a weekly > calendar view (and/or a monthly) with my schedule. > > Does some the code for this exist? (the ones I found all created calendars > but doesn't seem to include any schedule) Here's most of a monthly calendar CGI script I wrote a couple of years ago. Modify it to your needs. # ------------ CONSTANTS ------------ MONTH_NAMES = (None, # Use 1-based indexing 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') DAY_NAMES = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') # ------------ DATABASE FUNCTIONS ------------ official_events = shelve.open('../data/calendar/official.shelf') unofficial_events = shelve.open('../data/calendar/unofficial.shelf') def get_events(year, month, day): key = '%04d-%02d-%02d' % (year, month, day) events = official_events.get(key, []) if common.user and common.user.permissions.calendar_u: events += unofficial_events.get(key, []) return events # ------------ CALCULATION FUNCTIONS ------------ def is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def days_in_month(month, year): if month == 2: if is_leap_year(year): return 29 else: return 28 elif month in (4, 6, 9, 11): return 30 else: return 31 # ------------ DISPLAY FUNCTIONS ------------ def get_links(year, month): "Return URLs for previous month and next month." old_year = year old_month = month - 1 if old_month == 0: old_month = 12 old_year -= 1 left_link = 'calendar.py?year=%d&month=%d' % (old_year, old_month) new_year = year new_month = month + 1 if new_month == 13: new_month = 1 new_year += 1 right_link = '?year=%d&month=%d' % (new_year, new_month) return left_link, right_link def print_navigation(year, month): prev_link, next_link = get_links(year, month) document.write('') document.write('') def print_day_names(): document.write('') for day in DAY_NAMES: document.write('%s' % day) document.write('') def print_calendar(year, month): document.write('

%s %d

' % (MONTH_NAMES[month], year)) print_navigation(year, month) document.write('') print_day_names() days = days_in_month(month, year) start_offset = (datetime.date(year, month, 1).weekday() + 1) % 7 document.write('') for i in xrange(start_offset): document.write('') else: document.write('' % day) column += 1 if column == 7 and day != days: document.write('') column = 0 for i in xrange((7 - column) % 7): document.write('
') column = start_offset for day in xrange(1, days+1): events = get_events(year, month, day) if events: document.write('') document.write(str(day)) document.write('
    ') for event in events: document.write('
  • %s
  • ' % cgi.escape(event)) document.write('
%d
') document.write('
') # ------------ MAIN PROGRAM ------------ current_date = datetime.date.today() form = cgi.FieldStorage() try: year = int(form['year'].value) except: year = current_date.year try: month = int(form['month'].value) except: month = current_date.month if month < 1 or month > 12: month = current_date.month common.print_header('Calendar') document.write_txt2tags_file('../data/text/intro_calendar') print_calendar(year, month) common.print_footer() From mclaugb at nospm.yahoo.com Sat Jan 20 19:17:50 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Sun, 21 Jan 2007 00:17:50 -0000 Subject: scipy.optimize.lbfgsb help please!!! References: Message-ID: Just to clarify--this is a multivariate algorithm. I changed the function Permmin to simply take the absolute value of (xmin, ymin) so that it returns one value. Unfortunately, the error remains--it still returns this error: " x, f, d = lbfgsb.fmin_l_bfgs_b(Permmin, x0, Jacobi, params, bounds=[(.001,100),(-50,-.001)] , maxfun=500) File "C:\Python24\lib\site-packages\scipy\optimize\lbfgsb.py", line 197, in fmin_l_bfgs_b isave, dsave) ValueError: failed to initialize intent(inout) array -- expected elsize=8 but got 4 -- input 'l' not compatible to 'd'" "Robert Kern" wrote in message news:mailman.2953.1169333789.32031.python-list at python.org... > mclaugb wrote: >> Does anyone out there have a piece of code that demonstrates the use of >> the >> lbfgsb multivariate, bounded solver in the scipy.optimize toolkit? An >> example would get me started because my code below does not seem to work. > > You will probably get better/faster/more answers on the scipy-user mailing > list. > > http://www.scipy.org/Mailing_Lists > >> Permmin is a function that simply returns a vector array [xmin, ymin] > > This is your problem. The function to minimize must return a scalar, not a > vector. This is not a multi-objective optimizer. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless > enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > From no-spam at no-spam-no-spam.invalid Wed Jan 17 16:37:54 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 17 Jan 2007 22:37:54 +0100 Subject: Making a simple script standalone In-Reply-To: <5d1084-5j7.ln1@whisper.very.softly> References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: Rikishi 42 wrote: > Hi, > I'm new to this group. I've tried finding my answer in existing messages, > but no such luck. > > What I want to do is to compile/bundle/prepare/whatever_term a simple > Python script for deployment on a Windows machine. Installing Python > itself on that machine, is not an option. Ideally I would like to obtain > a single executable file, but a script+runtime is acceptable. > > There is nothing graphical, nothing fancy about the script. > The only imports are: os, stat, string and time. > > > Any suggestions on an - easy and clear - path to follow ? > > cx_Freeze was not mentioned so far. its perhaps most easy and clear. Robert From http Mon Jan 22 16:37:04 2007 From: http (Paul Rubin) Date: 22 Jan 2007 13:37:04 -0800 Subject: AES and Credit card number encryption References: <45b5159e$0$24377$88260bb3@free.teranews.com> Message-ID: <7xy7nu4ubj.fsf@ruckus.brouhaha.com> Tobiah writes: > I browsed this subject and thought I might use the 'AES' cypher > scheme to do this. Would this be a good choice? There's more to it than that, but yes, AES is a good underlying algorithm. > So my real question is, how do I go about generating the best key. > Isn't the length supposed to be a 2^n bits, and soforth? AES key length is your choice of 128, 192, or 256 bits. In practice 128 bits (16 bytes) is fine and is what most people use. You should use 16 completely random bytes. Get these by reading them from os.urandom(16), which is provided for basically this purpose. From steve at holdenweb.com Sun Jan 28 04:51:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Jan 2007 09:51:07 +0000 Subject: Crunchy 0.8 release In-Reply-To: <1169932766.450129.259840@k78g2000cwa.googlegroups.com> References: <1169932766.450129.259840@k78g2000cwa.googlegroups.com> Message-ID: <45BC720B.5010909@holdenweb.com> Andr? wrote: > Version 0.8 of Crunchy has been released. It is available on > http://code.google.com/p/crunchy/ > > Crunchy, the Interactive Python Tutorial Maker, is an application that > transforms an ordinary html-based Python tutorial into an interactive > session within a web browser. Currently, only Firefox is supported. > Crunchy is developed and tested on Windows XP and Ubuntu Dapper Drake, > but should work on any suitable windows or UNIX system. > > Three major improvements have been made since version 0.7 had been > released. > > 1. New editor > > Instead of a simple html textarea, Crunchy now gives the option of > using a "real" editor, namely EditArea > (http://www.cdolivet.net/editarea/). EditArea support syntax coloring > and allows loading and saving local Python files among other features. > Within Crunchy, it is set up so that the tab key is translated into 4 > spaces. > > 2. Language support > > Crunchy now supports English and French, through the use of ".po" > files. When running Python code, some error messages have been > adapted/translated. EditArea itself support more languages > (currently: Danish, Dutch, English, French, German, Italian, Japanese, > Polish, Portuguese). > > 3. Graphical tutorial converter. > > Crunchy uses some supplementary markup to transform html files into > interactive tutorials. Whereas previous versions required a tutorial > maker to edit an html file "by hand", version 0.8 includes a tutorial > editor: with a few clicks, you can easily add to an html file the > chosen interactive elements and options for Crunchy. > > In addition to the above major improvements, the code has been > refactored significantly and a number of small bug fixes have been > made. Crunchy will be demonstrated at the upcoming Pycon 2007. > > Andr? Roberge and Johannes Woolard. > Very nice indeed, and a significant advance over 0.7 - I'll be trying to write Crunchy presentations myself (though possibly not as soon as PyCon). I found it a little strange that the top-level directory in the distribution is called "andre" rather than "crunchy", but that's a very minor point. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From nagle at animats.com Fri Jan 12 23:23:33 2007 From: nagle at animats.com (John Nagle) Date: Sat, 13 Jan 2007 04:23:33 GMT Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error In-Reply-To: References: <1168543799.097737.127930@i56g2000hsf.googlegroups.com> Message-ID: <99Zph.19734$yC5.6287@newssvr27.news.prodigy.net> Heikki Toivonen wrote: > John Nagle wrote: > >>def connect(self, addr): >> self.socket.connect(addr) >> self.addr = addr >> self.socket.settimeout(None) # Back to normal timeout (NEW) > > > I am not sure if this is always appropriate. In fact, doesn't this just > eliminate the timeout completely from this connection? > > In your case you could achieve what you want by calling > connection_object.socket.settimeout(4.0) method just before calling > connect, without needing to edit M2Crypto itself. No, this actually works right. It seems that the default timeout controls the timeout on TCP connect, but puts the socket into non-blocking mode. So, if as soon as a TCP connection is opened, but before the SSL handshake starts, the socket timeout is set to None, then the socket returns to blocking mode before its first read. At least on Windows. More later on how this works on Linux. John Nagle From eight02645999 at yahoo.com Fri Jan 19 23:40:24 2007 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 19 Jan 2007 20:40:24 -0800 Subject: regexp qns Message-ID: <1169268024.164643.71320@l53g2000cwa.googlegroups.com> hi suppose i have a string like test1?test2t-test3*test4*test5$test6#test7*test8 how can i construct the regexp to get test3*test4*test5 and test7*test8, ie, i want to match * and the words before and after? thanks From tjgolden at gmail.com Wed Jan 17 05:36:25 2007 From: tjgolden at gmail.com (Tim Golden) Date: 17 Jan 2007 02:36:25 -0800 Subject: Check a windows service In-Reply-To: <1168985869.099273.13630@38g2000cwa.googlegroups.com> References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> <1168967374.568967.173690@11g2000cwr.googlegroups.com> <1168985869.099273.13630@38g2000cwa.googlegroups.com> Message-ID: <1169030185.707886.229920@51g2000cwl.googlegroups.com> awel wrote: > Sorry, but could you give me an example with a real service 'cause I've > tried this script but nothings happened, no error, nothings ; even if I > launch it in cmd prompt. Well, as that example said, it was designed to show automatic services which are not running. If you don't have any then nothing will show. I assumed you could use this as a starting point. To list all services try this: import wmi c = wmi.WMI () for service in c.Win32_Service (): print service.Caption To show a specific service: import wmi c = wmi.WMI () for service in c.Win32_Service (Caption="Task Scheduler"): print service TJG From grahn+nntp at snipabacken.dyndns.org Tue Jan 9 07:07:10 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 9 Jan 2007 12:07:10 GMT Subject: Execute binary code References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> Message-ID: On 8 Jan 2007 12:29:36 -0800, olsongt at verizon.net wrote: > > citronelu at yahoo.com wrote: >> Is it possible to execute a binary string stored within a python script >> as executable code ? >> >> The script is run under Windows, and the binary code (a full executable >> file) is stored in a variable in the script. >> >> I know I can use os.system() or os.popen() to run an external file, but >> these functions take as argument a string evaluated as command-line. >> >> I also know I could save the binary code as a temporary file, execute >> it and delete it afterwards, but this is not an alternative. >> >> Thanks. > > It's not impossible, that's basically what I did on a smaller scale in > pyasm: For what it's worth[1], under Unix it /is/ impossible. The only way to bring in new code (short of dynamic libraries) is to call exec(2) or its variations, and all need a file system object to load the code from. /Jorgen [1] Not much to the OP, I'd think. -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From webmaster at cacradicalgrace.org Wed Jan 3 16:51:11 2007 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Wed, 03 Jan 2007 14:51:11 -0700 Subject: Unsubscribing from the list References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> Message-ID: Nice move, using Perl/PHP for that. It's always fun to piss people off by apologizing. ;) Cheers, Cliff Dotan Cohen wrote: > On 03/01/07, Robert Kern wrote: >> He misunderstood you (as I nearly did, too). The way you phrased >> "decided that >> there was no futher interest on the page for me" is somewhat >> ambiguous: it can >> seem like it refers to the second time, not the first. >> > > Ah. Sorry. I'm getting better at confusing people :) > > if ($you=="got_offended") { > $dotan="sorry"; > } > > Dotan Cohen > > http://what-is-what.com/what_is/website.html > http://lyricslist.com/ From S.Mientki-nospam at mailbox.kun.nl Wed Jan 17 17:46:49 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 17 Jan 2007 23:46:49 +0100 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> <1168904865.253014.210140@m58g2000cwm.googlegroups.com> <8ab5f$45ad5c12$d443bb3a$7243@news.speedlinq.nl> Message-ID: <5d831$45aea748$d443bb3a$26464@news.speedlinq.nl> hi Gabriel, > It appears that you're a number crunching guy - you absolutely ignore > all types except numeric ones! :) Is there anything else than numbers ? ;-) But indeed I forgot the else statement, which should look like this: else: line = 'UNKNOWN: ' + type(V) print line line = ' ' + V.__repr__() # do something to prevent too long output sequences print line > > >> # count the occurances of the different types >> N_int,N_float,N_complex,N_list,N_tuple,N_array,N_unknown = >> 0,0,0,0,0,0,0 > > Ouch, seven counters... your guts should be saying that this is > candidate for a more structured type... what about a dictionary indexed > by the element type? > Using a dict: > > for item in V: > t = type(item) > try: count[t] = count[t]+1 > except IndexError: count[t] = 1 Thanks very much, that's almost perfect, I only had to change IndexError into KeyError. > > > We'll replace all of this with: > > for key,value in count: > line += ' %s=%d' % (key, value) > I didn't succeed to use value as a enumerator, and I had to typecast key into a string (and skipping some redundant information, but then it works great, thanks !! here the complete listing: count = {} for item in V: t = type(item) try: count[t] += 1 except KeyError: count[t] = 1 if type(V)==list: line = 'list:' else: line = 'tuple:' for key in count: line += ' %s=%d' %('N_'+str(key)[7:-2],count[key]) print line cheers, Stef Mientki From steve at REMOVE.THIS.cybersource.com.au Sat Jan 20 22:15:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 21 Jan 2007 14:15:46 +1100 Subject: Code reformater? References: Message-ID: On Sat, 20 Jan 2007 23:51:24 -0300, Gabriel Genellina wrote: > As the indentation *is* significant in python, none of the above can > help if you lose the indentation. Try to reconstruct this: > > def foo(): > if a>0: > if b>0: > print 1 > print 2 > else: > return 3 > return 4 > > The tools may help to make the indentation consistent (tabs/8 > spaces/4 spaces/2 spaces mixed) or look better, but not to make it right. Sure -- but a heuristic that gets it right *sometimes* may still be useful, provided the user knows that the code may not be indented correctly. There are lots of legal Python blocks where the indentation CAN be reconstructed correctly, and only a relatively small proportion where it can't -- the tool could do its best, and warn the user when there are indents that can't be dealt with. Or even refuse the temptation to guess, but re-indent whatever parts of the code it is sure about. Still, it is better not to lose the indentation in the first place. -- Steven. From steve at REMOVE.THIS.cybersource.com.au Thu Jan 25 05:58:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 25 Jan 2007 21:58:43 +1100 Subject: str and __setitem__ References: Message-ID: On Thu, 25 Jan 2007 10:16:31 +0000, Tor Erik Soenvisen wrote: > Hi, > > What do I need to do to make the code below work as expected: Use another language *wink* Python strings are immutable, you can't change them in place. > class str2(str): > > def __setitem__(self, i, y): > assert type(y) is str > assert type(i) is int > assert i < len(self) > self = self[:i] + y + self[1+i:] This line rebinds a NEW string to the name "self" -- it doesn't change the contents of the original string. Because the name self is local to the method, it doesn't change references to the original string. Are you sure you need mutable strings? Here are a few different ways of getting something like a mutable string: * use the MutableString class from the UserString module; * use the mmap module; * use lists of characters instead of strings; -- Steven From gagsl-py at yahoo.com.ar Thu Jan 11 00:32:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 02:32:49 -0300 Subject: IDLE Python and Environment Variables In-Reply-To: <1168482248.828858.161320@i39g2000hsf.googlegroups.com> References: <1168482248.828858.161320@i39g2000hsf.googlegroups.com> Message-ID: <7.0.1.0.0.20070111021615.0585b8a8@yahoo.com.ar> At Wednesday 10/1/2007 23:24, Tristan wrote: >1) For almost everyone, I execute a corresponding ".bat file" into > >which I define and/or include values for some "temporal" >environment variables that let me find all the objects that the >selected application uses. Sometimes I include in the .bat file the >execution of the application, but generally I leave in a prompt status, > >ready to invoke python or some dos commands. What kind of environment variables? Those used by Python itself, like PYTHONPATH? Or your own variables, like FOO_LOCATION=C:\My\Projects\Lib\Foo >2) When I close the command prompt window, there are no traces of >my >enviroment variables in my windows system (that is right). Only the >default windows environment variables remain. > >I tried to do the same with the IDLE (and I imagine tha same occurs >with Python command line), but I have the next problem: >I can not find in IDLE (or another app?) the way to previously define >and/or include automatically values for my "temporal" environment >variables as I do in the .bat files. So you write a .bat that: - defines some variables - calls your script. It appears that your variables are some kind of configuration - in this case it has more sense to put such configuration in another place, like a config file, and forget about environment variables. You can use the usual .ini Windows format and read it with ConfigParser. You can pass your script the name of the ini file to read - this would be the equivalent of using different .bat files to call the same script. This way it doesn't matter whether you invoke your application using python command line, or inside IDLE, or inside another environment. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nagle at animats.com Mon Jan 15 12:25:17 2007 From: nagle at animats.com (John Nagle) Date: Mon, 15 Jan 2007 17:25:17 GMT Subject: How naive is Python? In-Reply-To: References: <1168848408.785931.285160@q2g2000cwa.googlegroups.com> Message-ID: <1OOqh.23485$sR.5194@newssvr29.news.prodigy.net> skip at pobox.com wrote: > John> Sorry, Skip, but I find that very hard to believe. The foo() > John> function would take quadratic time if it were merely adding on > John> pieces of constant size -- however len(str(i)) is not a constant, > John> it is O(log10(i)), so the time should be > John> super-quadratic. > > Sorry, I should have pointed out that I'm using the latest version of > Python. I believe += for strings has been optimized to simply extend s when > there is only a single reference to it. I'd heard that, but wasn't sure. That's the kind of answer I was looking for. That kind of optimization is a huge win. John Nagle From skip at pobox.com Wed Jan 31 05:52:32 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 31 Jan 2007 04:52:32 -0600 Subject: Executing Javascript, then reading value In-Reply-To: <1170222193.579676.282040@m58g2000cwm.googlegroups.com> References: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> <1170105229.984079.219180@l53g2000cwa.googlegroups.com> <1170222193.579676.282040@m58g2000cwm.googlegroups.com> Message-ID: <17856.29936.584031.754316@montanaro.dyndns.org> Melih> In fact what you're describing is exactly what I needed. I ended Melih> up finding a way to execute the javascript using Rhino and then Melih> capturing the result. Not exactly what I wanted to do, but once I Melih> found it out, it works. There is an embeddable C implementation as well: SpiderMonkey. It has both a core engine and a standalone app. There also appears to a an unmaintained Python interface: python-spidermonkey. Relevant URLs: http://www.mozilla.org/js/spidermonkey/ http://cheeseshop.python.org/pypi/python-spidermonkey/ Skip From michael at mustun.ch Wed Jan 3 11:05:19 2007 From: michael at mustun.ch (Michael) Date: Wed, 03 Jan 2007 17:05:19 +0100 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: <1167839629.435980.311750@k21g2000cwa.googlegroups.com> References: <1167839629.435980.311750@k21g2000cwa.googlegroups.com> Message-ID: Yes, I konw what you mean. And thats the right way to do it - for beginners. --But not for someone who allready know programmings things for many years. They ask themself: How can I do this in Python? I can remember, it was that-way with Perl or C or C++ or whatever. So, not only a ververter can be useful, also a translation table. (Maybe just a table for print out.) LangX <-> LangY Matimus wrote: > I don't know of a converter, one may exist. I have seen similar > requests though and will give you a similar response to what I have > seen. A converter, if it exists, may be able to produce working code > but _not_ readable code. Python is a language whose strength comes > from, among other things, its readability and conventions. Learning > python is best done by using the online documentation > (http://docs.python.org/tut/tut.html) and reading existing code (take a > look at the built in modules). > > My biggest fear of teaching someone to program by using a program to > convert perl to python is that they will end up writing python that > still looks like perl. > > I don't know if it helps, but I know others will give you similar > advice. > > -Matt > From kylotan at gmail.com Wed Jan 3 12:15:56 2007 From: kylotan at gmail.com (Ben Sizer) Date: 3 Jan 2007 09:15:56 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <459BCE85.5070707@v.loewis.de> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <1167757721.883547.70530@42g2000cwt.googlegroups.com> <459BCE85.5070707@v.loewis.de> Message-ID: <1167844551.332740.320760@s34g2000cwa.googlegroups.com> Martin v. L?wis wrote: > Ben Sizer schrieb: > > Firstly, that solution only works for actual Python scripts; it doesn't > > solve the utility scripts that are often installed to the /scripts > > directory. > > Those packages should install .bat files into /scripts on Windows. Which still need their location to be be fully qualified, due to /scripts not being in the path. This is not my experience with Linux installations of the same packages. > Please submit a patch that does so, then. Make sure you add user > interface to make it an option. > > These things are *not* easy, and claiming that they are is > misleading. I will look into it. -- Ben Sizer From kent at kentsjohnson.com Thu Jan 11 14:00:21 2007 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 11 Jan 2007 19:00:21 GMT Subject: Learning Python book, new edition? In-Reply-To: <50n9daF1g30l4U1@mid.individual.net> References: <50n9daF1g30l4U1@mid.individual.net> Message-ID: <45A68944.7020205@kentsjohnson.com> Bjoern Schliessmann wrote: > Demel, Jeff wrote: > >> Does anyone know if there's a plan in the works for a new edition >> of Learning Python? The current edition (2nd) is a few years old >> and looks like it only covers Python 2.3. > > IIRC, differences to 2.4 are in it, too. No, it is one version back from that. From the Preface to the second edition: "This edition has been thoroughly updated to reflect Python 2.2...in addition, discussion of anticipated changes in the upcoming 2.3 release have been incorporated." Kent From smusnmrNOSPAM at yahoo.com Tue Jan 9 02:58:14 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Tue, 9 Jan 2007 08:58:14 +0100 Subject: help: code formatter? References: Message-ID: Chuck wrote: > http://lacusveris.com/PythonTidy/PythonTidy.python Wow, what a giant of a program! Trying to find out how this works. Thank you, siggi "Chuck Rhode" schrieb im Newsbeitrag news:mailman.2427.1168273761.32031.python-list at python.org... > siggi wrote this on Mon, Jan 08, 2007 at 03:33:21PM +0100. My reply is > below. > >> Is there a simple code formatter that first removes all indentations >> and then refomats correctly? > > Why, yes, there is: > > http://lacusveris.com/PythonTidy/PythonTidy.python > > -- > .. Chuck Rhode, Sheboygan, WI, USA > .. 1979 Honda Goldwing GL1000 (Geraldine) > .. Weather: http://LacusVeris.com/WX > .. 26? - Wind W 17 mph > From bdesth.quelquechose at free.quelquepart.fr Tue Jan 2 18:22:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Jan 2007 00:22:35 +0100 Subject: array of class In-Reply-To: <1167777053.152492.3460@v33g2000cwv.googlegroups.com> References: <459ad4f7$0$293$426a34cc@news.free.fr> <1167777053.152492.3460@v33g2000cwv.googlegroups.com> Message-ID: <459ae31f$0$294$426a74cc@news.free.fr> George Sakkis a ?crit : > Bruno Desthuilliers wrote: > (snip) >>words = [] >>for w in ['this', 'is', 'probably', 'what', 'you', 'want']: >> words.append(Word(w)) >>print words > > Or more compactly: > > words = [Word(w) for w in 'this is probably what you want'.split()] > print words I didn't want to introduce yet some more "confusing" stuff !-) From paddy3118 at netscape.net Wed Jan 31 02:22:52 2007 From: paddy3118 at netscape.net (Paddy) Date: 30 Jan 2007 23:22:52 -0800 Subject: how to "free" an object/var ? In-Reply-To: References: Message-ID: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> On Jan 31, 6:52 am, Steven D'Aprano wrote: > On Tue, 30 Jan 2007 15:48:37 -0800, James Stroud wrote: > > Stef Mientki wrote: > >> If I create a large array of data or class, > >> how do I destroy it (when not needed anymore) ? > > >> Assign it to an empty list ? > > >> thanks, > >> Stef Mientki > > > It will be gc'd when you leave the scope or you can call del() to > > explicitly get rid of the object if its existence bothers you. > > That is not quite correct. > > big_list = ["data"]*1000000 > another_reference = big_list > del big_list > > At this point, the list of one million "data" strings still exists. > > del big_list doesn't delete the list object, it removes the name > "big_list". Then, only if the list has a reference count of zero, Python > will dispose of the object and free the memory (if your OS allows that). > If there are still references to it, like "another_reference" above, it > will not be disposed of. > > As far as I know there is no way to force the deletion of an object even > if it is in use. This is a Good Thing. > > -- > Steven D'Aprano The folowing will make the data available for garbage collection no matter what references it: >>> l = ["data"] *10 >>> l ['data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data'] >>> l2 = l >>> l[:] = [] >>> l2 [] >>> - Paddy. From gheissenberger at gmail.com Fri Jan 12 09:44:27 2007 From: gheissenberger at gmail.com (gheissenberger at gmail.com) Date: 12 Jan 2007 06:44:27 -0800 Subject: Python nuube needs Unicode help In-Reply-To: References: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> Message-ID: <1168613067.354487.40840@51g2000cwl.googlegroups.com> Can you attach files in this forum? Couldn't find the option. Oh well, here's the file. #!/usr/bin/python # Version: 1.1 # Author: Steve Losh from sets import Set from optparse import OptionParser from xml.dom.minidom import parse AudioPath = 'audio/' DatafilePath = 'utterances.trmxml' CONFIDENCE_LOW = None #'500' CONFIDENCE_HIGH = None #'500' utterancesFile = None class Utterance: def __init__(self, audio, grammarSet, text): self.audio = audio self.grammarSet = grammarSet self.text = text def __str__(self): return "SWIrecAcousticStateReset\ntranscription " + self.text \ + "\nrecognize " + AudioPath + self.audio def getGrammarPaths(): """Get the paths of all the grammars needed. Returns a Set containing the results. If a grammar is listed more than once in the transcription manifest it will only appear once in these results. TODO: Find a less fragile way to split off the server half of the URIs.""" grammarTags = utterancesFile.getElementsByTagName('Grammar') grammarURIs = [tag.getAttribute('uri') for tag in grammarTags] grammarPaths = [uri.split('servlet/CA/')[1] for uri in grammarURIs] return Set(grammarPaths) def createGrammarNameFromPath(path): """Convert a given path into an appropriate name for the grammar.""" path = path.replace('/', '-') # Strip the directory slashes path = path.replace('.', '_') # and the dot before the extension. return path def loadGrammars(): """Output the statements that will load the required grammars.""" grammarPaths = list(getGrammarPaths()) grammarsToLoad = {} for path in grammarPaths: grammarName = createGrammarNameFromPath(path) grammarsToLoad[grammarName] = "grammars/" + path for grammarName in grammarsToLoad: print "SWIrecGrammarLoad", grammarName, grammarsToLoad[grammarName] def loadGrammarSets(): """Output the statements that will define the grammar sets/contexts. Returns a list of the grammar set names.""" grammarSetList = utterancesFile.getElementsByTagName('GrammarSets') grammarSets = grammarSetList[0].getElementsByTagName('GrammarSet') grammarSetNames = [] for gs in grammarSets: grammarSetName = gs.getAttribute('id') print "context_define", grammarSetName, CONFIDENCE_LOW, CONFIDENCE_HIGH for g in gs.getElementsByTagName('Grammar'): path = g.getAttribute('uri').split('servlet/CA/')[1] print "context_add", createGrammarNameFromPath(path), '1000' print "context_end\n" grammarSetNames.append(grammarSetName) return grammarSetNames def buildUtterances(call): """This function takes a call tag, builds the utterances belonging to it and returns a list containing them.""" utts = call.getElementsByTagName('Utt') utterances = [Utterance( utt.getAttribute('audio'), \ utt.getAttribute('grammarSet'), utt.getAttribute('transcribedText') ) \ for utt in utts] return utterances def getUtterances(): """Returns a list of all the utterances we want to test.""" callList = utterancesFile.getElementsByTagName('Calls')[0] calls = callList.getElementsByTagName('Call') utterances = [] for c in calls: utterances.extend(buildUtterances(c)) return utterances def loadData(utterances): """Outputs the statements that will tell rec_test what to test.""" contexts = {} for u in utterances: if u.grammarSet not in contexts: contexts[u.grammarSet] = [] contexts[u.grammarSet].append(u) for c in contexts: print "open errors " + c + ".errors" print "open utd " + c + ".utd" print "context_use", c for u in contexts[c]: print u print "close utd" print "close errors" print "\n" def makeParser(): parser = OptionParser( "usage: %prog -l LOWER CONFIDENCE -h UPPER CONFIDENCE [-f FILTER1 -f FILTER2 ...] file" ) parser.add_option("-l", "--low-confidence", dest="lower", \ help="The lower confidence level to test at.", metavar="CONFIDENCE") parser.add_option("-u", "--upper-confidence", dest="upper", \ help="The upper confidence level to test at.", metavar="CONFIDENCE") parser.add_option("-f", "--filter", dest="filter", action="append", \ help="Only test utterances transcribed as WORD.", metavar="WORD") return parser def main(): global utterancesFile, CONFIDENCE_HIGH, CONFIDENCE_LOW parser = makeParser() (options, args) = parser.parse_args() if len(args) != 1: parser.error("One data file must be specified.") elif options.lower == None: parser.error("A lower confidence level must be specified.") elif options.upper == None: parser.error("An upper confidence level must be specified.") DatafilePath = args[0] CONFIDENCE_LOW = options.lower CONFIDENCE_HIGH = options.upper utterancesFile = parse(DatafilePath) print ':ACC\n\n' loadGrammars() print "\n\n" grammarSetNames = loadGrammarSets() utterances = getUtterances() if options.filter != None: utterances = [u for u in utterances if u.text in options.filter] print "\n\n" loadData(utterances) print "report summary summary.txt" print "report oov oov.txt" print "report words words.txt" if __name__ == '__main__': main() Peter Otten wrote: > gheissenberger at gmail.com wrote: > > > HELP! > > Guy who was here before me wrote a script to parse files in Python. > > > > Includes line: > > print u > > According to your other posts 'u' seems to be an instance of a custom > Utterance class with a __str__() method that accidentally returns unicode. > Try changing the print statement to > > print unicode(u) > > If you're lucky, it works. Otherwise we need a piece of the actual code. To > give you an idea what a self-contained demonstration of your problem might > look like: > > >>> class Utterance(object): > ... def __str__(self): return u"???" > ... > >>> u = Utterance() > >>> print u > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: > ordinal not in range(128) > >>> print unicode(u) > ??? > > Peter From mike.klaas at gmail.com Wed Jan 10 17:35:29 2007 From: mike.klaas at gmail.com (Klaas) Date: 10 Jan 2007 14:35:29 -0800 Subject: Problem installing cElementTree on Python 2.5 In-Reply-To: References: Message-ID: <1168468529.118344.254020@i39g2000hsf.googlegroups.com> Piet van Oostrum wrote: > I have just installed Python 2.5 on Mac OS X 10.4.8 on an iBook (PPC) from > the dmg. Now I tried to install cElementTree -1.0.5-20 from source (no egg > available in cheeseshop) and got the following compilation error: python2.5 ships with cElementTree: import xml.etree.cElementTree cheers, -Mike From martin at v.loewis.de Wed Jan 10 17:01:00 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 10 Jan 2007 23:01:00 +0100 Subject: dynamic library loading, missing symbols In-Reply-To: <1168458713.270248.165830@i56g2000hsf.googlegroups.com> References: <1168439928.436359.240390@i39g2000hsf.googlegroups.com> <1168458713.270248.165830@i56g2000hsf.googlegroups.com> Message-ID: <45A5621C.8090104@v.loewis.de> dfj225 at gmail.com schrieb: > I suppose this means that any subsequent libraries dlopened will not > see any of the symbols in my module? That's correct, and intentional. Python has crashed in the past when symbols conflicted across shared libraries. > I guess I'll have to look through the Python documentation to see if > they offer any work arounds to this problem. There is sys.setdlopenflags, but I would use it with caution. Regards, Martin From duncan.booth at invalid.invalid Tue Jan 30 09:43:27 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Jan 2007 14:43:27 GMT Subject: How can I know both the Key c and Ctrl on the keyboard are pressed? References: <1170147029.261981.322740@a75g2000cwd.googlegroups.com> <1170164680.123191.206630@p10g2000cwp.googlegroups.com> Message-ID: "Szabolcs Nagy" wrote: > however Ctrl+C is a special key combination: running python in a unix > terminal it raises KeyboardInterrupt exception, imho in a windows cmd > promt it raises SystemExit > Your humble opinion is wrong. Under windows Ctrl-C raises KeyboardInterrupt just as it does under linux. Ctrl-break by default terminates the program (without invoking Python's usual cleanup), but you can override that behaviour by registering a different signal handler. e.g. import signal signal.signal(signal.SIGBREAK, signal.default_int_handler) will make Ctrl-break raise KeyboardInterrupt just like Ctrl-C. From ironfroggy at gmail.com Mon Jan 15 17:50:56 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Mon, 15 Jan 2007 17:50:56 -0500 Subject: The curious behavior of integer objects In-Reply-To: References: Message-ID: <76fd5acf0701151450q2762dbcco3a2169691f0e5a94@mail.gmail.com> As it turns out, this has little to do with integers and the operations you are trying to do on them. I'll explain in more detail. Integers are immutable, which you may already know. This presents a problem with subclassing them and using the usual special method __init__, because the int object has already been created by this point and can not change. Another special method, __new__, is called passing the class object itself (foo, in this case) for the first argument (traditionally named cls, instead of self). The return of this should be an integer which will be the value of your new foo int-subclass. The following will do as you expected your own example to do. class foo(int): def __new__(cls, value): return value & 0xF assert foo(0x10) == 0 # Assertions are much better tests than prints :-) On 1/15/07, Jim B. Wilson wrote: > Am I nuts? Or only profoundly confused? I expected the this little script > to print "0": > > class foo(int): > def __init__(self, value): > self = value & 0xF > > print foo(0x10) > > Instead, it prints "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine). > > Jim Wilson > GNV, FL > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From sturlamolden at yahoo.no Tue Jan 9 06:00:43 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 9 Jan 2007 03:00:43 -0800 Subject: Why less emphasis on private data? In-Reply-To: <1168283295.899914.125400@38g2000cwa.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168283295.899914.125400@38g2000cwa.googlegroups.com> Message-ID: <1168340443.888779.176630@51g2000cwl.googlegroups.com> time.swift at gmail.com wrote: > I let the user change the internal state of the engine, I have no > assurances that my product (the engine) is doing its job... How would you proceed to protect this inner states? In C++ private members they can be accessed through a cast to void pointer. In Java it can be done through introspection. In C# it can be done through introspection or casting to void pointer in an 'unsafe' block. There is no way you can protect inner states of an object, it is just an illusion you may have. Python have properties as well. Properties has nothing to do with hiding attributes. From miki.tebeka at gmail.com Fri Jan 26 08:45:18 2007 From: miki.tebeka at gmail.com (Miki) Date: 26 Jan 2007 05:45:18 -0800 Subject: Help extracting info from HTML source .. In-Reply-To: References: Message-ID: <1169819118.201093.267320@h3g2000cwc.googlegroups.com> Hello Shelton, > I am learning Python, and have never worked with HTML. However, I would > like to write a simple script to audit my 100+ Netware servers via their web > portal. Always use the right tool, BeautilfulSoup (http://www.crummy.com/software/BeautifulSoup/) is best for web scraping (IMO). from urllib import urlopen from BeautifulSoup import BeautifulSoup html = urlopen("http://www.python.org").read() soup = BeautifulSoup(html) for link in soup("a"): print link["href"], "-->", link.contents HTH, -- Miki http://pythonwise.blogspot.com/ From joeyslistings at yahoo.com Sun Jan 7 07:48:17 2007 From: joeyslistings at yahoo.com (joeyslistings at yahoo.com) Date: 7 Jan 2007 04:48:17 -0800 Subject: I want to learn Message-ID: <1168174097.252001.71130@s80g2000cwa.googlegroups.com> Hi, I have been "programming" in the .net environment and ide for a few years and I am looking to make the switch over to python. I have absolutely no python experience whatsoever. I am looking for a python guru who has instant messenger or gtalk or whatever who can meet me online in the mornings, give me some direction for the day and then answer some questions here and there online throughout the day. This would not be time consuming on your end and if necessary I would pay you for this. Ideally you would have familiarity with c# asp.net visual studio ide ajax.net etc. so you would understand where I'm coming from. Sorry to interrupt the group but since all python gurus appear to be happily at work on the next level apps at google nobody responded to my craigslist ads. Thanks From rw at smsnet.pl Thu Jan 25 08:04:48 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 25 Jan 2007 05:04:48 -0800 Subject: module email In-Reply-To: References: <874pqgf7hb.fsf@smsnet.pl> Message-ID: <1169730288.242005.176860@v45g2000cwv.googlegroups.com> Sergey Dorofeev wrote: > "Rob Wolfe" wrote in message news:874pqgf7hb.fsf at smsnet.pl... > > >> p2=email.message.Message() > >> p2.set_type("message/rfc822") > >> p2.set_payload(m) > > > > Payload is a _list_ of Message objects (is_multipart() == True) > > or a _string_ object (is_multipart() == False) but never just Message > > object. > > 1. If I give m.as_string() into set_payload, result is the same. The payload of a message/rfc822 is treated like a sequence of length 1. So that works: p2.set_payload([m]) > 2. I don't understand, how message/rfc822 section can accept a list of two > or more messages. Can you explain? That's another question. I don't understand either, why the payload for message/rfc822 has to be a list of length 1 and not a Message object itself. This assumption looks strange to me, too, but I can live with that. :) -- Regards, Rob From gagsl-py at yahoo.com.ar Thu Jan 4 22:08:59 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 00:08:59 -0300 Subject: bug in copy.deepcopy or in getattr or in my understanding? In-Reply-To: <1167942359.246311.80700@s34g2000cwa.googlegroups.com> References: <1167942359.246311.80700@s34g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070104235152.05b017a8@yahoo.com.ar> At Thursday 4/1/2007 17:26, Emin wrote: >I got some unexpected behavior in getattr and copy.deepcopy (see >transcript below). I'm not sure if this is actually a bug in >copy.deepcopy or if I'm doing something too magical with getattr. >Comments would be appreciated. Both examples are different. #1 stores a *bound* method into an instance attribute. Bound methods carry a reference to "self", this creates a cyclic reference that may cause problems to the garbage collector (and confuses deepcopy, apparently). #2 uses and *unbound* method and it's the usual way. > >>> class a: >... def foo(self): >... print 'hi' >... > >>> class b(a): #1 >... def __init__(self): >... self.y = getattr(self,'foo') > > >>> class b(a): #2 >... def __init__(self): >... self.x = self.__class__.__bases__[0].__dict__['foo'] For #2 you can simply say: class b(a): x = a.foo If you have to choose at runtime (a simplified version of your own code): class b(a): def __init__(self): name = select_method_to_use(..., default="foo") self.x = getattr(a, name) You *know* your bases because you wrote them in the class statement (or use super() instead of playing with __bases__); and getattr works fine here so you don't need to mess with the __dict__ details. (Note that #1 was *almost* right, you had to replace self by the base class) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From chris at wavestore.com Mon Jan 29 04:47:51 2007 From: chris at wavestore.com (Christopher Mocock) Date: Mon, 29 Jan 2007 09:47:51 +0000 Subject: Handling empty form fields in CGI In-Reply-To: <1169837596.200333.94360@s48g2000cws.googlegroups.com> References: <1169837596.200333.94360@s48g2000cws.googlegroups.com> Message-ID: <45BDC2C7.9000107@wavestore.com> Paul Boddie wrote: > Try replacing this with... > > form = cgi.FieldStorage(keep_blank_values=1) > > Paul > That worked a treat. Thanks very much to both who replied. Chris. From aisaac at american.edu Sat Jan 27 18:07:08 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 27 Jan 2007 23:07:08 GMT Subject: stop script w/o exiting interpreter References: Message-ID: Please note that this post has subject "stop script w/o exiting interpreter". The object is to work at the *interactive* interpreter, without leaving it. Here is an example goal: start a Python shell, execfile a script, exit the script at line 25, and return to the Python shell. E.g., some languages include a ``stop`` statement that you can put on line 25. Ideally, I would like the equivalent of this. Solutions suggested in this thread included: - raise SystemExit but this will exit the interpreter - sys.exit() but this will exit the interpreter - use pdb's set_trace() but I think that answers a different question. (However it does work to raise BdbQuit, but I'd like something less messy.) - wrap all code in functions and test the functions but this does not apply to my current use case - use PyScripter but this is overkill for my very simple goal Note that I can just put the undefined name ``stop`` on any line I want, and the script will stop execucting at that line and will return to the interactive interpreter, as I wish. It is just that it returns with an error message, and I'd like to avoid that. Thanks, Alan Isaac From dave.dean at xilinx.com Tue Jan 2 20:57:18 2007 From: dave.dean at xilinx.com (Dave Dean) Date: Tue, 2 Jan 2007 17:57:18 -0800 Subject: Iterate through list two items at a time Message-ID: Hi all, I'm looking for a way to iterate through a list, two (or more) items at a time. Basically... myList = [1,2,3,4,5,6] I'd like to be able to pull out two items at a time - simple examples would be: Create this output: 1 2 3 4 5 6 Create this list: [(1,2), (3,4), (5,6)] I want the following syntax to work, but sadly it does not: for x,y in myList: print x, y I can do this with a simple foreach statement in tcl, and if it's easy in tcl it's probably not too hard in Python. Thanks, Dave From bborcic at gmail.com Thu Jan 25 14:13:13 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 25 Jan 2007 20:13:13 +0100 Subject: Do I need Python to run Blender correctly? In-Reply-To: <1169724703.257330.188030@v45g2000cwv.googlegroups.com> References: <1169722064.189055.61620@v45g2000cwv.googlegroups.com> <1169724703.257330.188030@v45g2000cwv.googlegroups.com> Message-ID: Hieu.D.Hoang at gmail.com wrote: > Also note that only standard modules bundled in the Blender package are > available. And extension modules e.g. numpy can't be installed into it. Not my experience, I've installed and used numpy (or was it Numeric ?) with Blender Python a couple years ago. YMMV, Boris Borcic From gagsl-py at yahoo.com.ar Fri Jan 19 10:44:59 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 12:44:59 -0300 Subject: when format strings attack References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> Message-ID: escribi? en el mensaje news:1169207467.989977.162940 at q2g2000cwa.googlegroups.com... > http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN > > I saw a warning from homeland security about this. I only comment on > the because I am trying to use os.system('command1 arg') and it doesn't > work but I do see examples with % that is borrowed from the c language. > Seems like if I can write a batch file that does something the same > behavior should happen in the os module.. Pure Python programs are not affected, but a review of the C implementation should be made to see if any (variant of) printf is used without a proper format. Anyway I doubt you could find something, because the vulnerability is so well known for ages. -- Gabriel Genellina From jfabiani at yolo.com Wed Jan 10 21:27:44 2007 From: jfabiani at yolo.com (johnf) Date: Wed, 10 Jan 2007 18:27:44 -0800 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> Message-ID: <9ihph.72$fo1.64@newsfe03.lga> Bjoern Schliessmann wrote: > Sean Davis wrote: > >> The author of one of the python database clients mentioned that >> using one thread to retrieve the data from the oracle database and >> another to insert the data into postgresql with something like a >> pipe between the two threads might make sense, keeping both IO >> streams busy. > > IMHO he's wrong. Network interaction is quite slow compared with CPU > performance, so there's no gain (maybe even overhead due to thread > management and locking stuff). That's true even on multiprocessor > machines, not only because there's almost nothing to compute but > only IO traffic. CMIIW. > > Using multiplexing, you'll get good results with simple code without > the danger of deadlocks. Have a look at asyncore (standard library) > or the Twisted framework -- personally, I prefer the latter. > > Regards, > > > Bj?rn > Sean you can't win - everyone has a different idea! You need to explain that oracle has millions of records and it's possible to a pipe open to feed the Postgres side. One thing I didn't get - is this a one time transfer or something that is going to happen often. One time transfer live to the time issue. Johnf From mccredie at gmail.com Wed Jan 3 12:14:26 2007 From: mccredie at gmail.com (Matimus) Date: 3 Jan 2007 09:14:26 -0800 Subject: code optimization (calc PI) In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> Message-ID: <1167844466.030065.303280@k21g2000cwa.googlegroups.com> Using the '+' operator for string concatonation can be slow, especially when done many times in a loop. > pi = pi + str("%04d" % int(e + d/a)) ## this should be fast?! I dont The accepted solution would be to make pi an array and append to the end... pi = [] #create the array (empty) ... ... pi.append(str("%04d"%int(e+d/a))) # append to it And when it is time to print the results do the following: print "".join(pi) It may look strange, but it is a common Python idiom. You might also look into an optimizer such as psycho: http://psyco.sourceforge.net/. From george.sakkis at gmail.com Mon Jan 22 15:13:23 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 22 Jan 2007 12:13:23 -0800 Subject: mmap caching References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <1169415139.515834.233700@a75g2000cwd.googlegroups.com> <4X7th.13145$pQ3.5671@newsread4.news.pas.earthlink.net> Message-ID: <1169496803.518305.275750@s34g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > On 21 Jan 2007 13:32:19 -0800, "George Sakkis" > declaimed the following in comp.lang.python: > > > > > The file is written once and then opened as read-only, there's no > > flushing. So if caching is completely up to the OS, I take it that my > > How large is said file? While the OS should handle swapping pages as > needed, you do have to recall that those pages are /mapped/ into the > process virtual address space. Trying to mmap a 2GB file into a process > that is already using 1GB of memory may not work (what is the default > Windows split? 2GB process and 2GB shared OS?) It's around 400MB. As I said, I cannot reproduce the MemoryError locally since I have 1GB physical space but IIRC the user who reported it had less. Actually I am less concerned about whether a MemoryError is raised or not in this case and more about the fact that even if there's no exception, the program may suffer from severe thrashing due to constant swapping. That's an issue with the specific program/algorithm rather with Python or the OS. George From bj_666 at gmx.net Wed Jan 17 04:11:40 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 17 Jan 2007 10:11:40 +0100 Subject: How can I create a linked list in Python? References: <1168983652.192715.235580@a75g2000cwd.googlegroups.com> Message-ID: In <1168983652.192715.235580 at a75g2000cwd.googlegroups.com>, bearophileHUGS wrote: > In CPython they are dynamic arrays, they aren't lists. Try adding > elements at the beginning of a list compared to adding elements at the > beginning or in the middle of a python "list" and you will see the > efficiency differences. Python has a list type without the "s, it's a real list. Don't confuse the *ADT list* with *linked lists* which are just one implementation of the ADT list. Ciao, Marc 'BlackJack' Rintsch From smusnmrNOSPAM at yahoo.com Mon Jan 15 03:54:46 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Mon, 15 Jan 2007 09:54:46 +0100 Subject: pygame and python 2.5 References: Message-ID: Thanks, I'll try that! Siggi "Laurent Pointal" schrieb im Newsbeitrag news:eo7nca$7cf$1 at upsn250.cri.u-psud.fr... > siggi a ?crit : >> Hi all, >> >> when I rtry to install pygame (pygame-1.7.1release.win32-py2.4.exe, the >> most >> ciurrent version I found) it requires Python 2.4! Will I really have to >> uninstall my Python 2.5 and install the old Python 2.4 in order to use >> pygame? > > Note: You can have both versions installed, just be sure to use the > right one when using pygame (until there is a 2.5 compatible version). > From nagle at animats.com Sun Jan 7 14:13:57 2007 From: nagle at animats.com (John Nagle) Date: Sun, 07 Jan 2007 11:13:57 -0800 Subject: Why less emphasis on private data? In-Reply-To: <1168188427.144219.206490@s80g2000cwa.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> Message-ID: <9dboh.11767$ZT3.426@newssvr19.news.prodigy.com> sturlamolden wrote: > time.swift at gmail.com wrote: > >>Coming from a C++ / C# background, the lack of emphasis on private data >>seems weird to me. I've often found wrapping private data useful to >>prevent bugs and enforce error checking.. >> >>It appears to me (perhaps wrongly) that Python prefers to leave class >>data public. What is the logic behind that choice? > > > The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that > if an object's 'internal' variables or states cannot be kept private, > programmers get an irresistible temptation to mess with them in > malicious ways. If you're not clear on encapsulation issues, you probably haven't done extensive maintenance programming on code written by others. Finding out who can mess with a variable when debugging the code of others is not fun. Because Python doesn't have explicit declarations, scope of variables is a touchy issue. If you write "x = 1" within a function, that will create a local "x" if "x" doesn't exist, or alter a global "x" if "x" was previously created in the global context. But at least global variables are local to the namespace; we don't have clashes across files. So it's not too bad. JavaScript has the convention that newly created variables are global by default. Big mistake. The underscore thing makes sense. Single underscore variables are "protected" in the C++ sense, and double underscore variables are "private", not visible from inherited classes. It's hard to misuse such variables by accident. I'd be tempted to prohibit access to underscore variables other than via "self._x" forms, so they'd be inaccessable outside the object. It's undesirable from a maintenance standpoint to have an unenforced convention like a lead underscore. The maintenance programmer can't trust its meaning. As Python grows up, and larger systems are written in it, these issues become more important. John Nagle Animats From steve at holdenweb.com Wed Jan 24 10:21:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Jan 2007 15:21:42 +0000 Subject: Thoughts on using isinstance In-Reply-To: <1169647934.219682.144390@j27g2000cwj.googlegroups.com> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> Message-ID: <45B77986.9060708@holdenweb.com> abcd wrote: >> The "Python way" is to validate by performing the operations you need to >> perform and catching any exceptions that result. In the case of your >> example, you seem to be saying that you'd rather raise your own >> exception (which, by the way, should really be a subclass of Exception, >> but we will overlook that) that relying on the interpreter to raise a >> ValueError or a TypeError. Is there really any advantage to this? You >> increase your code size and add *something* to execution time with >> little real purpose. >> >> People coming to Python after C++ or some similar language that allows >> or requires parameter type declarations often don't feel comfortable >> taking this direction to start with, but it works well for most of us. >> >> regards >> Steve > > > So instead of validating input I should just try and use the input as > if it was correct, and let python throw the errors? > Yes. This approach is often referred to as BTAFTP (better to ask forgiveness than permission), as opposed to the LBYL (look before you leap) approach that your original email inquired about. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From bignose+hates-spam at benfinney.id.au Wed Jan 17 04:27:54 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Jan 2007 20:27:54 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <740c3aec0701160837r33340866w5ddef3e09a0de537@mail.gmail.com> <873b6abp12.fsf@benfinney.id.au> <740c3aec0701170103k29c17df9xdb8c32a3a878ac00@mail.gmail.com> Message-ID: <87r6tu80kl.fsf@benfinney.id.au> "BJ?rn Lindqvist" writes: > On 1/16/07, Ben Finney wrote: > > Use the supplied value as you expect to be able to use it, and > > catch the exception (somewhere) if it doesn't work. That will > > allow *any* type that exhibits the correct behaviour, without > > needlessly restricting it to a particular inheritance. > > Can you show an example of that? It seems like that approach would > lead to some very convoluted code. Perhaps so. I don't recommend either of those approaches; I recommend, instead, separate factory functions for separate input types. -- \ "When I was crossing the border into Canada, they asked if I | `\ had any firearms with me. I said, 'Well, what do you need?'" | _o__) -- Steven Wright | Ben Finney From fred at adventistcare.org Sun Jan 21 18:54:04 2007 From: fred at adventistcare.org (Sells, Fred) Date: Sun, 21 Jan 2007 18:54:04 -0500 Subject: OpenOffice 2.0 UNO update Links; need help Message-ID: <1A4BF05172023E468CB6E867923BC90404B0CF33@accmail2.sunbelt.org> I've got a ~100 page document I assemble from ~30 OOo .odt files with some search and replace functions. I then produce a PDF. So far so good. Now I need to get a barcode from our internal website and insert that. The barcode will vary based on some parameters. Our internal site provides a .jpg image (or .gif) based on those parameters. Can anyone provide a snippet or some pointers on how to do this. I've googled it to death and checked the OOo DevGuide to no avail. Either python or java solution is acceptable. --------------------------------------------------------------------------- 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 john.pythonlist at gmail.com Wed Jan 24 20:06:56 2007 From: john.pythonlist at gmail.com (john g) Date: Wed, 24 Jan 2007 20:06:56 -0500 Subject: memory leak Message-ID: i have a memory leak issue with extension function that im working on. it reads data from a binary file into a stl vector then creates a new list to pass back to the python interface. the function works the first 1021 times but then gives a segmentation fault (core dumped). heres the business part of the code: //read data vector data; float temp; for(int x=0;x From sigzero at gmail.com Sun Jan 21 16:35:58 2007 From: sigzero at gmail.com (Robert Hicks) Date: 21 Jan 2007 13:35:58 -0800 Subject: Beginners Tutorial in PDF Format? In-Reply-To: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net> References: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net> Message-ID: <1169415358.277431.130640@s34g2000cwa.googlegroups.com> W. Watson wrote: > I'd like to print a tutorial in one fell swoop, but it seems most on the > various sites are page by page embedded descriptions in the page. Any > available as a pdf? > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Two laws Newton and Einstein didn't discover: > 1. Time is money. > 2. Matter will be damaged in direct proportion > to its value. > -- > Web Page: http://docs.python.org/download.html http://www.diveintopython.org/ HTH Robert From timr at probo.com Mon Jan 1 01:33:04 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 01 Jan 2007 06:33:04 GMT Subject: Easiest way to print from XP/DOS. References: Message-ID: jim-on-linux wrote: > >Thanks, >The client is in a one printer office. If the >output file is opened with note and then sent to >the printer everything is fine but it defeats the >purpose of the utility. Also tried > lpt1 but >the same results. Is it a USB printer? Remember that "prn" and "lpt1" refer to the first parallel port, not necessarily the first printer. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From justinjohnson at gmail.com Wed Jan 10 10:29:12 2007 From: justinjohnson at gmail.com (Justin Johnson) Date: 10 Jan 2007 07:29:12 -0800 Subject: Building Python 2.5.0 on AIX 5.3 - Undefined symbol: .__floor Message-ID: <1168442952.063392.225160@p59g2000hsd.googlegroups.com> Hello, I'm trying to build Python 2.5.0 on AIX 5.3 using IBM's compiler (VisualAge C++ Professional / C for AIX Compiler, Version 6). I run configure and make, but makes fails with undefined symbols. See the output from configure and make below. svnadm /svn/build/python-2.5.0>env CC=cc CXX=xlC ./configure --prefix=$base_dir \ > --disable-ipv6 \ > --enable-shared=yes \ > --enable-static=no checking MACHDEP... aix5 checking EXTRAPLATDIR... checking for --without-gcc... checking for gcc... cc_r checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... no checking whether cc_r accepts -g... yes checking for cc_r option to accept ANSI C... none needed checking for --with-cxx-main=... no checking how to run the C preprocessor... cc_r -E checking for egrep... grep -E checking for AIX... yes checking for --with-suffix... checking for case-insensitive build directory... no checking LIBRARY... libpython$(VERSION).a checking LINKCC... $(srcdir)/Modules/makexp_aix Modules/python.exp . $(LIBRARY); $(PURIFY) $(MAINCC) checking for --enable-shared... yes checking for --enable-profiling... checking LDLIBRARY... libpython$(VERSION).a checking for ranlib... ranlib checking for ar... ar checking for svnversion... found checking for a BSD-compatible install... ./install-sh -c checking for --with-pydebug... no checking whether cc_r accepts -OPT:Olimit=0... no checking whether cc_r accepts -Olimit 1500... no checking whether pthreads are available without options... yes checking whether xlC also accepts flags for thread support... no checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking asm/types.h usability... no checking asm/types.h presence... no checking for asm/types.h... no checking conio.h usability... no checking conio.h presence... no checking for conio.h... no checking curses.h usability... yes checking curses.h presence... yes checking for curses.h... yes checking direct.h usability... no checking direct.h presence... no checking for direct.h... no checking dlfcn.h usability... yes checking dlfcn.h presence... yes checking for dlfcn.h... yes checking errno.h usability... yes checking errno.h presence... yes checking for errno.h... yes checking fcntl.h usability... yes checking fcntl.h presence... yes checking for fcntl.h... yes checking grp.h usability... yes checking grp.h presence... yes checking for grp.h... yes checking shadow.h usability... no checking shadow.h presence... no checking for shadow.h... no checking io.h usability... no checking io.h presence... no checking for io.h... no checking langinfo.h usability... yes checking langinfo.h presence... yes checking for langinfo.h... yes checking libintl.h usability... no checking libintl.h presence... no checking for libintl.h... no checking ncurses.h usability... no checking ncurses.h presence... no checking for ncurses.h... no checking poll.h usability... yes checking poll.h presence... yes checking for poll.h... yes checking process.h usability... no checking process.h presence... no checking for process.h... no checking pthread.h usability... yes checking pthread.h presence... yes checking for pthread.h... yes checking signal.h usability... yes checking signal.h presence... yes checking for signal.h... yes checking stropts.h usability... yes checking stropts.h presence... yes checking for stropts.h... yes checking termios.h usability... yes checking termios.h presence... yes checking for termios.h... yes checking thread.h usability... yes checking thread.h presence... yes checking for thread.h... yes checking for unistd.h... (cached) yes checking utime.h usability... yes checking utime.h presence... yes checking for utime.h... yes checking sys/audioio.h usability... no checking sys/audioio.h presence... no checking for sys/audioio.h... no checking sys/bsdtty.h usability... no checking sys/bsdtty.h presence... no checking for sys/bsdtty.h... no checking sys/file.h usability... yes checking sys/file.h presence... yes checking for sys/file.h... yes checking sys/loadavg.h usability... no checking sys/loadavg.h presence... no checking for sys/loadavg.h... no checking sys/lock.h usability... yes checking sys/lock.h presence... yes checking for sys/lock.h... yes checking sys/mkdev.h usability... no checking sys/mkdev.h presence... no checking for sys/mkdev.h... no checking sys/modem.h usability... no checking sys/modem.h presence... no checking for sys/modem.h... no checking sys/param.h usability... yes checking sys/param.h presence... yes checking for sys/param.h... yes checking sys/poll.h usability... yes checking sys/poll.h presence... yes checking for sys/poll.h... yes checking sys/select.h usability... yes checking sys/select.h presence... yes checking for sys/select.h... yes checking sys/socket.h usability... yes checking sys/socket.h presence... yes checking for sys/socket.h... yes checking sys/statvfs.h usability... yes checking sys/statvfs.h presence... yes checking for sys/statvfs.h... yes checking for sys/stat.h... (cached) yes checking sys/time.h usability... yes checking sys/time.h presence... yes checking for sys/time.h... yes checking sys/times.h usability... yes checking sys/times.h presence... yes checking for sys/times.h... yes checking for sys/types.h... (cached) yes checking sys/un.h usability... yes checking sys/un.h presence... yes checking for sys/un.h... yes checking sys/utsname.h usability... yes checking sys/utsname.h presence... yes checking for sys/utsname.h... yes checking sys/wait.h usability... yes checking sys/wait.h presence... yes checking for sys/wait.h... yes checking pty.h usability... no checking pty.h presence... no checking for pty.h... no checking libutil.h usability... no checking libutil.h presence... no checking for libutil.h... no checking sys/resource.h usability... yes checking sys/resource.h presence... yes checking for sys/resource.h... yes checking netpacket/packet.h usability... no checking netpacket/packet.h presence... no checking for netpacket/packet.h... no checking sysexits.h usability... yes checking sysexits.h presence... yes checking for sysexits.h... yes checking bluetooth.h usability... no checking bluetooth.h presence... no checking for bluetooth.h... no checking bluetooth/bluetooth.h usability... no checking bluetooth/bluetooth.h presence... no checking for bluetooth/bluetooth.h... no checking for dirent.h that defines DIR... yes checking for library containing opendir... none required checking whether sys/types.h defines makedev... no checking for sys/mkdev.h... (cached) no checking sys/sysmacros.h usability... yes checking sys/sysmacros.h presence... yes checking for sys/sysmacros.h... yes checking for term.h... yes checking for linux/netlink.h... no checking for clock_t in time.h... yes checking for makedev... no checking Solaris LFS bug... no checking for mode_t... yes checking for off_t... yes checking for pid_t... yes checking return type of signal handlers... void checking for size_t... yes checking for uid_t in sys/types.h... yes checking for ssize_t... yes checking for int... yes checking size of int... 4 checking for long... yes checking size of long... 4 checking for void *... yes checking size of void *... 4 checking for short... yes checking size of short... 2 checking for float... yes checking size of float... 4 checking for double... yes checking size of double... 8 checking for fpos_t... yes checking size of fpos_t... 4 checking for size_t... (cached) yes checking size of size_t... 4 checking for long long support... yes checking for long long... yes checking size of long long... 8 checking for uintptr_t support... no checking size of off_t... 4 checking whether to enable large file support... no checking size of time_t... 4 checking for pthread_t... yes checking size of pthread_t... 4 checking for --enable-toolbox-glue... no checking for --enable-framework... no checking for dyld... no checking SO... .so checking LDSHARED... $(BINLIBDEST)/config/ld_so_aix $(CC) -bI:$(BINLIBDEST)/config/python.exp checking CCSHARED... checking LINKFORSHARED... -Wl,-bE:Modules/python.exp -lld checking CFLAGSFORSHARED... checking SHLIBS... $(LIBS) checking for dlopen in -ldl... yes checking for shl_load in -ldld... no checking for library containing sem_init... none required checking for textdomain in -lintl... yes checking for genuine AIX C++ extensions support... no checking for t_open in -lnsl... no checking for socket in -lsocket... no checking for --with-libs... no checking for --with-system-ffi... no checking for --with-signal-module... yes checking for --with-dec-threads... no checking for --with-threads... yes checking if PTHREAD_SCOPE_SYSTEM is supported... yes checking for pthread_sigmask... yes checking if --enable-ipv6 is specified... no checking for --with-doc-strings... yes checking for --with-tsc... no checking for --with-pymalloc... yes checking for --with-wctype-functions... no checking for dlopen... yes checking DYNLOADFILE... dynload_shlib.o checking MACHDEP_OBJS... MACHDEP_OBJS checking for alarm... yes checking for bind_textdomain_codeset... no checking for chown... yes checking for clock... yes checking for confstr... yes checking for ctermid... yes checking for execv... yes checking for fork... yes checking for fpathconf... yes checking for ftime... yes checking for ftruncate... yes checking for gai_strerror... yes checking for getgroups... yes checking for getlogin... yes checking for getloadavg... no checking for getpeername... yes checking for getpgid... yes checking for getpid... yes checking for getpriority... yes checking for getpwent... yes checking for getspnam... no checking for getspent... no checking for getsid... yes checking for getwd... yes checking for kill... yes checking for killpg... yes checking for lchown... yes checking for lstat... yes checking for mkfifo... yes checking for mknod... yes checking for mktime... yes checking for mremap... no checking for nice... yes checking for pathconf... yes checking for pause... yes checking for plock... yes checking for poll... yes checking for pthread_init... yes checking for putenv... yes checking for readlink... yes checking for realpath... yes checking for select... yes checking for setegid... yes checking for seteuid... yes checking for setgid... yes checking for setlocale... yes checking for setregid... yes checking for setreuid... yes checking for setsid... yes checking for setpgid... yes checking for setpgrp... yes checking for setuid... yes checking for setvbuf... yes checking for snprintf... yes checking for sigaction... yes checking for siginterrupt... yes checking for sigrelse... yes checking for strftime... yes checking for sysconf... yes checking for tcgetpgrp... yes checking for tcsetpgrp... yes checking for tempnam... yes checking for timegm... no checking for times... yes checking for tmpfile... yes checking for tmpnam... yes checking for tmpnam_r... no checking for truncate... yes checking for uname... yes checking for unsetenv... yes checking for utimes... yes checking for waitpid... yes checking for wait3... yes checking for wait4... yes checking for wcscoll... yes checking for _getpty... no checking for chroot... yes checking for link... yes checking for symlink... yes checking for fchdir... yes checking for fsync... yes checking for fdatasync... yes checking for ctermid_r... no checking for flock... no checking for getpagesize... yes checking for true... true checking for inet_aton in -lc... yes checking for inflateCopy in -lz... yes checking for hstrerror... no checking for inet_aton... yes checking for inet_pton... yes checking for setgroups... yes checking for openpty... no checking for openpty in -lutil... no checking for openpty in -lbsd... no checking for forkpty... no checking for forkpty in -lutil... no checking for forkpty in -lbsd... no checking for fseek64... no checking for fseeko... yes checking for fstatvfs... yes checking for ftell64... no checking for ftello... yes checking for statvfs... yes checking for dup2... yes checking for getcwd... yes checking for strdup... yes checking for strerror... yes checking for memmove... yes checking for getpgrp... yes checking for setpgrp... (cached) yes checking for gettimeofday... yes checking for major... yes checking for getaddrinfo... yes checking getaddrinfo bug... buggy checking for getnameinfo... yes checking whether time.h and sys/time.h may both be included... yes checking whether struct tm is in sys/time.h or time.h... time.h checking for struct tm.tm_zone... no checking for tzname... yes checking for struct stat.st_rdev... yes checking for struct stat.st_blksize... yes checking for struct stat.st_flags... no checking for struct stat.st_gen... yes checking for struct stat.st_birthtime... no checking for struct stat.st_blocks... yes checking for time.h that defines altzone... no checking whether sys/select.h and sys/time.h may both be included... yes checking for addrinfo... yes checking for sockaddr_storage... yes checking whether char is unsigned... yes checking for an ANSI C-conforming const... yes checking for working volatile... yes checking for working signed char... yes checking for prototypes... yes checking for variable length prototypes and stdarg.h... yes checking for socketpair... yes checking if sockaddr has sa_len member... yes checking whether va_list is an array... no checking for gethostbyname_r... yes checking gethostbyname_r with 6 args... no checking gethostbyname_r with 5 args... no checking gethostbyname_r with 3 args... yes checking for __fpu_control... no checking for __fpu_control in -lieee... no checking for --with-fpectl... no checking for --with-libm=STRING... default LIBM="-lm" checking for --with-libc=STRING... default LIBC="" checking for hypot... yes checking wchar.h usability... yes checking wchar.h presence... yes checking for wchar.h... yes checking for wchar_t... yes checking size of wchar_t... 2 checking for UCS-4 tcl... no checking whether wchar_t is signed... no checking what type to use for unicode... wchar_t checking whether byte ordering is bigendian... yes checking whether right shift extends the sign bit... yes checking for getc_unlocked() and friends... yes checking for readline in -lreadline... yes checking for rl_callback_handler_install in -lreadline... yes checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... yes checking for broken nice()... no checking for broken poll()... no checking for struct tm.tm_zone... (cached) no checking for tzname... (cached) yes checking for working tzset()... yes checking for tv_nsec in struct stat... no checking for tv_nsec2 in struct stat... no checking whether mvwdelch is an expression... yes checking whether WINDOW has _flags... yes checking for is_term_resized... no checking for resize_term... no checking for resizeterm... no checking for /dev/ptmx... no checking for /dev/ptc... yes checking for %zd printf() format support... yes checking for socklen_t... yes checking for build directories... done configure: creating ./config.status config.status: creating Makefile.pre config.status: creating Modules/Setup.config config.status: creating pyconfig.h config.status: pyconfig.h is unchanged creating Modules/Setup creating Modules/Setup.local creating Makefile svnadm /svn/build/python-2.5.0>make cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Modules/python.o ./Modules/python.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Modules/_typesmodule.o Modules/_typesmodule.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/acceler.o Parser/acceler.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/grammar1.o Parser/grammar1.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/listnode.o Parser/listnode.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/node.o Parser/node.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/parser.o Parser/parser.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/parsetok.o Parser/parsetok.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/bitset.o Parser/bitset.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/metagrammar.o Parser/metagrammar.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/firstsets.o Parser/firstsets.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/grammar.o Parser/grammar.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/pgen.o Parser/pgen.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/myreadline.o Parser/myreadline.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/tokenizer.o Parser/tokenizer.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/abstract.o Objects/abstract.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/boolobject.o Objects/boolobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/bufferobject.o Objects/bufferobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/cellobject.o Objects/cellobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/classobject.o Objects/classobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/cobject.o Objects/cobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/codeobject.o Objects/codeobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/complexobject.o Objects/complexobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/descrobject.o Objects/descrobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/enumobject.o Objects/enumobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/exceptions.o Objects/exceptions.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/genobject.o Objects/genobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/fileobject.o Objects/fileobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/floatobject.o Objects/floatobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/frameobject.o Objects/frameobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/funcobject.o Objects/funcobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/intobject.o Objects/intobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/iterobject.o Objects/iterobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/listobject.o Objects/listobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/longobject.o Objects/longobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/dictobject.o Objects/dictobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/methodobject.o Objects/methodobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/moduleobject.o Objects/moduleobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/object.o Objects/object.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/obmalloc.o Objects/obmalloc.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/rangeobject.o Objects/rangeobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/setobject.o Objects/setobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/sliceobject.o Objects/sliceobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/stringobject.o Objects/stringobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/structseq.o Objects/structseq.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/tupleobject.o Objects/tupleobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/typeobject.o Objects/typeobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/weakrefobject.o Objects/weakrefobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/unicodeobject.o Objects/unicodeobject.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Objects/unicodectype.o Objects/unicodectype.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/Python-ast.o Python/Python-ast.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/asdl.o Python/asdl.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/ast.o Python/ast.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/bltinmodule.o Python/bltinmodule.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/ceval.o Python/ceval.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/mysnprintf.o Python/mysnprintf.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/tokenizer_pgen.o Parser/tokenizer_pgen.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/printgrammar.o Parser/printgrammar.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Parser/pgenmain.o Parser/pgenmain.c cc_r -DNDEBUG -O Parser/acceler.o Parser/grammar1.o Parser/listnode.o Parser/node.o Parser/parser.o Parser/parsetok.o Parser/bitset.o Parser/metagrammar.o Parser/firstsets.o Parser/grammar.o Parser/pgen.o Objects/obmalloc.o Python/mysnprintf.o Parser/tokenizer_pgen.o Parser/printgrammar.o Parser/pgenmain.o -ldl -o Parser/pgen Parser/pgen ./Grammar/Grammar ./Include/graminit.h ./Python/graminit.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/compile.o Python/compile.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/codecs.o Python/codecs.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/errors.o Python/errors.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/frozen.o Python/frozen.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/frozenmain.o Python/frozenmain.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/future.o Python/future.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/getargs.o Python/getargs.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/getcompiler.o Python/getcompiler.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/getcopyright.o Python/getcopyright.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/getmtime.o Python/getmtime.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -DPLATFORM='"aix5"' -o Python/getplatform.o ./Python/getplatform.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/getversion.o Python/getversion.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/graminit.o Python/graminit.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/import.o Python/import.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -I. -o Python/importdl.o ./Python/importdl.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/marshal.o Python/marshal.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/modsupport.o Python/modsupport.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/mystrtoul.o Python/mystrtoul.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/pyarena.o Python/pyarena.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/pyfpe.o Python/pyfpe.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/pystate.o Python/pystate.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/pythonrun.o Python/pythonrun.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/structmember.o Python/structmember.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/symtable.o Python/symtable.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/sysmodule.o Python/sysmodule.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/traceback.o Python/traceback.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/getopt.o Python/getopt.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/pystrtod.o Python/pystrtod.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/dynload_shlib.o Python/dynload_shlib.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/thread.o Python/thread.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Modules/config.o Modules/config.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -DPYTHONPATH='":plat-aix5:lib-tk"' \ -DPREFIX='"/svn"' \ -DEXEC_PREFIX='"/svn"' \ -DVERSION='"2.5"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Modules/main.o Modules/main.c cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Modules/gcmodule.o Modules/gcmodule.c cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/threadmodule.c -o Modules/threadmodule.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/signalmodule.c -o Modules/signalmodule.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/posixmodule.c -o Modules/posixmodule.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/errnomodule.c -o Modules/errnomodule.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/pwdmodule.c -o Modules/pwdmodule.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/_sre.c -o Modules/_sre.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/_codecsmodule.c -o Modules/_codecsmodule.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/zipimport.c -o Modules/zipimport.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/symtablemodule.c -o Modules/symtablemodule.o cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c ./Modules/xxsubtype.c -o Modules/xxsubtype.o cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -DSVNVERSION=\"`LANG=C svnversion .`\" -o Modules/getbuildinfo.o ./Modules/getbuildinfo.c rm -f libpython2.5.a ar cr libpython2.5.a Modules/getbuildinfo.o ar cr libpython2.5.a Modules/_typesmodule.o ar cr libpython2.5.a Parser/acceler.o Parser/grammar1.o Parser/listnode.o Parser/node.o Parser/parser.o Parser/parsetok.o Parser/bitset.o Parser/metagrammar.o Parser/firstsets.o Parser/grammar.o Parser/pgen.o Parser/myreadline.o Parser/tokenizer.o ar cr libpython2.5.a Objects/abstract.o Objects/boolobject.o Objects/bufferobject.o Objects/cellobject.o Objects/classobject.o Objects/cobject.o Objects/codeobject.o Objects/complexobject.o Objects/descrobject.o Objects/enumobject.o Objects/exceptions.o Objects/genobject.o Objects/fileobject.o Objects/floatobject.o Objects/frameobject.o Objects/funcobject.o Objects/intobject.o Objects/iterobject.o Objects/listobject.o Objects/longobject.o Objects/dictobject.o Objects/methodobject.o Objects/moduleobject.o Objects/object.o Objects/obmalloc.o Objects/rangeobject.o Objects/setobject.o Objects/sliceobject.o Objects/stringobject.o Objects/structseq.o Objects/tupleobject.o Objects/typeobject.o Objects/weakrefobject.o Objects/unicodeobject.o Objects/unicodectype.o ar cr libpython2.5.a Python/Python-ast.o Python/asdl.o Python/ast.o Python/bltinmodule.o Python/ceval.o Python/compile.o Python/codecs.o Python/errors.o Python/frozen.o Python/frozenmain.o Python/future.o Python/getargs.o Python/getcompiler.o Python/getcopyright.o Python/getmtime.o Python/getplatform.o Python/getversion.o Python/graminit.o Python/import.o Python/importdl.o Python/marshal.o Python/modsupport.o Python/mystrtoul.o Python/mysnprintf.o Python/pyarena.o Python/pyfpe.o Python/pystate.o Python/pythonrun.o Python/structmember.o Python/symtable.o Python/sysmodule.o Python/traceback.o Python/getopt.o Python/pystrtod.o Python/dynload_shlib.o Python/thread.o ar cr libpython2.5.a Modules/config.o Modules/getpath.o Modules/main.o Modules/gcmodule.o ar cr libpython2.5.a Modules/threadmodule.o Modules/signalmodule.o Modules/posixmodule.o Modules/errnomodule.o Modules/pwdmodule.o Modules/_sre.o Modules/_codecsmodule.o Modules/zipimport.o Modules/symtablemodule.o Modules/xxsubtype.o ranlib libpython2.5.a ./Modules/makexp_aix Modules/python.exp . libpython2.5.a; cc_r -Wl,-bE:Modules/python.exp -lld -o python \ Modules/python.o \ libpython2.5.a -ldl -lm ld: 0711-317 ERROR: Undefined symbol: .__floor ld: 0711-317 ERROR: Undefined symbol: .__ceil ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. make: *** [python] Error 8 svnadm /svn/build/python-2.5.0> I ran the last line again adding the -bloadmap option. The results of this are below. (ld): halt 4 (ld): setfflag 4 (ld): savename python (ld): filelist 9 2 (ld): i /lib/crt0.o (ld): lib /usr/lib/libld.a (ld): i Modules/python.o (ld): i libpython2.5.a (ld): lib /usr/lib/libdl.a (ld): lib /usr/lib/libm.a (ld): lib /usr/lib/libxlopt.a (ld): lib /usr/lib/libpthreads.a (ld): lib /usr/lib/threads/libc.a LIBRARY: Shared object libdl.a[shr.o]: 4 symbols imported. LIBRARY: Shared object libpthreads.a[shr_comm.o]: 173 symbols imported. LIBRARY: Shared object libpthreads.a[shr_xpg5.o]: 152 symbols imported. LIBRARY: Shared object libc.a[shr.o]: 2800 symbols imported. LIBRARY: Shared object libc.a[meth.o]: 2 symbols imported. LIBRARY: Shared object libc.a[posix_aio.o]: 20 symbols imported. LIBRARY: Shared object libc.a[aio.o]: 14 symbols imported. LIBRARY: Shared object libc.a[pse.o]: 5 symbols imported. LIBRARY: Shared object libc.a[dl.o]: 4 symbols imported. LIBRARY: Shared object libc.a[pty.o]: 1 symbols imported. FILELIST: Number of previously inserted files processed: 9 (ld): exports Modules/python.exp EXPORTS: Symbols exported: 1034 (ld): resolve RESOLVE: 5597 of 15450 symbols were kept. (ld): addgl /usr/lib/glink.o ADDGL: Glink code added for 178 symbols. (ld): er full ld: 0711-318 ERROR: Undefined symbols were found. The following symbols are in error: Symbol Inpndx TY CL Source-File(Object-File) OR Import-File{Shared-object} RLD: Address Section Rld-type Referencing Symbol ---------------------------------------------------------------------------------------------- .__floor [392] ER PR Objects/floatobject.c(libpython2.5.a[floatobject.o]) 00000b80 .text R_RBR [38] <.float_pow> 00000c28 .text R_RBR [38] <.float_pow> 00000ff4 .text R_RBR [42] <.float_divmod> .__floor [404] ER PR Objects/complexobject.c(libpython2.5.a[complexobject.o]) 0000179c .text R_RBR [42] <.complex_divmod> 00001a2c .text R_RBR [44] <.complex_remainder> .__floor [552] ER PR Python/bltinmodule.c(libpython2.5.a[bltinmodule.o]) 00000bec .text R_RBR [24] <.builtin_round> .__ceil [554] ER PR Python/bltinmodule.c(libpython2.5.a[bltinmodule.o]) 00000c2c .text R_RBR [24] <.builtin_round> ER: The return code is 8. I noticed the following in /usr/include/math.h, but am not sure how this relates. #ifdef __IBMC__ #if (__xlC__ >= 0x0600) /* VAC version 6 and above */ #define floor(__x) __floor(__x) #define ceil(__x) __ceil(__x) #endif /* __xlC__ >= 0x0600 */ #endif /* __IBMC__ */ Does anyone know what I am doing wrong here. Any help is appreciated. Justin From webraviteja at gmail.com Thu Jan 25 05:35:57 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 25 Jan 2007 02:35:57 -0800 Subject: While loop with "or"? Please help! In-Reply-To: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> Message-ID: <1169721357.871001.262810@v33g2000cwv.googlegroups.com> > while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM Correct way: while usrinp != "y" or usrinp != "Y" or usrinp != "N" or usrinp != "n": There has to be a boolean evaluation on both sides of or. Or in this case: while usrinp not in ['Y', 'y', 'N', 'n']: Ravi Teja. From nospam.notospam at gmail.com Sat Jan 20 02:58:28 2007 From: nospam.notospam at gmail.com (Drew) Date: 19 Jan 2007 23:58:28 -0800 Subject: multiple file deletes using ftp.delete In-Reply-To: <1169277378.015620.208910@51g2000cwl.googlegroups.com> References: <1169277378.015620.208910@51g2000cwl.googlegroups.com> Message-ID: <1169279908.415360.175580@q2g2000cwa.googlegroups.com> On Jan 19, 11:16 pm, "Drew" wrote: > Hi all > I'm fairly new to python so please forgive my lack of comprehension of > the obvious. > > I'm writing a script to ftp files to a server. This script will run > weekly. Part of the script first deletes the previous weeks files. The > problem is I'm never sure of the exact number and full name of the > files that need to be deleted. All the files start with the same string > but have different extensions (eg drew.1 drew.2 drew.tmp drew.hlp). So > I was wondering if anybody knows how to use a wild card similar to * in > UNIX to do the delete? Something like: > > ftp.delete("drew.*") > > Any help or suggestions would be greatly appreciated. > > Drew Dowling I should have summed if up thus: I'm trying to find a way to issue the ftp mdelete command in python. From tjreedy at udel.edu Wed Jan 17 03:08:40 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Jan 2007 03:08:40 -0500 Subject: How can i eval subindex on list[ ][ ] ? References: <1168988937.512029.192800@q2g2000cwa.googlegroups.com> Message-ID: "James Stroud" wrote in message news:eojnn5$1vo$1 at zinnia.noc.ucla.edu... | jairodsl wrote: | > Excuse me, i was trying in too many ways but i couldnt access subindex | > on a list , the problem is the next: | > | > I have | > | > indif=[[0,'A'],[1,'B'],[2,'C'],[3,'D']] | > | > and | > | > indic=[[0,'B'],[1,'C'],[2,'D'],[3,'E']] | > | > i need to eval if indic[i][j] is equal to indif[i][j] | > | > I used a double for but i had got "list index out of range". How can i | > do ??? | > | > Thanks a lot, | > | > Cordially, | > | > jDSL | > | | py> i = 1 | py> j = 0 | py> indif[i][j] == indic[i][j] | True Or, if you mean for every i and j, just indif == indic and let the types equality method do the work for you. From kernel1983 at gmail.com Tue Jan 16 23:34:23 2007 From: kernel1983 at gmail.com (kernel1983) Date: 16 Jan 2007 20:34:23 -0800 Subject: How can I write code using FP In-Reply-To: References: <1169003899.592015.300290@s34g2000cwa.googlegroups.com> Message-ID: <1169008463.722222.289130@q2g2000cwa.googlegroups.com> yeah! that's easy! althought no so clear a = lambda x,y:(x,y) b = lambda y:a(1,y) a(1,2) (1,2) b(2) (1,2) On 1?17?, ??12?10?, Alejandro Dubrovsky wrote: > kernel1983 wrote: > > In Function Program?Language can use like this: > > > define a function: > > f = lambda x,y:x,y > > > then we use f to define another function: > > f2 = f(1) > > the f2 should equal to: > > f2=lambda y:1,y > > > we should be able call f2 with one parameter:f2(2) > > just return 1,2 > > > but how can I implement the characteristic in Python??I think it could > > do like this but HOW-TO?If you are using python 2.5, then you can use functools.partial, otherwise > lookup one of the many curry implementations, like the ones found inhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 > > One found in the comments of that page by Scott David Daniels: > > def curry(*args, **kwargs): > function, args = args[0], args[1:] > def result(*rest, **kwrest): > combined = kwargs.copy() > combined.update(kwrest) > return function(*args + rest, **combined) > return result > > so, in your case: > > f = lambda x,y: (x,y) > f2 = functools.partial(f,1)>>> f2(3)1,3 From Sardaukary at gmail.com Mon Jan 8 07:53:54 2007 From: Sardaukary at gmail.com (Sardaukary at gmail.com) Date: 8 Jan 2007 04:53:54 -0800 Subject: General Question About Python In-Reply-To: <1168254451.098796.144790@42g2000cwt.googlegroups.com> References: <1168254451.098796.144790@42g2000cwt.googlegroups.com> Message-ID: <1168260834.183457.183520@51g2000cwl.googlegroups.com> Enteng wrote: > To those who program in python, what programs do you do? > Also what community projects are you involved in(OSS probably)? > Will mastering the language land me a job? > > I'm thinking about learning the language as a hobby. Just curious :) If you have any programming experience you'll be able to pick up Python in an afternoon. It's a very easy language to learn and you'll be writing useful programs in no time. Sadly I doubt learning it alone will land you a job (which is why I forced myself to learn Java C++ and even PHP), but once you do have that job, there's a 90% chance Python will help you get things done in that job. It's just a really fun and useful language with a huge amount of well written libraries. Check out www.pythonchallenge.com when you know the basics, but be warned it's quite addictive! From ximolistas at yahoo.es Thu Jan 18 14:53:35 2007 From: ximolistas at yahoo.es (Ximo Nadal) Date: Thu, 18 Jan 2007 20:53:35 +0100 Subject: Python Web Frameworks In-Reply-To: <1169048071.353887.279160@q2g2000cwa.googlegroups.com> References: <1169048071.353887.279160@q2g2000cwa.googlegroups.com> Message-ID: Shortash wrote: > Hi Gurus, > > I want to build a Python web app but im not sure which one to go for. I > prefer something like asp.Net , which would allow me to fully seperate > the presentation layer from the logic. Please advise? > > thanks, > > "Shortash' > Hi, Look at there are same of them. Now I'm studing karrigell, it's very interesting. bye, -- Ximo Nadal Powered by Debian GNU/Linux From timr at probo.com Tue Jan 23 02:30:44 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 23 Jan 2007 07:30:44 GMT Subject: Help with 'popen' References: <1169436640.161806.111510@38g2000cwa.googlegroups.com> Message-ID: James Stroud wrote: >stephen_b wrote: > >> Can someone let me know why this won't work? Thanks. >> >>>>>from os import popen >>>>>popen('export asdfasdf=hello').read() >> '' >>>>>popen('echo $asdfasdf').read() >> '\n' > >Python starts a new shell for each command, so your environment variable >is lost. You probably want this, which makes the variable "permanent". > >py> import os >py> os.environ['asdfasdf'] = 'hello' >py> os.popen('echo $asdfasdf').read() >'hello\n' For completeness, let us anticipate the followup question and point out that "permanent" here means "for this process and any processes that it spawns". Once the Python session ends, the "asdfasdf" will be lost. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From horpner at yahoo.com Wed Jan 10 11:17:20 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Jan 2007 17:17:20 +0100 Subject: Need startup suggestions for writing a MSA viewer GUI in python References: Message-ID: On 2007-01-10, hg wrote: > Joel Hedlund wrote: >> Thanks for taking the time! >> /Joel Hedlund > > I do not know if PyGtk and PyQT have demos, but wxPython does > and includes PyPlot: an easy way to look at the basic features. PyQT does come with an impressive plethora of demos. -- Neil Cerutti The concert held in Fellowship Hall was a great success. Special thanks are due to the minister's daughter, who labored the whole evening at the piano, which as usual fell upon her. --Church Bulletin Blooper From mike.klaas at gmail.com Wed Jan 24 19:00:48 2007 From: mike.klaas at gmail.com (Klaas) Date: 24 Jan 2007 16:00:48 -0800 Subject: The reliability of python threads In-Reply-To: References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> Message-ID: <1169683248.853997.309590@m58g2000cwm.googlegroups.com> On Jan 24, 10:43 am, "Carl J. Van Arsdall" wrote: > Chris Mellon wrote: > > On 24 Jan 2007 18:21:38 GMT, Nick Maclaren wrote: > > >> [snip] > > > I'm aware of the issues with the POSIX threading model. I still stand > > by my statement - bringing up the problems with the provability of > > correctness in the POSIX model amounts to FUD in a discussion of > > actual problems with actual code. > > > Logic and programming errors in user code are far more likely to be > > the cause of random errors in a threaded program than theoretical > > (I've never come across a case in practice) issues with the POSIX > > standard.Yea, typically I would think that. The problem I am seeing is > incredibly intermittent. Like a simple pyro server that gives me a > problem maybe every three or four months. Just something funky will > happen to the state of the whole thing, some bad data, i'm having an > issue tracking it down and some more experienced programmers mentioned > that its most likely a race condition. THe thing is, I'm really not > doing anything too crazy, so i'm having difficult tracking it down. I > had heard in the past that there may be issues with threads, so I > thought to investigate this side of things. > > It still proves difficult, but reassurance of the threading model helps > me focus my efforts. > > > Emphasizing this means that people will tend to ignore bugs as being > > "the fault of POSIX" rather than either auditing their code more > > carefully, or avoiding threads entirely (the second being what I > > suspect your goal is). > > > As a last case, I should point out that while the POSIX memory model > > can't be proven safe, concrete implementations do not necessarily > > suffer from this problem.Would you consider the Linux implementation of threads to be concrete? > > -carl > > -- > > Carl J. Van Arsdall > cvanarsd... at mvista.com > Build and Release > MontaVista Software From kuldjlevelet at gmail.com Thu Jan 18 07:21:18 2007 From: kuldjlevelet at gmail.com (0k-) Date: 18 Jan 2007 04:21:18 -0800 Subject: classes: need for an explanation In-Reply-To: References: <1169121502.779509.138890@m58g2000cwm.googlegroups.com> Message-ID: <1169122878.476800.109330@l53g2000cwa.googlegroups.com> thanks for the quick reply, Peter! :) From steve at holdenweb.com Fri Jan 26 12:06:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 26 Jan 2007 17:06:11 +0000 Subject: DOS, UNIX and tabs In-Reply-To: References: <1167243140.687557.93320@f1g2000cwa.googlegroups.com> <1167244483.792673.132220@42g2000cwt.googlegroups.com> <12p5ffrsdo6v088@corp.supernews.com> <1167245005.678672.196280@73g2000cwn.googlegroups.com> Message-ID: Tim Roberts wrote: > "Ben" wrote: >> Great - that worked.Thanks! >> Is that a general method in linux you can always use to redirect >> standard output to a file? > > Works in Windows, too. For some value of "work" :) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From NO_Kroeger at gmx.de Thu Jan 25 16:40:57 2007 From: NO_Kroeger at gmx.de (=?ISO-8859-1?Q?Nils_Oliver_Kr=F6ger?=) Date: Thu, 25 Jan 2007 22:40:57 +0100 Subject: pdf to text In-Reply-To: References: Message-ID: <45B923E9.1050109@gmx.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 have a look at the pdflib (www.pdflib.com). Their Text Extraction Toolkit might be what you are looking for, though I'm not sure whether you can use it detached from the pdflib itself. hth Nils tubby schrieb: > I know this question comes up a lot, so here goes again. I want to read > text from a PDF file, run re searches on the text, etc. I do not care > about layout, fonts, borders, etc. I just want the text. I've been > reading Adobe's PDF Reference Guide and I'm beginning to develop a > better understanding of PDF in general, but I need a bit of help... this > seems like it should be easier than it is. Here's some code: > > import zlib > > fp = open('test.pdf', 'rb') > bytes = [] > while 1: > byte = fp.read(1) > #print byte > bytes.append(byte) > if not byte: > break > > for byte in bytes: > > op = open('pdf.txt', 'a') > > dco = zlib.decompressobj() > > try: > s = dco.decompress(byte) > #print >> op, s > print s > except Exception, e: > print e > > op.close() > > fp.close() > > I know the text is compressed... that it would have stream and endstream > makers and BT (Begin Text) and ET (End Text) and that the uncompressed > text is enclosed in parenthesis (this is my text). Has anyone here done > this in a simple fashion? I've played with the pyPdf library some, but > it seems overly complex for my needs (merge PDFs, write PDFs, etc). I > just want a simple PDF text extractor. > > Thanks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.3 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFFuSPozvGJy8WEGTcRAnY0AJ0VZez3XRbLm/JXZKhn/rgHP0R3qwCfWAnT EupBECHab2kG33Rmnh+xf74= =INM5 -----END PGP SIGNATURE----- From jeremit0 at gmail.com Thu Jan 4 23:02:06 2007 From: jeremit0 at gmail.com (jeremito) Date: 4 Jan 2007 20:02:06 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> Message-ID: <1167969726.159675.226260@42g2000cwt.googlegroups.com> Gabriel Genellina wrote: > At Thursday 4/1/2007 23:52, jeremito wrote: > > >I am writing a class that is intended to be subclassed. What is the > >proper way to indicate that a sub class must override a method? > > If any subclass *must* override a method, raise NotImplementedError > in the base class (apart from documenting how your class is supposed > to be used). > > > -- > Gabriel Genellina > Softlab SRL > Thanks, that's what I needed. Since I am a complete novice at Exceptions, I'll have to learn about it. Jeremy From skip at pobox.com Sun Jan 14 09:59:12 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 14 Jan 2007 08:59:12 -0600 Subject: Threaded for loop In-Reply-To: <1168750177.856791.85730@s34g2000cwa.googlegroups.com> References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> <7xr6ty8ugv.fsf@ruckus.brouhaha.com> <1168750177.856791.85730@s34g2000cwa.googlegroups.com> Message-ID: <17834.17728.999793.401498@montanaro.dyndns.org> John> Damn! That is bad news. So even if caclulate is independent for John> (i,j) and is computable on separate CPUs (parts of it are CPU John> bound, parts are IO bound) python cant take advantage of this? It will help if parts are I/O bound, presuming the threads which block release the global interpreter lock (GIL). There is a module in development (processing.py) that provides an API like the threading module but that uses processes under the covers: http://mail.python.org/pipermail/python-dev/2006-October/069297.html You might find that an interesting alternative. Skip From martin at v.loewis.de Mon Jan 8 13:47:13 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 08 Jan 2007 19:47:13 +0100 Subject: Module to read svg In-Reply-To: References: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> <45a1f746$0$27874$9b622d9e@news.freenet.de> Message-ID: <45A291B1.7070509@v.loewis.de> Robert Kern schrieb: >>> Does anyone know if there's an actual free implementation of this? >> For the dom module in it, xml.dom.minidom should work. Depending on >> your processing needs, that might be sufficient. > > I don't think it quite fits what the OP is asking for. SVG defines some non-XML > structure for some of its contents. For example: > > > > The OP is asking for a module that would parse the "points" attribute into a list: > > [(100.0, 200.0), (100.0, 100.0)] Sure, but he also specifically asked for an implementation of http://www.w3.org/TR/SVGMobile12/python-binding.html minidom *is* such an implementation (at least of a subset). If I was to implement the entire thing, I'd base it on top of minidom: SVGDocument needs to inherit from Document, and SVGSVGElement needs to inherit from SVGLocatableElement needs to inherit from SVGElement needs to inherit from Element. Regards, Martin From laurent.pointal at limsi.fr Thu Jan 11 03:20:40 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 11 Jan 2007 09:20:40 +0100 Subject: Read from database, write to another database, simultaneously In-Reply-To: <50l9dlF1fuc1sU1@mid.individual.net> References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> Message-ID: Bjoern Schliessmann a ?crit : > Sean Davis wrote: > >> The author of one of the python database clients mentioned that >> using one thread to retrieve the data from the oracle database and >> another to insert the data into postgresql with something like a >> pipe between the two threads might make sense, keeping both IO >> streams busy. > > IMHO he's wrong. Network interaction is quite slow compared with CPU > performance, so there's no gain (maybe even overhead due to thread > management and locking stuff). That's true even on multiprocessor > machines, not only because there's almost nothing to compute but > only IO traffic. CMIIW. Not so sure, there is low CPU in the Python script, but there may be CPU+disk activity on the database sides [with cache management and other optimizations on disk access]. So, with a reader thread and a writer thread, he can have a select on a database performed in parallel with an insert on the other database. After, he must know if the two databases use same disks, same controller, same host... or not. But, if its only a do-once job, maybe the optimization is net really necessary. From nyenyec at gmail.com Mon Jan 8 23:17:51 2007 From: nyenyec at gmail.com (nyenyec) Date: 8 Jan 2007 20:17:51 -0800 Subject: re.sub and re.MULTILINE Message-ID: <1168316270.996407.226910@s80g2000cwa.googlegroups.com> I feel like a complete idiot but I can't figure out why re.sub won't match multiline strings: This works: >>> re.search("^foo", "\nfoo", re.MULTILINE) <_sre.SRE_Match object at 0x6c448> This doesn't. No replacement: >>> re.sub("^foo", "bar", "\nfoo", re.MULTILINE) '\nfoo' Why? Thanks, nyenyec From steven.bethard at gmail.com Tue Jan 30 09:13:15 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: 30 Jan 2007 06:13:15 -0800 Subject: Fixed length lists from .split()? In-Reply-To: <2007012611072716807-bob@passcalnmtedu> References: <2007012611072716807-bob@passcalnmtedu> Message-ID: <1170166395.766987.125010@l53g2000cwa.googlegroups.com> On Jan 26, 11:07 am, Bob Greschke wrote: > I'm reading a file that has lines like > > bcsn; 1000000; 1223 > bcsn; 1000001; 1456 > bcsn; 1000003 > bcsn; 1000010; 4567 > > The problem is the line with only the one semi-colon. > Is there a fancy way to get Parts=Line.split(";") to make Parts always > have three items in it In Python 2.5 you can use the .partition() method which always returns a three item tuple: >>> text = '''\ ... bcsn; 1000000; 1223 ... bcsn; 1000001; 1456 ... bcsn; 1000003 ... bcsn; 1000010; 4567 ... ''' >>> for line in text.splitlines(): ... bcsn, _, rest = line.partition(';') ... num1, _, num2 = rest.partition(';') ... print (bcsn, num1, num2) ... (' bcsn', ' 1000000', ' 1223') (' bcsn', ' 1000001', ' 1456') (' bcsn', ' 1000003', '') (' bcsn', ' 1000010', ' 4567') >>> help(str.partition) Help on method_descriptor: partition(...) S.partition(sep) -> (head, sep, tail) Searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns S and two empty strings. STeVe From jordan.taylor2 at gmail.com Thu Jan 25 13:08:01 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 25 Jan 2007 10:08:01 -0800 Subject: asyncore.dispatcher.handle_read In-Reply-To: References: Message-ID: <1169748481.260540.58640@k78g2000cwa.googlegroups.com> That was not entirely helpful, it's way more likely a mistake you made in subclassing dispatcher than a problem within asycore itself (that ended up sounding a lot more mean/angry than intended, sorry ?_? ), you really need to show us what changes you made to asyncore.dispatcher if you want help. Good luck. Cheers, Jordan On Jan 25, 12:18 pm, Indy wrote: > Greetings. > > I am writing an asynchronous server, and I use the standard library's > module asyncore. > I subclass asyncore.dispatcher. handle_accept works just right, that > is, when a client socket makes a request to connect to my server > socket, things that I set in handle_accept definition, happen. So, it > is OK. But, the problem is that handle_read does not work as expected. > Things I set in handle_read definition, do not happen when a client > socket sends me data. Why? Is this a known problem? Please, can you > help me? > Thanks a lot, in advance. > > Best regards, > Aristotelis Mikropoulos > > -- > Programs must be written for people to read, and only incidentally for > machines to execute. From Barry.Carroll at psc.com Wed Jan 17 13:53:06 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 17 Jan 2007 10:53:06 -0800 Subject: *POLL* How many sheeple believe in the 911 fairy tale and willingto accept an Orwellian doublespeak and enslavement world ? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A7D@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: Robert Hicks [mailto:sigzero at gmail.com] > Sent: Wednesday, January 17, 2007 10:33 AM > To: python-list at python.org > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > Please, none of the real facts points to anything else except what > actually happened. Two planes hit two towers and they came down. > Ladies and Gentlemen: PLEASE take this discussion to a more appropriate forum. There are many forums where people will be happy to debate this: physics, firefighting, metallurgy, geopolitics, etc. This forum is about the Python programming language. Let's keep it that way. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From horpner at yahoo.com Thu Jan 18 10:55:30 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 18 Jan 2007 15:55:30 GMT Subject: A note on heapq module References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <45ad0f6c$1@nntp0.pdx.net> <1168982702.903306.152940@m58g2000cwm.googlegroups.com> <1169118077.035345.321580@11g2000cwr.googlegroups.com> Message-ID: On 2007-01-18, bearophileHUGS at lycos.com wrote: > Neil Cerutti: >> One more idea, cribbed from the linked list thread elsewhere: >> it might be nice if your Heap could optionally use an >> underlying collections.deque instead of a list. I don't know >> how excellent Python's deque is, but it's possible a deque >> would provide a faster heap than a contiguous array. C++'s >> std::deque is the default implementation of C++'s >> std::priority_queue for that reason (unless I'm confused >> again). > > If you have some minutes you can do few speed tests and show us > the code and the timing results... collections.deque is the loser. Here's the output of the program from my last run: list: 5.81679827554 deque: 6.40347742423 C heapq: 2.24028186815 Here's the program. You can customize it somewhat to attempt to model a real program. It builds up a heap of random integers to some size, performs random pushes and pops for a while, and then pops the heap down until it's empty. import random import timeit OPCOUNT = 5000 HEAP_SIZE = 100 # Create a random sequence of pushes and pops. pushes = 0 ops = [] for i in xrange(OPCOUNT): x = random.randint(0, 1) if x == 0 or pushes < HEAP_SIZE: pushes += 1 ops.append(0) else: pushes -= 1 ops.append(1) # Pop off the rest for i in xrange(pushes): ops.append(1) def test(mod, cont): for op in ops: if op: mod.heappop(cont) else: mod.heappush(cont, random.randint(0, 150)) # heapqd is the pure Python heapq module without the C implementation. t1 = timeit.Timer("test(heapqd, list())", "from __main__ import test; import heapqd") t2 = timeit.Timer("test(heapqd, deque())", "from __main__ import test; "\ "from collections import deque; "\ "import heapqd") t3 = timeit.Timer("test(heapq, list())", "from __main__ import test; import heapq") print "list:", t1.timeit(100) print "deque:", t2.timeit(100) print "C heapq:", t3.timeit(100) -- Neil Cerutti The Pastor would appreciate it if the ladies of the congregation would lend him their electric girdles for the pancake breakfast next Sunday morning. --Church Bulletin Blooper -- Posted via a free Usenet account from http://www.teranews.com From arkanes at gmail.com Wed Jan 24 15:18:34 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 14:18:34 -0600 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <4866bea60701241218s7931e703yd44aecc6ac550058@mail.gmail.com> On 1/24/07, John Nagle wrote: > Chris Mellon wrote: > > On 1/24/07, John Nagle wrote: > > > >> Harry George wrote: > >> > John Nagle writes: > > > Just to be clear: The problem here is "my personal itch is not being > > scratched by other people for me", not "Python doesn't play well with > > others". You are not any more important than anyone else and assuming > > that anyone cares about your problems is a major fallacy. You have a > > specific library that doesn't meet your needs, and that you are not > > interested in maintaining yourself, so you are attempting to leverage > > some sort of community guilt trip to get other people to do it for > > you. That's dishonest and off-putting. > > No, the problem is that these things are broken. > That's *your* problem. I don't write any code that uses SSL and so it's not *my* problem. In a community effort, you either need to fix your own problems or convince other people that they should fix them. Saying "hey guys, this is broken" is a start. "You guys are shirking your responsibilities and not supporting me the way I want to be supported" is not, because it assumes an entitlement that you do not have. > Python is the only major open source project I've encountered where > there's so much hostility to bug reports. > You've never submitted a duplicate bug to Gnome, have you? Regardless, I see very little hostility toward bug reports. You confuse people failing to satisfy your needs with hostility. > For a while, I tried submitting long, detailed bug reports showing > where in the C code a problem lies, and pointing out ways to fix it. > But I don't want to take over maintenance on the SSL package; > it's too delicate. And yet, you are perfectly willing to claim that everyone else who makes the same decision is failing, somehow. Could one not point out that you are failing your responsibility to the Python community, following the same logic? From jrpfinch at gmail.com Fri Jan 12 12:18:54 2007 From: jrpfinch at gmail.com (jrpfinch) Date: 12 Jan 2007 09:18:54 -0800 Subject: Newbie imap lib question In-Reply-To: <1168611888.009894.271190@51g2000cwl.googlegroups.com> References: <1168611888.009894.271190@51g2000cwl.googlegroups.com> Message-ID: <1168622334.397481.186310@38g2000cwa.googlegroups.com> All I have to go on is the RFC2060 standard which says: 7.3.1. EXISTS Response Contents: none The EXISTS response reports the number of messages in the mailbox. This response occurs as a result of a SELECT or EXAMINE command, and if the size of the mailbox changes (e.g. new mail). The update from the EXISTS response MUST be recorded by the client. Example: S: * 23 EXISTS From gmenhennitt at optusnet.com.au Thu Jan 11 17:47:37 2007 From: gmenhennitt at optusnet.com.au (Graham Menhennitt) Date: Fri, 12 Jan 2007 09:47:37 +1100 Subject: injecting functions into a python sandbox within a python program In-Reply-To: <45a41cb7$0$308$426a74cc@news.free.fr> References: <45a4172e$0$71751$c30e37c6@ken-reader.news.telstra.net> <45a41cb7$0$308$426a74cc@news.free.fr> Message-ID: <45a6be85$0$71760$c30e37c6@ken-reader.news.telstra.net> Bruno Desthuilliers wrote: > If all your helper functions are really methods of the Interface > instance, you may try this instead (NB : not tested): > > glob = { > 'i': i, > 'f1': i.whatever, > } > exec script in glob Bruno, Thanks for replying. Some of the functions are as simple as that so I can do as you described. Some are more complicated so it doesn't work. For now I'll stick with the prepending. Thanks, Graham From theller at ctypes.org Tue Jan 2 12:06:30 2007 From: theller at ctypes.org (Thomas Heller) Date: Tue, 02 Jan 2007 18:06:30 +0100 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167757137.942280.32270@42g2000cwt.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <1167757137.942280.32270@42g2000cwt.googlegroups.com> Message-ID: Ben Sizer schrieb: > Gabriel Genellina wrote: > >> Notice that there is NO need to alter the system path. You just have >> to tell Windows where python.exe resides; there is a per-application >> path located at >> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths. >> In order to launch Python just writing "python" at the command >> prompt, the installer should -instead of playing with the system >> path- create a new key below App Paths, named "python.exe", and set >> its default value to the full path of the installed python executable. >> See >> http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/fileassociations/fa_perceived_types.asp > >>From what I can tell, that is solely for file associations. If so, it > will work if you type "setup.py install" but not if you type "python > setup.py install". For instance, I have an entry for Firefox in that > part of the registry, but if you try executing "firefox" at the command > line, it fails. Not really. It's for ShellExecute, which is used for the 'run' entry in the start menu, or when you type 'start firefox' from the command line. Thomas From python at rcn.com Wed Jan 10 21:58:35 2007 From: python at rcn.com (Raymond Hettinger) Date: 10 Jan 2007 18:58:35 -0800 Subject: Evolving doctests for changing output format References: <1168313515.965895.86730@s80g2000cwa.googlegroups.com> Message-ID: <1168484315.722785.101890@k58g2000hse.googlegroups.com> [nriley at gmail.com] > What I'd like is if I could get doctest to take my tests, and > substitute the obtained output for the provided output. There's currently no support for auto-updating doctests. I think it would make for a good feature request. In the meantime, it may not be difficult to roll your own by converting the current expected/got output into a diff and then applying it to the original source code being doctested. Start with a regular expression like this: pat = re.compile(r''' File.+,\sline\s(\d+),.+\n Failed\sexample:\n((?:.*?\n)*?) Expected:\n((?:.*?\n)*?) Got:\n((?:.*?\n)*?) \*{70,70} ''', (re.MULTILINE | re.VERBOSE)) Then, build-up a diff in your preferred format. Perhaps like this: cumadj = 0 for lineno, example, expected, got in pat.findall(source): len_example, len_expected, len_got = example.count('\n'), expected.count('\n') , got.count('\n') start = int(lineno) + len_example lead = str(start) if len_expected !=1: lead += ',' + str(start+len_expected-1) lead += 'c' + str(start + cumadj) if len_got != 1: lead += ',' + str(start+cumadj+len_got-1) print lead for old in expected.splitlines(False): print '<' + old print '---' for new in got.splitlines(False): print '>' + new cumadj += len_got - len_expected Raymond From bdesth.quelquechose at free.quelquepart.fr Mon Jan 29 16:12:02 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Jan 2007 22:12:02 +0100 Subject: Python does not play well with others In-Reply-To: References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> Message-ID: <45be5c40$0$23047$426a74cc@news.free.fr> John Nagle a ?crit : (snip) > My main concern is with glue code to major packages. The connections > to OpenSSL, MySQL, and Apache (i.e. mod_python) all exist, but have major > weaknesses. Neither MySQLdb nor mod_python are part of the Python's standard lib AFAIK. > If you're doing web applications, I do. > those are standard pieces > which need to work right. I avoid using MySQL - SQLite does a better job as a lighweight SQL-compliant no-server solution, and PostgreSQL is years ahead of MySQL when it comes to serious, rock-solid transactional RDBMS. But I had no problem with the MySQLdb package so far. I also tend to favor Apache-independant deployment solutions, so while I had some fun with mod_python, I failed to clearly understand how broken it is. And I did not have to worry about the ssl support in Python so far. FWIW, I had do some LDAP stuff with both PHP and Python, and I would certainly not advocate PHP's LDAP support. > There's a tendency to treat those as abandonware > and re-implement them as event-driven systems in Twisted. While Twisted seems an interesting project, it's usually not the first mentioned when talking about web development with Python. > Yet the > main packages aren't seriously broken. It's just that the learning curve > to make a small fix to any of them is substantial, so nobody new takes > on the problem. If you feel you need it, then it's up to you. From steve at REMOVEME.cybersource.com.au Wed Jan 31 02:24:22 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 31 Jan 2007 18:24:22 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> Message-ID: On Tue, 30 Jan 2007 21:15:53 -0800, manstey wrote: > Hi Ben, > > Could I also do something like the following? What does it mean to > store the parent class as a private variable in the child class? What it means is that references to "self.__data" (note the TWO leading underscores) in your code below are mangled by Python to be "self._CacheProperty__data__" instead. This gives you a weak form of "private" variable, good for annoying people and yourself, possibly okay to help prevent many accidental name clashes, but not much else. On the other hand, references to "self._parent" (note only ONE leading underscore) is a convention. It is like putting a comment "Private, don't touch" in your code. It isn't enforced by Python. That's usually a good thing. > class CacheProperty(object): > def __init__(self, obj, parent, properties=None): > self.__data = obj > self._parent = parent > if properties is None: > properties = {} > self._accumulate_properties(properties) > > > def _accumulate_properties(self, properties): > self.properties = [] Probably better to put that in the __init__ method, otherwise if somebody runs instance._accumulate_properties(...) again, it will have the side-effect of throwing away whatever was already in instance.properties. Some people might argue that if someone runs a private method like _accumulate_properties, they deserve whatever bad things happen to them. But I say, well, sure, but why *design* your method to break things when called twice? Who knows, maybe you'll decide you want to call it twice yourself. > for key, val in properties.iteritems(): > setattr(self, key, val) > self.properties.append(key) If I am reading this correctly, self.properties is almost the same as self.__dict__.keys() only missing some values. > def __getattr__(self, name): > return getattr(self.__data, name) Okay, let's see how this works. child = CacheProperty([1,2,3], PARENT, {"food": "eggs", "colour": "green"}) # child.__data is the list [1,2,3] # child._parent is PARENT (whatever that is) # child.properties is the list ['food', 'colour'] Now, if I say: child.__len__() => returns 3 child.index(2) => returns 1 That's just straight-forward delegation to the "obj" argument stored in data. But when I say: child.set('foo') expecting to have the following method called: > def set(self, property): > return self._parent.set(property) oops! It gets delegated to obj instead of the parent. > the set function allows us to call the parent set function within the > child, which is what we need to do. Why not do this? instance._parent.set('foo') No mess, no fuss, bug-free, and self-documenting. -- Steven D'Aprano From kotamura at hello.email.ne.jp Sat Jan 6 13:29:41 2007 From: kotamura at hello.email.ne.jp (Koichi) Date: Sun, 07 Jan 2007 03:29:41 +0900 Subject: A problem in embedding Python in a plug-in Message-ID: <20070106182941.3B1D3252D6@mail.asahi-net.or.jp> Hi, I'm now making a plug-in for a CG software. I embed Python in a plugin and it works. The problem is that it conflicts with other plugins that also embeds Python because it runs in the same thread. I don't know when Py_Initialize() and Py_Finalize() are executed because I don't know when user loads/unloads a plugin that embeds Python. Is there any right way to embed Python in a plug-in under the following conditions? If not, what options do I have to give up any of them? - My plug-in has no way to know when the user loads/unloads it. - My plug-in has no way to know when the user loads/unloads somebody else's plug-in that embeds Python. - Somebody else's plug-in might have used any Python/C API including GIL related stuff, new_interpreter, PyGILState_* - Every plug-in initially runs in the same thread but some plug-in can start a new thread. - Preferably my plug-in has its own __main__ - My plug-in doesn't have to be thread safe but shouldn't disturb any other plug-in (so should be thread safe anyway) Typical problem is: - When somebody else loads or unloads another plugin and calls Py_IsInitialized() or Py_Finalize(), my plugin fails - When some other plugin uses PyGILState*(), both plugin fails because my plug-in uses new interpreter (I'm new to Python/C API so I may be misunderstanding one ore more) Any suggestion is appreciated. Koichi From danielkleinad at gmail.com Mon Jan 1 18:25:26 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Mon, 01 Jan 2007 18:25:26 -0500 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> Message-ID: On 1 Jan 2007 11:33:42 -0800, "Ramdas" wrote: >How do I add users using Python scripts on a Linux machine? > >Someone has a script? This should be as easy as something like: os.system("/usr/sbin/useradd -m -d /home/newuser -s /bin/ksh") Dan From uval at rz.uni-karlsruhe.de Sun Jan 21 12:18:14 2007 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Sun, 21 Jan 2007 18:18:14 +0100 Subject: pylab, matplotlib ... roots function question Message-ID: Hello NG, given this call to roots funtion from pylab In [342]: roots([0,2,2]) Out[342]: array([-1.]) as far as I understand it [a0,a1,a2] stands for a0+a1*x+a2*x^2 in the above case it yields 2x^2+2x = 2x(1+x) and the roots are 0 and -1 I am wondering why roots function gives me only the -1 second try In [343]: roots([1,0,0]) Out[343]: array([], dtype=float64) ok, as it should be In [344]: roots([0,0,1]) Out[344]: array([], dtype=float64) here again, 0 is the root of x^2 Do I miss something important? Regards, Daniel From chris at kateandchris.net Tue Jan 2 16:34:14 2007 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 2 Jan 2007 16:34:14 -0500 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167757721.883547.70530@42g2000cwt.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <1167757721.883547.70530@42g2000cwt.googlegroups.com> Message-ID: <20070102213414.GA17469@kateandchris.net> On Tue, Jan 02, 2007 at 09:08:41AM -0800, Ben Sizer wrote: > Chris Lambacher wrote: > > > On Sat, Dec 30, 2006 at 04:55:09PM -0800, Ben Sizer wrote: > > > > Yet many scripts and applications require parameters, or to be executed > > > from a certain directory. For example, setup.py. Or the various > > > turbogears scripts. Or easy_install. > > > Martin's point was that if you need to pass arguments, you can call the script > > from the command line like so: > > setup.py install > > > > The python part of the 'python setup.py install' idiom needs to be omitted on > > Windows, but that does not mean that the solution is to automatically add it > > to PATH. > > Firstly, that solution only works for actual Python scripts; it doesn't > solve the utility scripts that are often installed to the /scripts > directory. It's a shame that many responses on this thread don't > address that half of the issue. Am I the only person who installs > packages that add scripts (not all of which are Python ones)? Nope, but just adding the scripts directory to the PATH does not solve the problem. You also need to either create an executable launcher (.bat or .exe) for the script or mess with environment variables to tell Windows to treat .py files a executable. This issue is solved in Unix by toggling the executable bit on the file in the file system. Easy Install helps the situation by making an executable of the same name as the script which calls the script. There has been discussion on the distutils mailing list about how to put this in the user's path. No good solution has been proposed. If Easy Install were made the default distribution method, or distutils spawned the ability to handle scripts in a similar manner, I would be in favour of optionally adding scripts to PATH. Whether that option is on by default or not could be debated at that time. > > Secondly, it's still a significant difference from the Unix-based > installs. Its not really. Unix installs default to being installed to the prefix /usr, which just happens to put the executable in your path. It does not modify the user's path in any way. If you install to some location that is not in your path it is your responsibility to add that location to your path or provide an explicit path. Some of the problems caused by this are mitigated by the way Unix identifies executables. > You're right, the solution doesn't automatically have to be > adding it to the PATH - but I'm yet to see a good argument for choosing > not to, apart from "I don't like it when apps do that". > > > The documentation is misleading... time for a but report: > > http://sourceforge.net/tracker/index.php?func=detail&aid=1626300&group_id=5470&atid=105470 > > Fixing the docs is better than nothing, but I believe fixing the > install to encourage uniform usage across all platforms is preferable, > and that in this regard the documentation shows how it 'should' work. > > > > There appears to be a freely-available binary at this address that may > > > suffice: > > > http://legroom.net/modules.php?op=modload&name=Open_Source&file=index&page=software&app=modpath > > > Unfortunately the Python installer is not an InnoSetup installer. > > The page I linked to is a bit misleading but there is an executable on > that page. All you then have to do is invoke it with the relevant > parameter. Sorry, I saw the Inno version and the AutoIt and did not see the compiled executable version. I still think it will be more likely to be accepted if the code was translated into Python, since shipping another executable will not be required. > > -- > Ben Sizer > > -- > http://mail.python.org/mailman/listinfo/python-list From juanefren at gmail.com Sat Jan 27 02:14:20 2007 From: juanefren at gmail.com (juanefren at gmail.com) Date: Sat, 27 Jan 2007 00:14:20 -0700 Subject: Convert String to list of chars Message-ID: How can I convert a string to a char list? for example "hello" --> ['h','e','l','l','o'] I have been searching but I can't find my answers thanks -- Juan Efr?n Castillo Encinas From __peter__ at web.de Wed Jan 31 08:47:23 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 Jan 2007 14:47:23 +0100 Subject: Regex with ASCII and non-ASCII chars References: <1170243969.504255.134100@v33g2000cwv.googlegroups.com> Message-ID: TOXiC wrote: > How I can do a regex match in a string with ascii and non ascii chars > for example: > > regex = re.compile(r"(???????ty)", re.IGNORECASE) > match = regex.search("???????ty") > if match: > result = match.group() > print result > else: > result = "No match found" > print result > > it return "no match found" even if the two string are equal. For equal strings you should get a match: >>> re.compile("Z???", re.IGNORECASE).search("yadda z??? yadda") <_sre.SRE_Match object at 0x401e0a68> >>> print _.group() z??? For case ignorance your best bet is unicode: >>> re.compile(u"???", re.IGNORECASE|re.UNICODE).search(u"???") <_sre.SRE_Match object at 0x401e09f8> Peter From S.Mientki-nospam at mailbox.kun.nl Wed Jan 3 09:37:25 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 03 Jan 2007 15:37:25 +0100 Subject: function without brackets ? Message-ID: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> If I call a parameterless function without brackets at the end, the function is not performed, but ... I don't get an error message ??? Is this normal behavior ? thanks, Stef Mientki From could.net at gmail.com Wed Jan 17 11:28:14 2007 From: could.net at gmail.com (Frank Potter) Date: 17 Jan 2007 08:28:14 -0800 Subject: how to write unicode to a txt file? Message-ID: <1169051293.848769.163860@s34g2000cwa.googlegroups.com> I want to change an srt file to unicode format so mpalyer can display Chinese subtitles properly. I did it like this: txt=open('dmd-guardian-cd1.srt').read() txt=unicode(txt,'gb18030') open('dmd-guardian-cd1.srt','w').write(txt) But it seems that python can't directly write unicode to a file, I got and error at the 3rd line: UnicodeEncodeError: 'ascii' codec can't encode characters in position 85-96: ordinal not in range(128) How to save the unicode string to the file, please? Thanks! From donn at u.washington.edu Thu Jan 18 15:02:11 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 18 Jan 2007 12:02:11 -0800 Subject: How to find out if another process is using a file References: Message-ID: In article , "Gabriel Genellina" wrote: > "Tom Wright" escribi? en el mensaje > news:eoo6vd$33u$1 at gemini.csx.cam.ac.uk... > > > I'm writing a program which reads a series of data files as they are > > dumped > > into a directory by another process. At the moment, it gets sporadic bugs > > when it tries to read files which are only partially written. > > > > I'm looking for a function which will tell me if a file is opened in > > write-mode by another process - if it is, my program will ignore it for > > now > > and come back to it later. This needs to work on linux and windows. Mac > > OS would be a bonus too. An os-independent solution would be good, but I > > could write os-specific options and have it pick the appropriate one. > > Use os.open with the O_EXCL flag; will fail if the other process has the > file still open (and will fail if another process is reading the file, too, > not just if someone is writing). O_EXCL fails if the file exists at all - whether closed or open. Donn Cave, donn at u.washington.edu From pavlovevidence at gmail.com Sat Jan 27 09:19:59 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 27 Jan 2007 06:19:59 -0800 Subject: assertions to validate function parameters In-Reply-To: References: Message-ID: <1169907599.090680.286910@a75g2000cwd.googlegroups.com> On Jan 25, 11:26 pm, Steven D'Aprano wrote: > Note also that for real code, a bare assert like that is uselessly > uninformative: > > >>> x = 1 > >>> assert x == 3Traceback (most recent call last): > File "", line 1, in ? > AssertionError In real code, a traceback usually prints the line of code containing the failed assertion. > This is better: > > >>> assert x == 3, "x must be equal to three but is %s instead" % xTraceback (most recent call last): > File "", line 1, in ? > AssertionError: x must be equal to three but is 1 instead > > This is even better still: > > >>> if x != 3:... raise ValueError("x must be equal to three but is %s instead" % x) > ... > Traceback (most recent call last): > File "", line 1, in ? > ValueError: x must be equal to three but is 1 instead These are are verbose to the point of silliness, and usually not worth the effort since assertions are only supposed to check for ostensibly impossible conditions. Thus it shouldn't pop up often enough to justify writing a verbose error message in advance, and when it does trigger you're going to have to print the failed result in a debuging run anyways. Carl Banks From gagsl-py at yahoo.com.ar Mon Jan 22 20:15:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Jan 2007 22:15:00 -0300 Subject: How to get self reference from within a module? In-Reply-To: <3ca9bbe50701221526p4bb7cffdx767d6737bed0a6a2@mail.gmail.co m> References: <3ca9bbe50701221526p4bb7cffdx767d6737bed0a6a2@mail.gmail.com> Message-ID: <7.0.1.0.0.20070122221123.03fb7e40@yahoo.com.ar> At Monday 22/1/2007 20:26, Lavoie ?rick wrote: > i would like to now how to get a self > reference from within a module. The goal is to > be able to generate a list of all declared function within the module. From inside the module, use globals() - that includes all defined symbols (classes, imported modules, functions, etc). You can filter them using inspect.isfunction by example. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From cvanarsdall at mvista.com Wed Jan 31 16:52:35 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 31 Jan 2007 13:52:35 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <20070131203758.25807.1007628884.divmod.quotient.4971@ohm> References: <20070131203758.25807.1007628884.divmod.quotient.4971@ohm> Message-ID: <45C10FA3.7030208@mvista.com> Jean-Paul Calderone wrote: > On 31 Jan 2007 12:24:21 -0800, Carl Banks wrote: > >> Michele Simionato wrote: >> >>> On Jan 31, 5:23 pm, "Frank Potter" wrote: >>> >>>> I want to find a multithreaded downloading lib in python, >>>> can someone recommend one for me, please? >>>> Thanks~ >>>> >>> Why do you want to use threads for that? Twisted is the >>> obvious solution for your problem, >>> >> Overkill? Just to download a few web pages? You've got to be >> kidding. >> > > Better "overkill" (whatever that is) than wasting time re-implementing > the same boring thing over and over for no reason. > How is that a waste of time? I wrote the script to do it in 10 lines. What is a waste of time is learning a whole new technology/framework to do a simple task that can be scripted in 4 minutes. -c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From codecraig at gmail.com Tue Jan 16 10:22:30 2007 From: codecraig at gmail.com (abcd) Date: 16 Jan 2007 07:22:30 -0800 Subject: Search Queue Message-ID: <1168960945.787822.286690@s34g2000cwa.googlegroups.com> I have a class such as... id = 0 class Foo: def __init__(self, data): self.id = id id += 1 self.data = data And I am storing them in a Queue.Queue... import Queue q = Queue.Queue() q.put(Foo('blah')) q.put(Foo('hello world')) q.put(Foo('test')) how can I search "q" for an instance of Foo which has 'id' equal to say 2? Typically a queue only lets you put and get, not really search. Thanks. From martin at v.loewis.de Fri Jan 5 19:30:03 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 06 Jan 2007 01:30:03 +0100 Subject: PyType_IsSubtype () In-Reply-To: <1167996955.467665.286170@42g2000cwt.googlegroups.com> References: <1167986947.735415.99970@s34g2000cwa.googlegroups.com> <459E1988.8060807@v.loewis.de> <1167996955.467665.286170@42g2000cwt.googlegroups.com> Message-ID: <459eed8b$0$25915$9b622d9e@news.freenet.de> Sheldon schrieb: > I ran the program in GDB and it crashed giving the following backtrace: > > #0 0x4008376e in PyType_IsSubtype () from /usr/lib/libpython2.3.so.1.0 > #1 0x4047730c in ?? () from > /usr/lib/python2.3/site-packages/Numeric/_numpy.so > > Can you make head or tail of this? Not yet, although it hints to a bug in Numeric. It now would help if _numpy.so was compiled with debug information enabled. Regards, Martin From beej at beej.us Mon Jan 29 13:30:16 2007 From: beej at beej.us (Beej) Date: 29 Jan 2007 10:30:16 -0800 Subject: Data structure and algorithms In-Reply-To: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> Message-ID: <1170095416.261460.157660@a34g2000cwb.googlegroups.com> On Jan 28, 2:56 pm, "azrael" wrote: > class Node: > def __init__(self, cargo=None, next=None): > self.cargo = cargo > self.next = next This is OK for the node itself, but maybe you should try writing a LinkedList class that you use: class LinkedList(object): def __init__(self): self.head = None def append(self, node): ... def remove(self, node): ... >>> ll = LinkedList() >>> ll.append(Node(3490)) (For extra fun, make it so you can iterate over the linked list and call it like this: for n in ll: print n :-) ) > >>> list=[] > >>> list.append(Node(1)) > >>> list.append(Node(2)) > >>> list[0].next=list[1] > >>> list.append(Node(3)) > >>> list[1].next=list[2] I'd classify this as "not pretty". Sure, it's more "dynamic" in that you don't have a variable to reference every node, but it's way cleaner to make an encapsulating LinkedList class, right? In in Python, references to objects are very much like pointers in C: >>> foo = Node(3490) # foo is a reference to a Node instance >>> bar = foo # bar points to the same Node instance as foo >>> foo <__main__.Node object at 0xb7b362ec> >>> bar <__main__.Node object at 0xb7b362ec> See? They point to the name Node object. > I think that my concept is wrong by using a list to create a list. I agree with you, if your goal is to implement your own list. Using the Python functionality just makes things less clear. > Is > it possible to manage the insertation of new object like in C by > allocating new memory space. Absolutely. The "next" pointer thing is the way to go, so you're on the right track with that. When deleting nodes from the list, you don't explicitly delete them; you just need to remove all your references to them. Nodes will be garbage collected when there are no more references to them anywhere. > any sugestions how to make the implementation more like in C. I never > managed the syntax of C so I stoped when structs crossed my way. > Please help. I dont want to learn C. Ah, it's a pity. C is my favorite compiled procedural language. -Beej From google at spiceaid.com Fri Jan 12 09:27:53 2007 From: google at spiceaid.com (Dr. Who) Date: 12 Jan 2007 06:27:53 -0800 Subject: What about this? In-Reply-To: <50n9kcF1g30l4U2@mid.individual.net> References: <1168525050.536736.74590@i39g2000hsf.googlegroups.com> <50n9kcF1g30l4U2@mid.individual.net> Message-ID: <1168612073.635206.84620@s34g2000cwa.googlegroups.com> What's more amazing is that anyone would click on the link at all given the increasing number of website that provide hidden content that tries to deliver spyware or viruses just by getting visitors. Jeff Bjoern Schliessmann wrote: > new wrote: > > > www.magicoz.com > > amazing > > Yeah, it *is* really amazing that someone dares to spam for such an > unprofessional homepage. Even too stupid to include a doctype ... > > > Bj?rn > > -- > BOFH excuse #61: > > not approved by the FCC From gagsl-py at yahoo.com.ar Wed Jan 31 22:17:02 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Feb 2007 00:17:02 -0300 Subject: win32com.client References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> <1170292629.986774.88240@a34g2000cwb.googlegroups.com> Message-ID: En Wed, 31 Jan 2007 22:17:10 -0300, vithi escribi?: > This is not I was looking for. There is a module call > "win32com.client" in python some people used it If any body know about > it let me know. > > On Jan 31, 1:45 pm, Gary Herron wrote: >> vithi wrote: >> > Hi >> > Any one tell me where I can get (or download) python modules win32com >> > or win32com.client because I have to use "Dispatch" thanks >> >> You want the "python for windows" extension, available from >> http://sourceforge.net/projects/pywin32/ Yes. You get the win32com module from the above url. It's part of that package, by Mark Hammond, and a lot of people uses it. -- Gabriel Genellina From sturlamolden at yahoo.no Sat Jan 13 17:47:53 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 13 Jan 2007 14:47:53 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168715634.695961.14710@l53g2000cwa.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168715634.695961.14710@l53g2000cwa.googlegroups.com> Message-ID: <1168728465.178605.218850@q2g2000cwa.googlegroups.com> oyekomova wrote: > Thanks to everyone for their excellent suggestions. I was able to > acheive the following results with all your suggestions. However, I am > unable to cross file size of 6 million rows. I would appreciate any > helpful suggestions on avoiding memory errors. None of the solutions > posted was able to cross this limit. The error message means you are running out of RAM. With 6 million rows and 6 columns, the size of the data array is (only) 274 MiB. I have no problem allocating it on my laptop. How large is the csv file and how much RAM do you have? Also it helps to post the whole code you are trying to run. I don't care much for guesswork. From silovana.vjeverica at com.gmail Mon Jan 22 15:48:22 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Mon, 22 Jan 2007 21:48:22 +0100 Subject: Best way to document Python code... References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: Adonis Vargas wrote: > Then Python will generate a quick help interface for your module. I Hi Does Python has API just like in Java, for example http://java.sun.com/j2se/1.5.0/docs/api/allclasses-noframe.html ctrl-f and than click on class you are searching for, and finally you get clean list of all fields and methods. Where can I find similar in Python, for example, if I would like to see which methods list/dictionary has. -- "kad ima? 7 godina glup si ko kurac, sve je predobro: auti?i i bageri u kvartu.. to je ?ivot" Drito Konj From rw at smsnet.pl Wed Jan 10 15:51:13 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 10 Jan 2007 21:51:13 +0100 Subject: Question about compiling. References: Message-ID: <87ac0qy5a6.fsf@smsnet.pl> Gabriel Genellina writes: > At Tuesday 9/1/2007 14:56, Steven W. Orr wrote: > >>I *just* read the tutorial so please be gentle. I created a file called >>fib.py which works very nicely thank you. When I run it it does what it's >>supposed to do but I do not get a resulting .pyc file. The tutorial says I >>shouldn't do anything special to create it. I have machines that have both >>2.4.1 and 2.3.5. Does anyone have an idea what to do? > > Welcome to Python! > When you run a script directly, no .pyc file is generated. Only when a > module is imported (See section 6.1.2 on the tutorial). And don't > worry about it... That's not the whole truth. :) If you want to compile your script, you can do that, of course: $ ls fib* fib.py $ python2.4 -mpy_compile fib.py $ ls fib* fib.py fib.pyc -- HTH, Rob From pierre.imbaud at laposte.net Tue Jan 30 16:46:42 2007 From: pierre.imbaud at laposte.net (Imbaud Pierre) Date: Tue, 30 Jan 2007 22:46:42 +0100 Subject: data design In-Reply-To: <1170183985.871094.155720@q2g2000cwa.googlegroups.com> References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> Message-ID: <45bfbcc3$0$30950$426a74cc@news.free.fr> Paddy a ?crit : > > On Jan 30, 2:34 pm, Imbaud Pierre wrote: > >>The applications I write are made of, lets say, algorithms and data. >>I mean constant data, dicts, tables, etc: to keep algorithms simple, >>describe what is peculiar, data dependent, as data rather than "case >>statements". These could be called configuration data. >> >>The lazy way to do this: have modules that initialize bunches of >>objects, attributes holding the data: the object is somehow the row of >>the "table", attribute names being the column. This is the way I >>proceeded up to now. >>Data input this way are almost "configuration data", with 2 big >>drawbacks: >> - Only a python programmer can fix the file: this cant be called a >> configuration file. >> - Even for the author, these data aint easy to maintain. >> >>I feel pretty much ready to change this: >>- make these data true text data, easier to read and fix. >>- write the module that will make python objects out of these data: >>the extra cost should yield ease of use. >> >>2 questions arise: >>- which kind of text data? >> - csv: ok for simple attributes, not easy for lists or complex >> data. >> - xml: the form wont be easier to read than python code, >> but an xml editor could be used, and a formal description >> of what is expected can be used. >>- how can I make the data-to-object transformation both easy, and able >> to spot errors in text data? >> >>Last, but not least: is there a python lib implementing at least part >>of this dream? > > Google for YAML and JSON formats too. > http://www.yaml.org/ > http://www.json.org/ > > -Paddy > Hurray for yaml! A perfect fit for my need! And a swell tool! Thanks a lot! From gagsl-py at yahoo.com.ar Fri Jan 5 08:28:40 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 10:28:40 -0300 Subject: Calculating Download Rate In-Reply-To: <1167998032.425050.264280@i15g2000cwa.googlegroups.com> References: <1167998032.425050.264280@i15g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070105102740.05c92b90@yahoo.com.ar> At Friday 5/1/2007 08:53, placid wrote: >I want be able to work the download rate for downloading HTML pages >using the urllib.urlopen(url). The way i thought i would do this is >start a timer (or log the current time) just before calling this >function and the stopping the timer (logging the current time again and >the working out the difference) this would give me duration that it >took to retrieve the web-page, not the download rate? Then, the download rate in bytes/sec would be (size of page in bytes)/(time elapsed in seconds) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From timr at probo.com Wed Jan 3 02:58:04 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 03 Jan 2007 07:58:04 GMT Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> Message-ID: "Ramdas" wrote: > >I need to add users from a web interface for a web server, which runs >only Python. I need to add users, set quotas and in future even look at >managing ip tables to limit bandwidth. > >I know os.system(), but this has to be done through a form entry >through a web interface. > >Anyways thanks, do advise if there more pythonic solutions os.system is perfectly Pythonic, and can be executed from a CGI script. The challenge is becoming root, which is necessary to do what you ask. You can write a simple C program that is setuid root that calls your script for you. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ptmcg at austin.rr.com Thu Jan 25 03:04:58 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Jan 2007 00:04:58 -0800 Subject: Fast Imaging for Webserver In-Reply-To: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> References: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> Message-ID: <1169712298.439101.171730@l53g2000cwa.googlegroups.com> On Jan 25, 12:46 am, "Prateek" wrote: > Concurrency Level: 1 > Time taken for tests: 18.664 seconds > Complete requests: 1000 > Failed requests: 0 > Broken pipe errors: 0 > Total transferred: 14680000 bytes > HTML transferred: 14417000 bytes > Requests per second: 53.58 [#/sec] (mean) > Time per request: 18.66 [ms] (mean) > Time per request: 18.66 [ms] (mean, across all concurrent > requests) > Transfer rate: 786.54 [Kbytes/sec] received > > FYI: This request returns a PNG image (image/png) and not html > > My understanding is that the problem is either with the CherryPy setup > (which is likely because even in other cases, i don't get much more > than 65 requests per second) or PIL itself (even though I'm caching the > background images and source images) > > Does anyone have a better solution? Is there a faster replacement for > PIL? > So you have some gross level statistics on how long a request takes to process, that's good. But before you start replacing PIL, or optimizing CherryPy, or other possible performance-improving efforts, you should profile the within-request processing, find the bottleneck, and take care of that first. Without profiling info, you can easily spend days optimizing out 90% of a task that takes 2% of the total processing time, for little net gain. -- Paul From fred at adventistcare.org Wed Jan 31 13:42:36 2007 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 31 Jan 2007 13:42:36 -0500 Subject: Python tools to manipulate JARs ? Message-ID: <1A4BF05172023E468CB6E867923BC90404B0CF6A@accmail2.sunbelt.org> I have not tried this, but... Assuming jython is out of the question???? You might want to try a simple java command line program you could run from popen -----Original Message----- From: python-list-bounces+frsells=adventistcare.org at python.org [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On Behalf Of Andy Dingley Sent: Wednesday, January 31, 2007 11:11 AM To: python-list at python.org Subject: Python tools to manipulate JARs ? I run build processes for a Java shop using Python (and some Ant). Would anyone care to suggest favoured tools for manipulating the innards of JARs? Or do I just treat them as plain zipfiles and get stuck right in there? Mainly I'm trying to query lists of classes and their embedded versions and do some library dependency reporting. Performance speed is starting to be an issue, as there's 1500+ classes in this bucket and it's an interactive query. Thanks for any suggestions -- http://mail.python.org/mailman/listinfo/python-list From no-spam at no-spam-no-spam.invalid Mon Jan 1 07:40:03 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Mon, 01 Jan 2007 13:40:03 +0100 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167526509.471697.320750@v33g2000cwv.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> Message-ID: Ben Sizer wrote: > Martin v. L?wis wrote: > >> 2. Many windows users (including myself) dislike setup routines that >> manipulate PATH. > > My opinion is that this is not as big a problem as some may feel that > it is. Unlike Unix systems, the PATH variable is rarely used. Most It is a big problem. It is not less than the majority of Python users (at least those who do things on the command line) who deal with multiple Python versions. This would create funny PATH variables - almost a "psychic behavior with history". I'd vote heavily against manipulating the PATH. Example: Just recently I had a lot of magical version problems with Borland stuff installers which by default and without question or noticeable checkboxes add naively (and multiple folders) to the PATH. And there were not just version mix-up problems - even things with same names of the C++ and the Pascal compilers and even stuff from old 16bit compilers wanted to deal with each other... "Default Links" - generally speaking - are by far better than PATHs regarding application level stuff. >> if Python is to be found in PATH, it >> should rather be installed to a directory that is known to live >> on PATH (or where CreateProcess searches, anyway, such >> as system32). So if the installer had such a feature, it should >> be optional, and it should default to "off". > > It's a lot more anti-social to install to system32 than to modify the > PATH variable. How easy is it to temporarily undo an installation to a > system directory like that? What if you still want Python in your path > but with less precedence than some other user directory? Uninstallation would be same as for the pythonXX.dll. A python(XX).exe next to the DLL would just be a natural consequence - the DLL already defined the policy. python.exe is nothing else than a DLL loader. Windows is at all less a multi user system. I don't even know a case where two (Python) Programmers use _one_ box and then also want separate Python's - just know home mates (parasites) who occasionally share the web browser or so... If one really wants multi user separate installations that clean, it is all necessary to create oneself something like ....\\bin \system32. Yet not different from Linux: a ~\bin on the PATH would be custom with most *unix default layouts also. Dealing with less and more precedence / PATH order is about the same issue : you have by far crossed the line from where you have to set yourself the PATH consciously. And multiple Python installers automatically establishing the right precedence on the PATH !? - with re.sub() :-) Putting a pythonXX.exe next to pythonXX.dll into system32 should be a non-q and a kind of default comfort for multi-python users. Linking also a default python.exe into the system32 upon a (non-default) checkbox mark in the installer should be simple, clear and do everything what 99.9% want - and most "compatible" to *nix. Robert From bj_666 at gmx.net Thu Jan 18 11:47:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 18 Jan 2007 17:47:25 +0100 Subject: How to read and write huge binary files References: <1169136850.518228.103360@l53g2000cwa.googlegroups.com> Message-ID: In <1169136850.518228.103360 at l53g2000cwa.googlegroups.com>, Lad wrote: > What is a good way to read binary data from HUGE file and write it > to another file? What about `shutil.copy()`? Ciao, Marc 'BlackJack' Rintsch From bearophileHUGS at lycos.com Thu Jan 18 18:26:03 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Jan 2007 15:26:03 -0800 Subject: Iterator length Message-ID: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> Often I need to tell the len of an iterator, this is a stupid example: >>> l = (i for i in xrange(100) if i&1) len isn't able to tell it: >>> len(l) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'generator' has no len() This is a bad solution, it may need too much memory, etc: >>> len(list(l)) This is a simple solution in a modern Python: >>> sum(1 for _ in l) 50 This is a faster solution (and Psyco helps even more): def leniter(iterator): """leniter(iterator): return the length of an iterator, consuming it.""" if hasattr(iterator, "__len__"): return len(iterator) nelements = 0 for _ in iterator: nelements += 1 return nelements Is it a good idea to extend the functionalities of the built-in len function to cover such situation too? Bye, bearophile From elrondrules at gmail.com Thu Jan 18 18:46:47 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 18 Jan 2007 15:46:47 -0800 Subject: Match 2 words in a line of file Message-ID: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> Hi Am pretty new to python and hence this question.. I have file with an output of a process. I need to search this file one line at a time and my pattern is that I am looking for the lines that has the word 'event' and the word 'new'. Note that i need lines that has both the words only and not either one of them.. how do i write a regexp for this.. or better yet shd i even be using regexp or is there a better way to do this.... thanks From dfj225 at gmail.com Thu Jan 11 13:43:15 2007 From: dfj225 at gmail.com (dfj225 at gmail.com) Date: 11 Jan 2007 10:43:15 -0800 Subject: dynamic library loading, missing symbols In-Reply-To: References: Message-ID: <1168540994.907072.114540@p59g2000hsd.googlegroups.com> On Jan 11, 3:40 am, "Ames Andreas" wrote: > Have you already checked the output of LD_DEBUG=all or sth. like that? Yes, that is how I initially knew that my libraries were not even being processed when the linker tried to bind the symbol. On Jan 10, 5:01 pm, "Martin v. L?wis" wrote: > > I suppose this means that any subsequent libraries dlopened will not > > see any of the symbols in my module? > That's correct, and intentional. Python has crashed in the past when > symbols conflicted across shared libraries. > > I guess I'll have to look through the Python documentation to see if > > they offer any work arounds to this problem. > There is sys.setdlopenflags, but I would use it with caution. Ok, thank you for pointing out sys.setdlopenflags. This allowed me to set the RTLD_GLOBAL flag and the linker to bind the symbol to my library's code. I realize that doing this is more or less a hack, but at least it will allow me to test my code until a better solution is created. Thank you both Martin and Andreas for taking the time to reply to my post. ~Doug From piet at cs.uu.nl Wed Jan 10 17:21:07 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 10 Jan 2007 23:21:07 +0100 Subject: Problem installing cElementTree on Python 2.5 Message-ID: I have just installed Python 2.5 on Mac OS X 10.4.8 on an iBook (PPC) from the dmg. Now I tried to install cElementTree -1.0.5-20 from source (no egg available in cheeseshop) and got the following compilation error: gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -DXML_STATIC -DHAVE_MEMMOVE=1 -DXML_NS=1 -DXML_DTD=1 -DBYTEORDER=4321 -DXML_CONTEXT_BYTES=1024 -Iexpat -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c cElementTree.c -o build/temp.macosx-10.3-fat-2.5/cElementTree.o gcc: cannot specify -o with -c or -S and multiple compilations error: command 'gcc' failed with exit status 1 Does anybody know how to solve this? As I don't need the universal binary I tried to strip the -arch i386 from the command above but that didn't help. I also removed the -c, but then the install failed in the next step. Has anybody succesfully installed cElementTree on this combination? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From gagsl-py at yahoo.com.ar Tue Jan 16 20:29:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 22:29:47 -0300 Subject: Check a windows service In-Reply-To: <1168985943.060145.54490@a75g2000cwd.googlegroups.com> References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> <1168967374.568967.173690@11g2000cwr.googlegroups.com> <1168985943.060145.54490@a75g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20070116221330.042ff630@yahoo.com.ar> At Tuesday 16/1/2007 19:19, awel wrote: >Sorry, but could you give me an example with a real service 'cause I've >tried this script but nothings happened, no error, nothings ; even if I >launch it in cmd prompt. You have to call the EnumServices function if you want some useful output. Copy&paste the code in a new file, add these 2 lines at the end, and save the file with a .py extension: if __name__=='__main__': EnumServices() Then execute it with: python your_file_name.py See http://diveintopython.org/getting_to_know_python/testing_modules.html to understand what's that; and read the whole book, it's a good tutorial if you already know another language. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at REMOVEME.cybersource.com.au Wed Jan 31 20:45:28 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 01 Feb 2007 12:45:28 +1100 Subject: how to "free" an object/var ? References: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> <1170264406.588032.116550@s48g2000cws.googlegroups.com> Message-ID: On Wed, 31 Jan 2007 09:26:46 -0800, Paddy wrote: > On Jan 31, 7:34 am, Steven D'Aprano > wrote: [snip] >> -- >> Steven D'Aprano > > Thanks Stephen for explaining my answer a bit more. Ste_ph_en??? I know the ph-form of the name is marginally more popular, but dammit my name is right there just two lines above where Paddy started typing, how hard is it to get it right? It's not like I spell my name with four M's and a silent Q like the famous author Farles Wickens *wink* -- Steven D'Aprano who thinks there can never be too many Monty Python references From S.Mientki-nospam at mailbox.kun.nl Fri Jan 12 17:21:27 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 12 Jan 2007 23:21:27 +0100 Subject: Portable Python - free portable development environment ! In-Reply-To: <1168639781.763133.319580@s34g2000cwa.googlegroups.com> References: <1168533423.224355.221390@k58g2000hse.googlegroups.com> <1168639781.763133.319580@s34g2000cwa.googlegroups.com> Message-ID: perica.zivkovic at gmail.com wrote: > Right now there is not a big difference with Movable Python. > - Smaller size but less libraries in default package > - Portable Python comes with django > - Uses SciTE not SPE > > but this is first release and I have big plans ;) > any plans for a something like the Enthought-edition ? cheers, Stef Mientki From bborcic at gmail.com Thu Jan 25 13:22:09 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 25 Jan 2007 19:22:09 +0100 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <4866bea60701250609u61e72d30q21dd11c8c8fd9bcd@mail.gmail.com> References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> <4866bea60701240736v837d246w187ecb1ccb90eefd@mail.gmail.com> <4866bea60701250609u61e72d30q21dd11c8c8fd9bcd@mail.gmail.com> Message-ID: Chris Mellon wrote: > On 1/25/07, Boris Borcic wrote: >> Chris Mellon wrote: >>>>> >>>>> Some quick & dirty wxPython code >>>>> >>>>> def getTextBitmap(text, font, fgcolor, bgcolor): >>>>> dc = wx.MemoryDC() >>>>> dc.SetFont(font) >>>>> width, height= dc.GetTextExtent(text) >>>>> bmp = wx.EmptyBitmap(width, height) >>>>> dc.SelectObject(bmp) >>>>> dc.SetBackground(wx.Brush(bgcolor)) >>>>> dc.Clear() >>>>> dc.SetTextBackground(bgcolor) >>>>> dc.SetTextForeground(fgcolor) >>>>> dc.DrawText(text, 0, 0) >>>>> dc.SelectObject(wx.NullBitmap) >>>>> return bmp >>>>> >>>>> >>>>> Raw win32 code will look similar but will be much more verbose. >>>> Thx again for this base. >>>> >>>> Quickly testing this, it appears that the result is rendered half a pixel off in >>>> the x-direction. Does this make sense ? Is it possible to position text with >>>> subpixel accuracy ? >> In short, wx._gdi_ fights quite hard to enforce what I am trying to avoid :( I >> might admire its consistency if it extended to treating both axes similarly... >> > > I have not recently had a need to examine drawn text output this > closely, but I am familiar with the C++ code that implements the > drawing and it's a direct wrapping of win32 GDI calls. If it's not > matching your source text, then the source may be drawn using a > different method or using one of the alternate engines, like GDI+. Maybe. In any case, color separation solves my (sub)problem : the blue layer from the wx generated model matches the green layer from the app's window, pixel for pixel (at least with antialiasing and cleartype on, while writing black on white). Best, Boris Borcic From s.mientki at id.umcn.nl Tue Jan 16 10:24:45 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 16 Jan 2007 16:24:45 +0100 Subject: Projects anyone? In-Reply-To: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> References: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> Message-ID: placid wrote: > Hi all, > > I'm looking for anyone who is working on a project at the moment that > needs help (volunteer). The last project i worked on personally was > screen-scraping MySpace profiles (read more at the following link) > > http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles > > > but that didn't go all to well, so im kinda bored and need something to > do, with Python. So any suggestions anyone? > > Cheers > > hello Chad, I would have expected lots of reactions on your message, buts as there's still none, I'll kick of. I don't know what your knowledge and interests and I'm just a completely newbie in Python (3..4 weeks), so I might not have a good overview, but coming from MatLab (and I'm not the only one who is thinking of switching to Python ;-) there are a couple of fairly general modules that I'm missing in Python: - SimuLink - (PowerSim) cheers, Stef Mientki From krypto.wizard at gmail.com Wed Jan 31 21:42:54 2007 From: krypto.wizard at gmail.com (krypto.wizard at gmail.com) Date: 31 Jan 2007 18:42:54 -0800 Subject: division by 7 efficiently ??? Message-ID: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> How to divide a number by 7 efficiently without using - or / operator. We can use the bit operators. I was thinking about bit shift operator but I don't know the correct answer. From ktenney at gmail.com Sun Jan 28 21:23:20 2007 From: ktenney at gmail.com (Kent Tenney) Date: 28 Jan 2007 18:23:20 -0800 Subject: Problems with ElementTree and ProcessingInstruction In-Reply-To: References: <1169994480.424321.51600@m58g2000cwm.googlegroups.com> Message-ID: <1170037400.357531.35310@a34g2000cwb.googlegroups.com> On Jan 28, 7:46 pm, Gabriel Genellina wrote: > At Sunday 28/1/2007 11:28, Kent Tenney wrote: > > >I want to generate the following file; > > > > > > >stuff > > >How should I be doing this?open("filename","w").write('\n' > '\n' > 'stuff\n') Right. I can use ElementTree.write('filename') and prepend the instructions to the resulting file. It leaves me curious as to the purpose/usage of ProcessingInstruction() Thanks, Kent > > :) > > >As far as I can tell, ElementTree() requires everything > >to be inside the root element (leo_file)Just keep the first two lines on my example... > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya!http://www.yahoo.com.ar/respuestas From Thomas.Ploch at gmx.net Thu Jan 4 22:56:39 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 04:56:39 +0100 Subject: What is proper way to require a method to be overridden? In-Reply-To: <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> Message-ID: <459DCC77.2030708@gmx.net> Gabriel Genellina schrieb: > At Thursday 4/1/2007 23:52, jeremito wrote: > >> I am writing a class that is intended to be subclassed. What is the >> proper way to indicate that a sub class must override a method? > > If any subclass *must* override a method, raise NotImplementedError in > the base class (apart from documenting how your class is supposed to be > used). > > I learn so much from this list. I didn't even know this error existed. Thomas From paul.sijben at xs4all.nl Wed Jan 10 06:48:47 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 12:48:47 +0100 Subject: convert binary data to int In-Reply-To: <1168424278.193439.216770@k58g2000hse.googlegroups.com> References: <1168424278.193439.216770@k58g2000hse.googlegroups.com> Message-ID: <45A4D29F.3050207@xs4all.nl> in some cases struct.unpack would also help rubbishemail at web.de wrote: > Hello, > > > I need to convert a 3 byte binary string like > "\x41\x00\x00" to 3 int values ( (65,0,0) in this case). > The string might contain characters not escaped with a \x, like > "A\x00\x00" > > > Any ideas? > > > Daniel > From zhangry at feng.co.jp Tue Jan 16 03:57:57 2007 From: zhangry at feng.co.jp (HYRY) Date: 16 Jan 2007 00:57:57 -0800 Subject: why scipy cause my program slow? In-Reply-To: References: <1168935124.912419.147250@a75g2000cwd.googlegroups.com> Message-ID: <1168937877.189713.239360@38g2000cwa.googlegroups.com> Thanks, by your hint, I change type(data) to type(data[0]), and I get So, calculate with float is about 5x faster numpy.float64. Robert Kern wrote: > HYRY wrote: > > Why the exec time of test(readdata()) and test(randomdata()) of > > following program is different? > > my test file 150Hz10dB.wav has 2586024 samples, so I set randomdata > > function > > to return a list with 2586024 samples. > > the exec result is: > > 2586024 > > > > 10.8603842736 > > 2586024 > > > > 2.16525233979 > > test(randomdata()) is 5x faster than test(readdata()) > > if I remove "from scipy import *" then I get the following result: > > 2586024 > > > > 2.21851601473 > > 2586024 > > > > 2.13885042216 > > > > So, what the problem with scipy? > > You're importing (through scipy) numpy's sum() function. The result type of that > function is a numpy scalar type. The set of scalar types was introduced for a > number of reasons, mostly having to do with being able to represent the full > range of numerical datatypes that Python does not have builtin types for. > Unfortunately, the code paths that get executed when arithmetic is performed > sith such scalars are still suboptimal; I believe they are still going through > the full ufunc machinery. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From gagsl-py at yahoo.com.ar Wed Jan 10 04:36:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Jan 2007 06:36:36 -0300 Subject: Why less emphasis on private data? In-Reply-To: <019e01c7348c$1cae4fc0$03000080@hendrik> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> <019e01c7348c$1cae4fc0$03000080@hendrik> Message-ID: <7.0.1.0.0.20070110063347.05095e20@yahoo.com.ar> At Wednesday 10/1/2007 04:33, Hendrik van Rooyen wrote: >Oh I am of the opposite conviction - Like the fellow of the Circuit Cellar >I forget his name ( Steve Circia (?) ) who said: "My favourite Programming >Language is Solder".. Almost right: Steve Ciarcia. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ray223 at gmail.com Tue Jan 16 17:21:52 2007 From: ray223 at gmail.com (ray223 at gmail.com) Date: 16 Jan 2007 14:21:52 -0800 Subject: How can I create a linked list in Python? In-Reply-To: References: Message-ID: <1168986110.770209.161340@11g2000cwr.googlegroups.com> Dongsheng Ruan wrote: > with a cell class like this: > > #!/usr/bin/python > > import sys > > class Cell: > > def __init__( self, data, next=None ): > self.data = data > self.next = next > > def __str__( self ): > return str( self.data ) > > def echo( self ): > print self.__str__() Hi, The "How to Think Like a Computer Scientist" free book has a chapter just for this topic: http://greenteapress.com/thinkpython/html/chap17.html Regards, Ray Smith http://RaymondSmith.com From rweth at cisco.com Sat Jan 6 14:13:30 2007 From: rweth at cisco.com (rweth) Date: Sat, 06 Jan 2007 11:13:30 -0800 Subject: Adding a directory to the Python System Path - Edit the registry? In-Reply-To: <1168057627.305211.151320@s34g2000cwa.googlegroups.com> References: <1168017552.010631.276080@s34g2000cwa.googlegroups.com> <459e8fa5$0$335$e4fe514c@news.xs4all.nl> <1168057627.305211.151320@s34g2000cwa.googlegroups.com> Message-ID: <1168110810.676546@sj-nntpcache-1.cisco.com> redefined.horizons at gmail.com wrote: > Thanks Martin. > > I'll take a look at the documentation you pointed out. > > Scott > > Martin P. Hellwig wrote: >> redefined.horizons at gmail.com wrote: >>> I have been trying to find a way to add a directory to Python's sytem >>> path on my MS Windows XP computer. I did some searching online, but the >>> only solution I found involved editing the MS Windows Registry. That >>> seemed a little to hard core. Is there another easier way to do this? >>> >>> Thanks, >>> >>> Scott Huey >>> >> Take a look at: >> http://docs.python.org/tut/node8.html >> >> Specifically 6.1.1 and 6.2, perhaps that might answer your question. >> >> Cheers >> >> -- >> mph > There is a file you can use to extend your system path on my windows box it is here: C:\Python24\Lib\site-packages\package.pth Inside the package.pth I have added: C:\\QA\\bin I think I needed to do this in linux as well (and it worked). Find your installation path to ../Lib/site-packages and if that file does not exist create it and add your paths in their own lines no separators needed. From kavithapython at yahoo.co.in Tue Jan 23 03:25:35 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Tue, 23 Jan 2007 08:25:35 +0000 (GMT) Subject: newbie question In-Reply-To: <45B49B6E.8040900@portaone.com> Message-ID: <550243.47113.qm@web7805.mail.in.yahoo.com> Hi Eugene, I tried with conn.commit() as well,,but doesnt seem to work. Also i cannot even view the existing tables via python script.For example,,,i have manually added a customer table in my database.but if i execute the query, select * from customer,,,i get the following error: mxODBC.ProgrammingError: ('S0002', 208, "[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name customer.", 4612) If someone knows the solution please help me,,, Kavitha Eugene Antimirov wrote: Eugene Antimirov wrote: > You've probably missed cursor.commit() ;) Sorry, my bad: conn.commit() is correct one AFAIR. -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer support at portaone.com * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Wed Jan 31 21:51:40 2007 From: http (Paul Rubin) Date: 31 Jan 2007 18:51:40 -0800 Subject: division by 7 efficiently ??? References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: <7xtzy6twsj.fsf@ruckus.brouhaha.com> krypto.wizard at gmail.com writes: > How to divide a number by 7 efficiently without using - or / operator. > We can use the bit operators. I was thinking about bit shift operator > but I don't know the correct answer. Erm, sounds like a homework problem... suggestion: think of how many input bits you have, then check the accuracy of the obvious approximations until you reach one that's precise enough. From opengeometry at yahoo.ca Tue Jan 23 18:01:20 2007 From: opengeometry at yahoo.ca (William Park) Date: Tue, 23 Jan 2007 18:01:20 -0500 Subject: spidering script References: <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d@fdn.com> Message-ID: In David Waizer wrote: > Hello.. > > I'm looking for a script (perl, python, sh...)or program (such as wget) > that will help me get a list of ALL the links on a website. lynx -dump (look at the bottom) -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Super Bash shell http://freshmeat.net/projects/bashdiff/ From 12cc104 at gmail.com Mon Jan 8 03:28:42 2007 From: 12cc104 at gmail.com (proctor) Date: 8 Jan 2007 00:28:42 -0800 Subject: regex question References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> <1168243020.304940.212700@42g2000cwt.googlegroups.com> Message-ID: <1168244922.620428.273260@38g2000cwa.googlegroups.com> Steven D'Aprano wrote: > On Sun, 07 Jan 2007 23:57:00 -0800, proctor wrote: > > > it does work now...however, one more question: when i type: > > > > rx_a = re.compile(r'a|b|c') > > it works correctly! > > > > shouldn't: > > rx_a = re.compile(makeRE(test)) > > give the same result since makeRE(test)) returns the string "r'a|b|c'" > > Those two strings are NOT the same. > > >>> s1 = r'a|b|c' > >>> s2 = "r'a|b|c'" > >>> print s1, len(s1) > a|b|c 5 > >>> print s2, len(s2) > r'a|b|c' 8 > > A string with a leading r *outside* the quotation marks is a raw-string. > The r is not part of the string, but part of the delimiter. > > A string with a leading r *inside* the quotation marks is just a string > with a leading r. It has no special meaning. > > > > -- > Steven D'Aprano thanks steven, is there any way i would be successful then, in using raw string inside my makeRE() function? proctor. From sean at datafly.net Tue Jan 23 03:01:12 2007 From: sean at datafly.net (Sean Schertell) Date: Tue, 23 Jan 2007 17:01:12 +0900 Subject: How to use dynamic properties? <-- Noob Message-ID: person.name = 'Joe' person.age = 20 person.sex = 'm' info_I_need = name print person.info_I_need # How can I make it print 'Joe' ? Sean :::: DataFly.Net :::: Complete Web Services http://www.datafly.net From smusnmrNOSPAM at yahoo.com Fri Jan 5 08:57:25 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Fri, 5 Jan 2007 14:57:25 +0100 Subject: where to find wx package References: Message-ID: Thanks to you, too, Robert! siggi "Robert Kern" schrieb im Newsbeitrag news:mailman.2318.1167991773.32031.python-list at python.org... > siggi wrote: >> Hi all, >> >> a newbie question: >> >> I have a program gui03A.py using wxPython, importing it such: >> "from wxPython.wx import *" >> >> The program works, but I get the warning message: >> >> "gui03A.py:4: DeprecationWarning: The wxPython compatibility package is >> no >> longer automatically generated or activly maintained. Please switch to >> the >> wx package as soon as possible." >> >> However, after extensive searching on www.python.org and Googling the >> web, I >> do not find any package with "wx" as its only name. >> >> Where can I get the wx package (for win32 XP)? > > It's the same project (from the people at www.wxpython.org), they just > renamed > the package. You already have it installed. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless > enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > From tkpmep at hotmail.com Wed Jan 17 11:31:07 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 17 Jan 2007 08:31:07 -0800 Subject: Globbing files by their creation date References: <1168954453.954486.188680@m58g2000cwm.googlegroups.com> <6L2dnaxFNt0tqzDYnZ2dnUVZ_vPinZ2d@99main.com> Message-ID: <1169051467.179899.178570@s34g2000cwa.googlegroups.com> Thanks a mill - os.path.getctime(f) is what I needed. Unfortunately, my attempts to turn the integer it returns into a date have failed. >>> os.path.getctime(fn) #fn was created today, 1/17/2007 1168955503 I tried to convert this to a date object by typing >>>datetime.date.fromordinal(1168955503) Traceback (most recent call last): File "", line 1, in -toplevel- datetime.date.fromordinal(1168955503) ValueError: year is out of range How can I do the conversion? I'm trying to identify all files that were created after YYYY/MM/DD. For a quick sanity check, I ran >>> datetime.date.today().toordinal() 732693 which is orders of magnitude smaller than the number returned by os.path.getctime(fn). Thanks in advance for your help Thomas Philips From nospam at nospam.com Mon Jan 29 21:26:30 2007 From: nospam at nospam.com (Hampton Din) Date: Mon, 29 Jan 2007 20:26:30 -0600 Subject: Excellent Interview with Dennis D'Souza, full of laughs References: <1170083292.991070.79560@v33g2000cwv.googlegroups.com> <45be1d27$0$97248$892e7fe2@authen.yellow.readfreenews.net> <1170087497.071441.118560@s48g2000cws.googlegroups.com> <6Mqvh.5640$fC2.95@bignews4.bellsouth.net> <1170114420.772278.7130@a75g2000cwd.googlegroups.com> Message-ID: <45beacc4$0$97225$892e7fe2@authen.yellow.readfreenews.net> still a stupid troll. From aboudouvas at panafonet.gr Fri Jan 5 07:00:49 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 5 Jan 2007 04:00:49 -0800 Subject: program deployment Message-ID: <1167998448.978001.3720@38g2000cwa.googlegroups.com> hi to all folks here, i am learning Python, just finished a book and i am starting to write programs. I just want to ask, is the "correct" way to deploy my programs to other computers, the .pyc files ?? I now that with the "-m compileall ." switch can compile a .py file into bytecodes. So i suppose that if Python has to run a .pyc file, it will load and execute it faster. And if i have some "sensitive" data in my source, like passwords (and the source of cource!) they will be more secure in a compiled file. Is that correct ? Thanks a lot for any help! From eurleif at ecritters.biz Mon Jan 29 00:09:48 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 29 Jan 2007 00:09:48 -0500 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170046719.708692.243290@s48g2000cws.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: <45bd8130$0$17928$4d3efbfe@news.sover.net> NoName wrote: > from random import choice > import string > print ''.join([choice(string.letters+string.digits) for i in > range(1,8)]) > > !!generate password once :( So add a while true: line. > who can write this smaller or without 'import'? Why are those your goals? From nanjundi at gmail.com Sun Jan 21 17:35:19 2007 From: nanjundi at gmail.com (Nanjundi) Date: 21 Jan 2007 14:35:19 -0800 Subject: instancemethod In-Reply-To: References: Message-ID: <1169418918.963891.196080@m58g2000cwm.googlegroups.com> > > if __name__ == '__main__': > gert=Db('localhost','root','******','gert') > gert.excecute('select * from person') > for x in range(0,gert.rowcount): > print gert.fetchone() > gert.close() > > gert at gert:~$ python ./Desktop/svn/db/Py/db.py > Traceback (most recent call last): > File "./Desktop/svn/db/Py/db.py", line 35, in > for x in range(0,gert.rowcount): > TypeError: range() integer end argument expected, got instancemethod. > gert at gert:~$ > > Can anybody explain what i must do in order to get integer instead of > a instance ? Gert, > for x in range(0,gert.rowcount): gert.rowcount is the method (and not a data attribute). gert.rowcount() is the method call, which get the return value from method. So try this. for x in range( 0,gert.rowcount() ): -N From bj_666 at gmx.net Sun Jan 28 02:33:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 28 Jan 2007 08:33:32 +0100 Subject: import from future References: <1169969100.946843.111770@p10g2000cwp.googlegroups.com> Message-ID: In <1169969100.946843.111770 at p10g2000cwp.googlegroups.com>, lee wrote: > what are the things that we can do with import from future usage.....i > heard its very interesting......thanks Here's how to find out yourself (done with a 2.4 release): In [2]: import __future__ In [3]: dir(__future__) Out[3]: ['CO_FUTURE_DIVISION', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'all_feature_names', 'division', 'generators', 'nested_scopes'] In [4]: __future__.all_feature_names Out[4]: ['nested_scopes', 'generators', 'division'] In [5]: __future__.division Out[5]: _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192) In [6]: help(__future__) Ciao, Marc 'BlackJack' Rintsch From tim at tdw.net Sat Jan 13 06:23:57 2007 From: tim at tdw.net (Tim Williams) Date: Sat, 13 Jan 2007 11:23:57 +0000 Subject: WMI Python, writing remotely and retrieving env variables values In-Reply-To: References: <1168637924.982266.214250@s34g2000cwa.googlegroups.com> Message-ID: <9afea2ac0701130323v3e39080o44c85596a7874916@mail.gmail.com> On 13 Jan 2007 02:01:11 -0800, Tim Golden wrote: > Thierry Lam wrote: > > I'm using the WMI library for python and I was able to connect to > > another computer on the network with the following line: > > > > c = wmi.WMI(computer="the-network-computer", user="hello", > > password="hello") > > > > Is there a way to write information to a file on that computer? > > > > How do I read environment variables, for example SystemDrive? > > Questions of this sort are really Win32 questions rather than Python > questions. That's not to say we can't help, but rather that you can > probably find an answer by going to a search engine of your choice > and typing in, say, "WMI SystemDrive". I did that, and the first hit > (from Google) was: > > http://msdn2.microsoft.com/en-us/library/aa394239.aspx > > which indicates that it's available from the Win32_OperatingSystem > WMI class. So, in Python: > > > import wmi > c = wmi.WMI () # optionally on another computer > for os in c.Win32_OperatingSystem (): > print os # show the whole thing > print os.SystemDrive # get only what you want > > > > If you were after Environment Variables, then search again, > this time for "WMI Environment Variables". Third hit: > > http://msdn2.microsoft.com/en-us/library/aa394143.aspx > > pointing to the Win32_Environment class. And so on. > > Your first question: can I write into a file? is a little > more tricky. As far as I know, there's no way even to > *create* a file with WMI, let alone write information into > it. It's not really a file-manipulation technology. You can > get hold of the name of a remote file and other of its > properties via the CIM_DataFile class, but you'd have > to translate that into an accessible UNC to be able to > access it. > One possibility is to create a hidden share on the remote computer and write to a file on it. Shares ending in $ are hidden, the unc path would be \\machinename\share$ According to http://msdn2.microsoft.com/en-us/library/aa394594.aspx you need the WMI Win32_Share class and the Create method. HTH :) From gagsl-py at yahoo.com.ar Thu Jan 11 23:05:45 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Jan 2007 01:05:45 -0300 Subject: Python nuube needs Unicode help In-Reply-To: <1168550858.233814.292900@p59g2000hsd.googlegroups.com> References: <1168550858.233814.292900@p59g2000hsd.googlegroups.com> Message-ID: <7.0.1.0.0.20070112004929.05978ec8@yahoo.com.ar> At Thursday 11/1/2007 18:27, gheissenberger at gmail.com wrote: >HELP! >Guy who was here before me wrote a script to parse files in Python. > >Includes line: >print u >where u is a line from a file we are parsing. >However, we have started recieving data from Brazil. If I open file to >parse in VI, looks like: > >audio="313-20070102144528.wav" grammarSet="G3" rawText="não" >recValue="{data:CHOICE=NO;}" conf="970" rawText2="" conf2="0" >transcribedText="não" parsableText="não"/ Is this part of an XML document? You should use a true XML parser instead of doing that by hand. >Clearly those "nã" are some non-Ascii characters, but how do I get >print to understand that? Understanding how Unicode works may be very useful: http://www.amk.ca/python/howto/unicode >I keep getting: >"UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in >position 40: > ordinal not in range(128)" py> u = u"?????" py> print u, repr(u) ????? u'\xe1\xe9\xed\xf3\xfa' py> print str(u) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordin al not in range(128) py> print u.encode('cp850') ????? (cp850 is my console encoding) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From eurleif at ecritters.biz Wed Jan 10 19:06:32 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 10 Jan 2007 19:06:32 -0500 Subject: Legally correct way of copying stdlib module? Message-ID: <45a57f65$0$15152$4d3efbfe@news.sover.net> I'm writing a package where I need to use the uuid module. Unfortunately, that module is only available in Python 2.5, and my package needs to be compatible with 2.4. I'm planning to copy it from Python 2.5's stdlib into my package, and import it like this: try: import uuid except ImportError: from mypackage import _uuid as uuid However, I'm concerned about how to do this in a legal way. uuid.py is presumably released under the Python license, but the file itself includes no mention of this. Should I copy the Python license as a comment into my _uuid.py? Do I need a copyright statement too (and if so, how do I know who owns the copyright to that particular module)? From robert.kern at gmail.com Sat Jan 20 17:55:56 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 20 Jan 2007 16:55:56 -0600 Subject: scipy.optimize.lbfgsb help please!!! In-Reply-To: References: Message-ID: mclaugb wrote: > Does anyone out there have a piece of code that demonstrates the use of the > lbfgsb multivariate, bounded solver in the scipy.optimize toolkit? An > example would get me started because my code below does not seem to work. You will probably get better/faster/more answers on the scipy-user mailing list. http://www.scipy.org/Mailing_Lists > Permmin is a function that simply returns a vector array [xmin, ymin] This is your problem. The function to minimize must return a scalar, not a vector. This is not a multi-objective optimizer. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bearophileHUGS at lycos.com Sun Jan 14 15:04:56 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Jan 2007 12:04:56 -0800 Subject: help with recursion on GP project In-Reply-To: <45aa8784$0$5803$4c368faf@roadrunner.com> References: <45aa8784$0$5803$4c368faf@roadrunner.com> Message-ID: <1168805096.401513.106040@q2g2000cwa.googlegroups.com> First possible raw solution: from operator import add, sub, mul, div, neg def evaluate(expr): if isinstance(expr, list): fun, ops = expr[0], expr[1:] return fun(*map(evaluate, ops)) else: return expr example = [add, [add, [sub, 5, 4], [mul, 3, 2]], [neg, 5]] print evaluate(example) But it's rather slow... Bye, bearophile From carsten at uniqsys.com Wed Jan 10 17:31:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 10 Jan 2007 17:31:19 -0500 Subject: where to find the spec of format in PyObject_CallMethod In-Reply-To: <1168466755.996033.130120@i39g2000hsf.googlegroups.com> References: <1168466755.996033.130120@i39g2000hsf.googlegroups.com> Message-ID: <1168468279.3413.31.camel@dot.uniqsys.com> On Wed, 2007-01-10 at 14:05 -0800, Huayang Xia wrote: > I am trying to use PyObject_CallMethod. It needs a format string to > specify what are the followed arguments. Is it possible to use a > PyObject* as an argument? > > Where can I find the spec for the format? > > Thanks in advance. See http://docs.python.org/api/object.html#l2h-247 : Note in particular "The C arguments are described by a Py_BuildValue() format string that should produce a tuple" and "Note that if you only pass PyObject * args, PyObject_CallMethodObjArgs is a faster alternative." So, If all your arguments are PyObject pointers, use PyObject_CallMethodObjArgs instead. Otherwise, use PyObject_CallMethod and consult the documentation for Py_BuildValue on how to construct the format string. Hope this helps, Carsten. From george.sakkis at gmail.com Thu Jan 25 12:26:01 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 25 Jan 2007 09:26:01 -0800 Subject: assertions to validate function parameters In-Reply-To: References: Message-ID: <1169745961.524921.155070@v33g2000cwv.googlegroups.com> On Jan 25, 11:54 am, Matthew Wilson wrote: > Lately, I've been writing functions like this: > > def f(a, b): > > assert a in [1, 2, 3] > assert b in [4, 5, 6] > > The point is that I'm checking the type and the values of the > parameters. > > I'm curious how this does or doesn't fit into python's duck-typing > philosophy. > > I find that when I detect invalid parameters overtly, I spend less time > debugging. > > Are other people doing things like this? Any related commentary is > welcome. > > Matt Well, duck (or even static for that matter) typing can't help you if you're checking for specific *values*, not types. The real question is rather, is f() intended to be used in the "outside world" (whatever this might be; another program, library, web service, etc.) or is it to be called only by you in a very controlled fashion ? In the first case, passing an invalid input is a *user error*, not a *programming error*. Assertions should be used for programming errors only to assert invariants, statements which should be correct no matter what; their violations mean that the code is buggy and should be fixed asap. User errors OTOH should be handled by explicit checking and raising appropriate exceptions, e.g. ValueError or a subclass of it. There are several reasons for this but a very practical one is that a user can turn off the assertions by running python with '-O' or '-OO'. Optimization flags should never change the behavior of a program, so using assertions for what's part of the normal program behavior (validating user-provided input) is wrong. George From skip at pobox.com Fri Jan 19 19:05:56 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 19 Jan 2007 18:05:56 -0600 Subject: float comparison confusion In-Reply-To: <1169250923.146916.206430@s34g2000cwa.googlegroups.com> References: <1169250923.146916.206430@s34g2000cwa.googlegroups.com> Message-ID: <17841.23780.872739.936331@montanaro.dyndns.org> chrolson> Why is cmp returning -1 instead of returning positive integer? Last time I checked 20.1 was less than 20.9. Skip From martin at v.loewis.de Mon Jan 8 02:48:22 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 08 Jan 2007 08:48:22 +0100 Subject: Module to read svg In-Reply-To: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> References: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> Message-ID: <45a1f746$0$27874$9b622d9e@news.freenet.de> schpok at gmail.com schrieb: > Does anyone know if there's an actual free implementation of this? For the dom module in it, xml.dom.minidom should work. Depending on your processing needs, that might be sufficient. Regards, Martin From s.mientki at id.umcn.nl Mon Jan 22 03:38:37 2007 From: s.mientki at id.umcn.nl (stef) Date: Mon, 22 Jan 2007 09:38:37 +0100 Subject: Python Windows Editors In-Reply-To: References: <79e7c$45b3facb$d443bb3a$7251@news.speedlinq.nl> Message-ID: <5ec4b$45b47813$83aef404$7970@news1.tudelft.nl> gonzlobo wrote: > I prefer PyScripter too, but would like to know if I can have > 'indentation guides' enabled like PythonWin allows. If you mean, typing a for-statement, then when placing the final ":"+Enter, the indentation auto increases, then the answer is yes, otherwise I don't kno what you mean. cheers, Stef Mientki From ptmcg at austin.rr._bogus_.com Tue Jan 9 07:11:25 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 9 Jan 2007 06:11:25 -0600 Subject: A simple array in Python References: <1168337391.770307.54750@11g2000cwr.googlegroups.com> Message-ID: <45a3866c$0$5805$4c368faf@roadrunner.com> wrote in message news:1168337391.770307.54750 at 11g2000cwr.googlegroups.com... > Hi, > > I have the following enum - > > class State: > Fire = 0 > Water = 1 > Earth = 2 > > And I want a variable which holds a value for each of these states, > something like - > > myState1[State.Fire] = 10 > myState1[State.Earth] = 4 > > myState2[State.Fire] = 20 > myState2[State.Earth] = 24 > > How do I do this? > > Thanks Barry. > How about (arrays are sooo last century): class State(object): def __init__(self,**kwargs): self.__dict__.update(kwargs) myState1 = State(Fire=10, Earth=4) myState2 = State(Fire=20, Earth=24) print myState1.Fire print myState2.Earth -- Paul From redefined.horizons at gmail.com Fri Jan 5 12:15:42 2007 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 5 Jan 2007 09:15:42 -0800 Subject: Dividing integers...Convert to float first? Message-ID: <1168017342.255981.134400@11g2000cwr.googlegroups.com> I'm still pretty new to Python. I'm writing a function that accepts thre integers as arguments. I need to divide the first integer by te second integer, and get a float as a result. I don't want the caller of the function to have to pass floats instead of integers. How do I convert the arguments passed to the function into floats before I do the division? Is this necessary, or is their a better way? Thanks, Scott Huey From luismgz at gmail.com Tue Jan 9 22:50:57 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 9 Jan 2007 19:50:57 -0800 Subject: Python - C# interoperability In-Reply-To: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> References: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> Message-ID: <1168401054.044692.187040@77g2000hsv.googlegroups.com> mc wrote: > Is there an easy way to compile a Python class (or set of classes) into > a .DLL that a C# program can call? Or otherwise to use an existing > library of Python classes from a C# program as seamlessly as possible? I'm affraid this is not possible. Ironpython (the .NET python implementation) can consume assemblies written in other statically typed languages, such as c#, but not the other way around. This is because Ironpython is still a dynamic language, and the lack of type information makes it impossible to be compiled as c#. For the time being, if you really need to write reusable assemblies that could be consumed from other .NET languages, you shouldn't use Ironpython. You should use c#, vb.net or any other static language implementation for .NET. If you want a more "pythonic" alternative, you could use Boo ( http://boo.codehaus.org ). It's a static language with a python-like syntax, and it's very easy to pick up if you already know python. For consuming Boo assemblies from Ironpython, you should compile them as .DLL, and place them into a "DLLs" folder in your Ironpython root directory (where ipy.exe is located). Then you simply import them as you would with any other python module. Make sure to add also the boo assembly. If you are using c# instead, you don't have to add anything else. Hope this helps, Luis From larry.bates at websafe.com Tue Jan 9 16:11:52 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 09 Jan 2007 15:11:52 -0600 Subject: Summarizing data by week In-Reply-To: <1168372624.543712.149070@77g2000hsv.googlegroups.com> References: <1168372624.543712.149070@77g2000hsv.googlegroups.com> Message-ID: Mike Orr wrote: > What's the best way to summarize data by week? I have a set of > timestamped records, and I want a report with one row for each week in > the time period, including zero rows if there are weeks with no > activity. I was planning to use ISO weeks because datetime has a > convenient .isocalendar() method, but I want each output row to have a > label like this: > > 2006 week 5 (Feb) > > However, to get the month (of the Thursday of that week) I have to > convert it back to an actual date,and I don't see a method to do that > in datetime or dateutil or mx.DateTime. > > I was planning to use a dateutil.rrule to generate the weeks from the > minimum to maximum date, including any weeks that have no activity (so > they won't be in the dictionary). But rrule sequences are based on an > actual start date, not an ISO week, so that won't work. Unless perhaps > I take the minimum date and calculate the Thursday of that week, and > start from there. Then all my conversions would be to iso_week rather > than from iso_week. > > Is there a better way to do this? > > --Mike > Generally I always check the day of week (DOW) of the beginning and ending dates in the sequence and adjust them so that they align with "real" weeks. Then it is usually as easy as adding 7 days inside the loop to increment each row. I'm not 100% sure I understand the problem but perhaps this will help. -Larry From cvanarsdall at mvista.com Fri Jan 26 12:26:43 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 26 Jan 2007 09:26:43 -0800 Subject: The reliability of python threads In-Reply-To: <01b001c7411d$17e52a20$03000080@hendrik> References: <45B90118.5010408@mvista.com> <01b001c7411d$17e52a20$03000080@hendrik> Message-ID: <45BA39D3.7020400@mvista.com> Hendrik van Rooyen wrote: > "Carl J. Van Arsdall" wrote: > > >> [snip] >> > > Are you 100% rock bottom gold plated guaranteed sure that there is > not something else that is also critical that you just haven't realised is? > 100%? No, definitely not. I know myself, as I explore this option and other options, I will of course be going into and out of the code, looking for that small piece I might have missed. But I'm like a modern operating system, I do lots of things at once. So after being unable to solve it the first few times, I thought to pose a question, but as I pose the question that never means that I'm done looking at my code and hoping I missed something. I'd much rather have this be my fault... that means I have a much higher probability of fixing it. But i sought to explore some tips given to me. Ah, but the day I could be 100% sure, that would be a good day (hell, i'd go ask for a raise for being the best coder ever!) > This stuff is never obvious before the fact - and always seems stupid > afterward, when you have found it. Your best (some would say only) > weapon is your imagination, fueled by scepticism... > > Yea, seriously! >> try and get a better understanding might be to check data before its >> stored. Again, I still don't know how it would get messed up nor can I >> reproduce the error on my own. >> >> Do any of you think that would be a good practice for trying to track >> this down? (Check the data after reading it, check the data before >> saving it) >> > > Nothing wrong with doing that to find a bug - not as a general > practice, of course - that would be too pessimistic. > > In hard to find bugs - doing anything to narrow the time and place > of the error down is fair game - the object is to get you to read > some code that you *know works* with new eyes... > > I really like that piece of wisdom, I'll add that to my list of coding mantras. Thanks! > I build in a global boolean variable that I call trace, and when its on > I do all sort of weird stuff, giving a running commentary (either by > print or in some log like file) of what the programme is doing, > like read this, wrote that, received this, done that here, etc. > A bare useful minimum is a "we get here" indicator like the routine > name, but the data helps a lot too. > > Yea, I do some of that too. I use that with conditional print statements to stderr when i'm doing my validation against my test cases. But I could definitely do more of them. The thing will be simulating the failure. In the production server, thousands of printed messages would be bad. I've done short but heavy simulations, but to no avail. For example, I'll have a couple systems infinitely loop and beat on the system. This is a much heavier load than the system will ever normally face, as its hit a lot at once and then idles for a while. The test environment constantly hits it, and I let that run for several days. Maybe a longer run is needed, but how long is reasonable before determining that its something beyond my control? > Compared to an assert, it does not stop the execution, and you > could get lucky by cross correlating such "traces" from different > threads. - or better, if you use a queue or a pipe for the "log", > you might see the timing relationships directly. > Ah, store the logs in a rotating queue of fixed size? That would work pretty well to maintain control on a large run, thanks! > But this in itself is fraught with danger, as you can hit file size > limits, or slow the whole thing down to unusability. > > On the other hand it does not generate the volume that a genuine > trace does, it is easier to read, and you can limit it to the bits that > you are currently suspicious of. > > Programming is such fun... > Yea, I'm one of those guys who really gets a sense of satisfaction out of coding. Thanks for the tips. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From eurleif at ecritters.biz Sun Jan 28 23:41:19 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 28 Jan 2007 23:41:19 -0500 Subject: Convert from unicode chars to HTML entities In-Reply-To: References: Message-ID: <45bd7a82$0$17928$4d3efbfe@news.sover.net> Steven D'Aprano wrote: > I have a string containing Latin-1 characters: > > s = u"? and many more..." > > I want to convert it to HTML entities: > > result => > "© and many more..." > > Decimal/hex escapes would be acceptable: > "© and many more..." > "© and many more..." >>> s = u"? and many more..." >>> s.encode('ascii', 'xmlcharrefreplace') '© and many more...' From tjgolden at gmail.com Tue Jan 16 10:51:16 2007 From: tjgolden at gmail.com (Tim Golden) Date: 16 Jan 2007 07:51:16 -0800 Subject: Search Queue In-Reply-To: <1168960945.787822.286690@s34g2000cwa.googlegroups.com> References: <1168960945.787822.286690@s34g2000cwa.googlegroups.com> Message-ID: <1168962673.664083.146220@38g2000cwa.googlegroups.com> abcd wrote: > I have a class such as... [... ] > And I am storing them in a Queue.Queue... > > import Queue > q = Queue.Queue() > q.put(Foo('blah')) > q.put(Foo('hello world')) > q.put(Foo('test')) > > how can I search "q" for an instance of Foo which has 'id' equal to say > 2? Typically a queue only lets you put and get, not really search. It's possible you're seeing the Queue structure as some sort of list / array, rather than its intended purpose as a thread-safe channel. If I'm wrong, ignore the rest of this post. If, however, you're just after a container for various instances of Foo then use a list or a dict, depending on what you're after. eg, class Foo: def __init__ (self, id): self.id = id list_of_foos = [Foo('blah'), Foo('hello'), Foo('test')] dict_of_foos = dict ((f.id, f) for f in list_of_foos) print dict_of_foos['blah'] TJG From chris at kateandchris.net Tue Jan 2 11:43:01 2007 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 2 Jan 2007 11:43:01 -0500 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167526509.471697.320750@v33g2000cwv.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> Message-ID: <20070102164301.GA9471@kateandchris.net> On Sat, Dec 30, 2006 at 04:55:09PM -0800, Ben Sizer wrote: > Martin v. L?wis wrote: > > > Ben Sizer schrieb: > > > I've installed several different versions of Python across several > > > different versions of MS Windows, and not a single time was the Python > > > directory or the Scripts subdirectory added to the PATH environment > > > variable. Every time, I've had to go through and add this by hand, to > > > have something resembling a usable Python installation. No such > > > problems on Linux, whether it be Mandrake/Mandriva, Fedora Core, or > > > Kubuntu. So why is the Windows install half-crippled by default? > > > > For several reasons: > > 1. Python can be used just fine without being on PATH. Python > > scripts run fine both when double-clicked and when invoked in > > the command line, and if you want to use an interactive > > interpreter, you can find it readily on the Start menu. > > Yet many scripts and applications require parameters, or to be executed > from a certain directory. For example, setup.py. Or the various > turbogears scripts. Or easy_install. Martin's point was that if you need to pass arguments, you can call the script from the command line like so: setup.py install The python part of the 'python setup.py install' idiom needs to be omitted on Windows, but that does not mean that the solution is to automatically add it to PATH. > > 2. Many windows users (including myself) dislike setup routines that > > manipulate PATH. > > My opinion is that this is not as big a problem as some may feel that > it is. Unlike Unix systems, the PATH variable is rarely used. Most > applications are launched via the Start Menu, which uses absolute > paths, or via file associations, also done via absolute paths. The > chance of a naming collision only really arises when you start using > the command line, which most people don't do. > > However, among those who will use the command line, are some people new > to Python, who will come across instructions like this: > > > > > Pretty much none of the instructions in that part of the docs will work > without you altering your path beforehand. Python's cross-platform > nature means people rightly expect the same instructions to work on > Linux and Windows from a standard installation. Right now, they don't. The documentation is misleading... time for a but report: http://sourceforge.net/tracker/index.php?func=detail&aid=1626300&group_id=5470&atid=105470 > > if Python is to be found in PATH, it > > should rather be installed to a directory that is known to live > > on PATH (or where CreateProcess searches, anyway, such > > as system32). So if the installer had such a feature, it should > > be optional, and it should default to "off". > > It's a lot more anti-social to install to system32 than to modify the > PATH variable. How easy is it to temporarily undo an installation to a > system directory like that? What if you still want Python in your path > but with less precedence than some other user directory? I agree an optional add to PATH, should just add to the path rather than install python.exe into a location on the path. > > > 3. Most importantly: it is difficult to implement, and nobody has > > contributed code to make it work. > > There appears to be a freely-available binary at this address that may > suffice: > http://legroom.net/modules.php?op=modload&name=Open_Source&file=index&page=software&app=modpath Unfortunately the Python installer is not an InnoSetup installer. If you converted this code to Python you might get farther since the MSI could call an add2path script with the newly installed Python executable. I am sure submitting a patch for the installer option would also help your cause. -Chris From goodidea1950 at hotmail.spam.com Thu Jan 25 03:25:38 2007 From: goodidea1950 at hotmail.spam.com (AKA gray asphalt) Date: Thu, 25 Jan 2007 00:25:38 -0800 Subject: Do I need Python to run Blender correctly? Message-ID: I downloaded Blender but there was no link for python. Am I on the right track? From mail at microcorp.co.za Fri Jan 12 00:48:24 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Jan 2007 07:48:24 +0200 Subject: Is there a way to protect a piece of critical code? References: Message-ID: <007901c7360d$469393e0$03000080@hendrik> "robert" wrote: > pushing data objects through an inter-thread queue is a major source for trouble - as this thread shows again. > Everybody builds up a new protocol and worries about Empty/Full, Exception-handling/passing, None-Elements, ... > I've noticed that those troubles disappear when a functional queue is used - which is very easy with a functional language like Python. > For example with http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 > > > One would just use a cq=CallQueue() > > On the producer side one would just write the functional code one wants to execute in a target thread: > > cq.call( what_i_want_do_func ) > > > The consumer/receiver thread would just do (periodically) a non-blocking > > cq.receive() > > > => Without any object fumbling, protocol worries and very fast. > > And note: This way - working with functional jobs - one can also "protect a piece of critical code" most naturally and specifically for certain threads without spreading locks throughout the code. > Even things which are commonly claimed "forbidden" (even when using lots of locks) can be magically done in perfect order and effectively this way. Think of worker threads doing things in the GUI or in master / database owner threads etc. > > Similarly discrete background thread jobs can be used in a functional style this way: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491280 > ( an alternative for the laborious OO-centric threading.Thread which mostly is a lazy copy from Java ) > or for higher job frequencies by using "default consumer threads" as also shown in the 1st example of > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281 > Thank you - had a (very) quick look and I will return to it later - It is not immediately obvious to my assembler programmer's mentality - looks like in the one case the thread starts up, does its job and then dies, and in the other its a sort of "remote" daemon like engine, that you can "tell what to do", from "here"... Both concepts seem nice and I will try to wrap my head around them properly. So far I have only used dicts to pass functions around in a relatively unimaginative static jump table like way... Thanks. - Hendrik From garyjefferson123 at yahoo.com Sat Jan 20 22:16:40 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 20 Jan 2007 19:16:40 -0800 Subject: selective logger disable/enable In-Reply-To: <1169204564.348768.186900@38g2000cwa.googlegroups.com> References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> Message-ID: <1169349399.938121.238430@38g2000cwa.googlegroups.com> Vinay Sajip wrote: > > The documentation for Logger - see > > http://docs.python.org/lib/node406.html > > - shows that there are addFilter() and removeFilter() methods on the > Logger class which you can use to add or remove filters from individual > Logger instances. From the above page (entitled "14.5.1 Logger > Objects"): > > addFilter(filt) > Adds the specified filter filt to this logger. > > removeFilter(filt) > Removes the specified filter filt from this logger. > > The parent section of Section 14.5.1, which is Section 14.5, was the > first search result when I just searched Google for "python logging". Thanks for the reply Vinay. I had been reading those docs prior to posting, but addFilter/removeFilter only work on individual logger instances and handlers. I want to globally enable/disable multiple logger instances, based on their namespaces (see the example I provided). I cannot find a way to do this. I can certainly call addFilter on every instance of every logger throughout the source code, but this is more than inconvenient -- it breaks when new modules are added with their own loggers in their own namespaces (until fixed by manually adding addFilter() to those instances). e.g., suppose you have a source tree with a several components that do network access, and several components that do other things like saving state to disk, accessing the filesystem, etc. And suppose you find a bug that you think is in the networking code. It would be nice to be able to GLOBALLY enable just the loggers that belong in the networking namespace, and disable all others (similar to how Filters are supposed to work for individual loggers). And then to be able to do this with any component, by providing, for example, a command line switch or environment variable. Otherwise, the poor programmer is forced to go and edit every module in the source tree to selectively turn on/off their respecitve loggers. Or am I missing something really obvious about how this is done with the logging module? thanks, Gary From hg at nospam.org Mon Jan 15 08:18:20 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 14:18:20 +0100 Subject: check if there is data in stdin without blocking References: <4PMqh.47441$X97.9536@newsfe18.lga> <9uNqh.48239$X97.14123@newsfe18.lga> Message-ID: Gabriel Genellina wrote: > At Monday 15/1/2007 05:55, hg wrote: > >>Well I'm testing under Linux but need support under Windows ... is there >>any way to poll stdin somehow under both plateform ? > > I think you may want this portable getch function: > > > > -- > Gabriel Genellina > Softlab SRL > > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas will take a look, thanks. hg From goodepic at gmail.com Fri Jan 5 16:29:07 2007 From: goodepic at gmail.com (goodepic) Date: 5 Jan 2007 13:29:07 -0800 Subject: PyGreSQL Install In-Reply-To: References: <1168030553.913612.309020@q40g2000cwq.googlegroups.com> Message-ID: <1168032547.281390.272960@51g2000cwl.googlegroups.com> Awesome! I forgot that when I did switched to root I lost my PATH, where I'd put usr/local/bin ahead of /usr/bin, so "python" went to 2.5 instead of 2.3. Using python2.5 worked perfectly. Thanks!! From jamesthiele.usenet at gmail.com Thu Jan 11 11:41:52 2007 From: jamesthiele.usenet at gmail.com (James Thiele) Date: 11 Jan 2007 08:41:52 -0800 Subject: Progress count in terminal (Mac OS X) In-Reply-To: References: <9079A3B8-47A8-495A-BFAE-09A603CFB819@mac.com> Message-ID: <1168533712.512068.259310@o58g2000hsb.googlegroups.com> if you invoke python with the -u option the output of print is unbuffered. On Jan 11, 7:04 am, Tommy Grav wrote: > This certainly does work when running the interpreter interactively, > but when inserted into a script it seems to buffer the print statement > and not write it out to the terminal. How can I force the print > statement > to not buffer the output? > > Cheers > Tommy > > On Jan 11, 2007, at 9:22 AM, Fredrik Lundh wrote: > > > Tommy Grav : > > >> I have a program that does a lot of iterations and would like > >> to follow its progress by having it print out the current iteration > >> number as it progresses. How do I do this so that it appears > >> like a counter that increases in the same place in the terminal > >> window? I am using python2.5 on a Mac OSX and its terminal > >> tcsh window. > > > print a carriage return before, and no line feed after, each line: > > > for i in range(100): > > print "\r" + "count", i, > > print # done > > > > > > -- > >http://mail.python.org/mailman/listinfo/python-list From jmfbahciv at aol.com Thu Jan 11 08:53:35 2007 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 11 Jan 07 13:53:35 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> <0001HW.C1CA63B1059BC980F0203648@news.verizon.net> Message-ID: In article , kkkisok at operamail.com wrote: > > >On 10-Jan-2007, krw wrote: > >> ...and "HexaPussy" just wouldn't be right. > > >SexagesimalPussy (base 60) has kind of a nice ring to it. That would cause kiddies to look up the word. But 360 would have the correct ring. /BAH From stefaan.himpe at gmail.com Sat Jan 13 09:56:47 2007 From: stefaan.himpe at gmail.com (stefaan) Date: 13 Jan 2007 06:56:47 -0800 Subject: difflib.HtmlDiff Message-ID: <1168700207.846457.194710@38g2000cwa.googlegroups.com> Hello List, I am using difflib.HtmlDiff and it provides great functionality. Unfortunately it is too slow for my purpose. Is anyone aware of an alternative ? - a C-implementation lying around somewhere ? - perhaps an external tool into which I can pipe my data ? Intra-line differences are important for my task at hand. Does it make sense performance-wise to use e.g. GNU diff to generate a line-by-line diff, then use SequenceMatcher to find intraline changes? Google is my friend, but so far it didn't turn up much practical results :s Thanks for any insights you may share. Stefaan. From grahamd at dscpl.com.au Sat Jan 13 21:10:37 2007 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 13 Jan 2007 18:10:37 -0800 Subject: mod_python and Content-Type References: <8764bbb6jt.fsf@rudin.co.uk> Message-ID: <1168740637.544535.113490@38g2000cwa.googlegroups.com> Paul Rudin wrote: > I'm have a little experiment with mod_python. I'm trying to figure out > how to get hold of the original Content-Type header. > > In my config file I have: > > > AddHandler mod_python .py > PythonHandler atomserv > PythonDebug On > PythonAutoReload On > > > The file atomserv.py in that directory has a function called handler > that gets called as I expect, but on entry to that function > req.content_type is "text/x-python" whereas my test client sent a > different Content-Type header. > > So, how can I either persuade the apache/mod_python machinery to > preserve the original content_type, or else how can I get hold of it? All headers which come from the client are available through the 'headers_in' attribute of the request object. Eg. def handler(req): ct = req.headers_in.get('Content-Type') ... The 'content_type' attribute is set by Apache based on its determination of what the content type of the response will be based on looking at the extension type used on the matched resource specified by the URL. Graham From nagle at animats.com Wed Jan 24 14:59:51 2007 From: nagle at animats.com (John Nagle) Date: Wed, 24 Jan 2007 19:59:51 GMT Subject: Python does not play well with others In-Reply-To: References: Message-ID: Chris Mellon wrote: > On 1/24/07, John Nagle wrote: > >> Harry George wrote: >> > John Nagle writes: > Just to be clear: The problem here is "my personal itch is not being > scratched by other people for me", not "Python doesn't play well with > others". You are not any more important than anyone else and assuming > that anyone cares about your problems is a major fallacy. You have a > specific library that doesn't meet your needs, and that you are not > interested in maintaining yourself, so you are attempting to leverage > some sort of community guilt trip to get other people to do it for > you. That's dishonest and off-putting. No, the problem is that these things are broken. Python is the only major open source project I've encountered where there's so much hostility to bug reports. For a while, I tried submitting long, detailed bug reports showing where in the C code a problem lies, and pointing out ways to fix it. But I don't want to take over maintenance on the SSL package; it's too delicate. John Nagle From pierre at saiph.com Wed Jan 31 05:02:04 2007 From: pierre at saiph.com (Imbaud Pierre) Date: Wed, 31 Jan 2007 11:02:04 +0100 Subject: data design In-Reply-To: References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> <45bfbcc3$0$30950$426a74cc@news.free.fr> <1170201274.580256.182740@v45g2000cwv.googlegroups.com> Message-ID: <45c0691c$0$6724$426a74cc@news.free.fr> James Stroud a ?crit : > Szabolcs Nagy wrote: > >>> Hurray for yaml! A perfect fit for my need! And a swell tool! >>> Thanks a lot! >> >> >> >> i warn you against yaml I feel both thanful, and sorry, for your warning. And not convinced yet, but Ill be cautious. >> it looks nice, but the underlying format is imho too complex (just >> look at their spec.) complex indeed, but real powerful. Is it not true that: if I used yaml, sticking to what .ini allows, yaml files would be simple? >> >> you said you don't want python source because that's too complex for >> the users. >> i must say that yaml is not easier to use than python data structures. Easier to read and write, U must agree. Surround strings with quotes is a python requirement, to distinguish them from identifiers. This only makes data input for python somewhat clumsy. Granted, its a new format to learn. But sharing this format with a much wider community than python, aint this worth the effort? (well, if yaml succeeds and spreads...) >> >> if you want userfriedly config files then ConfigParser is the way to go. Granted. for END users. I rather target administrators, programmers, integrators: make customization an easy process, and allowing this customization to go much farther than changing simple values, aint this the REAL challenge for new applications? >> >> if you want somthing really simple and fast then i'd recommend s- >> expressions of lisp lisp is more powerful than python. its syntax deterred many programmers, who adopted python, it will deter my targeted "customizers". And the process to translate to python structure, I have no idea. involves a python or lisp translater... >> >> also here is an identation based xml-like tree/hierarchical data >> structure syntax: >> http://www.scottsweeney.com/projects/slip/ Pretty nice, too! James, have a look at this! >> > > I've been spending the last 2 days weighing ConfigParser and yaml, with > much thought and re-organizing of each file type. The underlying > difference is that, conceptually, ini files are an absurdly limited > subset of yaml in that ini files are basically limited to a map of a map. U have a point here. > > For instance, I have a copy_files section of a configuration. In order > to know what goes with what you have to resort to gymnastics with the > option names > > [copy_files] > files_dir1 = this.file that.file > path_dir1 = /some/path > > files_dir2 = the_other.file yet_another.file > path_dir2 = /some/other/path > > In yaml, it might look thus. > > copy_files : > - files : [this.file, that.file] > path : /some/path > - files : [the_other.file, yet_another.file] > path : /some/other/path > > Both are readable (though I like equals signs in appearance over > colons), but yaml doesn't require a lot of string processing to group > the files with the paths. I don't even want to think the coding > gymnastics required to split all of the option names and then group > those with common suffixes. > > Now if the config file were for copying only, ini would be okay, because > one could just have sections that group paths and dirs: > > [dir1] > files = this.file, that.file > path = /some/path > > [dir2] > ... > > But if you need different kinds of sections, you have outgrown ini. > > In essence, ini is limited to a single dictionary of dictionaries while > yama can express pretty much arbitrary complexity. James, this single formula makes things real clear. As we both work on the subject, maybe we could continue to exchange ideas, and information? Have a look at the link Szabolcs Nagy gives: http://www.scottsweeney.com/projects/slip/ Ill further dig yaml, with 2 questions: - how do I translate to python? - how do I express and/or enforce rules the data should follow? (avoid the classic: configuration data error raise some obscure exception). Big thanks to Szabolcs Nagy (hungarian, my friend? I love this country), although I seem to disagree, your statements are pretty clear and helpful, and... maybe U are right, and I am a fool... Pierre From gagsl-py at yahoo.com.ar Mon Jan 29 23:54:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 01:54:43 -0300 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: En Mon, 29 Jan 2007 01:58:39 -0300, NoName escribi?: > Perl: > @char=("A".."Z","a".."z",0..9); > do{print join("", at char[map{rand @char}(1..8)])}while(<>); > > !!generate passwords untill U press ctrl-z > > > > Python (from CookBook): > > from random import choice > import string > print ''.join([choice(string.letters+string.digits) for i in > range(1,8)]) > > !!generate password once :( > > who can write this smaller or without 'import'? > Isn't it small enough? What's the point on being shorter? I think you could avoid importing string (building the set of characters like the Perl code) but anyway you will end importing random, or os.urandom Do you want more than one password? Wrap the print inside a while True: statement. -- Gabriel Genellina From nemesis at nowhere.invalid Fri Jan 12 15:01:36 2007 From: nemesis at nowhere.invalid (Nemesis) Date: Fri, 12 Jan 2007 20:01:36 GMT Subject: [ANN] XPN 0.7.0 Message-ID: <20070112200136.6022.19611.XPN@ip-208-67-219-41.n.opendns.com> XPN (X Python Newsreader) is a multi-platform newsreader with Unicode support. It is written with Python+GTK. It has features like scoring/actions, X-Face and Face decoding, muting of quoted text, newsrc import/export, find article and search in the body, spoiler char/rot13, random taglines and configurable attribution lines. You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn Changes in this release: * v0.7.0: added basic multiserver support. This change has required some modifications to the groups db format, in order to keep your subscriptions you need to export to a newsrc file from XPN-0.6.5 and reimport it in XPN-0.7.0. * v0.7.0: now is possible to use Function keys for customized keybindings * v0.7.0: modified the command used to test the connection in order to prevent hamster hang-ups. * v0.7.0: fixed a bug that caused XPN to crash trying to export newsrc file with empty groups subscribed. * v0.7.0: fixed a bug in "Apply Scoring and Actions Rules" feature that caused XPN crashes trying to apply !kill rule. * v0.7.0: some minor fixes. XPN is translated in Italian French and German, if you'd like to translate it in your language and you are familiar with gettext and po-files editing please contact me (xpn at altervista.org). -- I may not have gone where I intended to go, but I think I have ended up where I needed to be. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From dotancohen at gmail.com Wed Jan 3 15:47:26 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 3 Jan 2007 22:47:26 +0200 Subject: Unsubscribing from the list In-Reply-To: References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> Message-ID: <880dece00701031247l3d2354a3le318340653969de8@mail.gmail.com> On 03/01/07, Robert Kern wrote: > He misunderstood you (as I nearly did, too). The way you phrased "decided that > there was no futher interest on the page for me" is somewhat ambiguous: it can > seem like it refers to the second time, not the first. > Ah. Sorry. I'm getting better at confusing people :) if ($you=="got_offended") { $dotan="sorry"; } Dotan Cohen http://what-is-what.com/what_is/website.html http://lyricslist.com/ From gagsl-py at yahoo.com.ar Fri Jan 12 00:16:35 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Jan 2007 02:16:35 -0300 Subject: Explanation about for loop In-Reply-To: <1168577299.485773.8160@q2g2000cwa.googlegroups.com> References: <1168577299.485773.8160@q2g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070112021537.0596f950@yahoo.com.ar> At Friday 12/1/2007 01:48, raghu wrote: >can any one help me explaining for loop and its execution and its >syntax with a simple example. This section of Dive Into Python explain for loops: http://diveintopython.org/file_handling/for_loops.html (And you could read the whole book too) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From webraviteja at gmail.com Mon Jan 8 19:15:39 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Jan 2007 16:15:39 -0800 Subject: Network failure when using urllib2 In-Reply-To: <1168292352.349983.139260@i15g2000cwa.googlegroups.com> References: <1168292352.349983.139260@i15g2000cwa.googlegroups.com> Message-ID: <1168301738.984509.3030@38g2000cwa.googlegroups.com> jdvolz at gmail.com wrote: > I have a script that uses urllib2 to repeatedly lookup web pages (in a > spider sort of way). It appears to function normally, but if it runs > too long I start to get 404 responses. If I try to use the internet > through any other programs (Outlook, FireFox, etc.) it will also fail. > If I stop the script, the internet returns. > > Has anyone observed this behavior before? I am relatively new to > Python and would appreciate any suggestions. > > Shuad I am assuming that you are fetching the full page every little while. You are not supposed to do that. The admin of the web site you are constantly hitting probably configured his server to block you temporarily when that happens. But don't feel bad :-). This is a common Beginners mistake. Read here on the proper way to do this. http://diveintopython.org/http_web_services/review.html especially 11.3.3. Last-Modified/If-Modified-Since in the next page Ravi Teja. From gagsl-py at yahoo.com.ar Sat Jan 13 23:07:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Jan 2007 01:07:00 -0300 Subject: Decorators inside of class and decorator parameters References: <1168728983.541526.202320@l53g2000cwa.googlegroups.com> Message-ID: "MR" escribi? en el mensaje news:1168728983.541526.202320 at l53g2000cwa.googlegroups.com... > I have a question about decorators, and I think an illustration would > be helpful. Consider the following simple class: > > #begin code > class Foo: > def fooDecorator(f): > print "fooDecorator" > > def _f(self, *args, **kw): > return f(self, *args, **kw) > > return _f > > @fooDecorator > def fooMethod(self): > print "fooMethod" > > f = Foo() > f.fooMethod() > #end of code > > This code runs, and actually serves my purpose. However, I'm a little > confused about three things and wanted to try and work through them > while I had the time to do so. I believe all of my confusion is related > to the parameters related to the fooDecorator: [I reordered your questions to make the answer a bit more clear] > -why does this code even work, because the first argument to > fooDecorator isn't self fooDecorator is called when the class is *defined*, not when it's instantiated. `self` has no meaning inside it, neither the class to which it belongs (Foo does not even exist yet). At this time, fooDecorator is just a simple function, being collected inside a namespace in order to construct the Foo class at the end. So, you get *exactly* the same effect if you move fooDecorator outside the class. > -how I would pass arguments into the fooDecorator if I wanted to (my > various attempts have failed) Once you move fooDecorator outside the class, and forget about `self` and such irrelevant stuff, it's just a decorator with arguments. If you want to use something like this: @fooDecorator(3) def fooMethod(self): that is translated to: fooMethod = fooDecorator(3)(fooMethod) That is, fooDecorator will be called with one argument, and the result must be a normal decorator - a function accepting a function an an argument and returning another function. def outerDecorator(param): def fooDecorator(f): print "fooDecorator" def _f(self, *args, **kw): print "decorated self=%s args=%s kw=%s param=%s" % (self, args, kw, param) kw['newparam']=param return f(self, *args, **kw) return _f return fooDecorator This is the most direct way of doing this without any help from other modules - see this article by M. Simoniato http://www.phyast.pitt.edu/~micheles/python/documentation.html for a better way using its decorator factory. > -what the difference is between decorating with @fooDecorator versus > @fooDecorator() Easy: the second way doesn't work :) (I hope reading the previous item you can answer this yourself) > I'm searched the net and read the PEPs that seemed relevant, but I > didn't see much about decorators inside of a class like this. Can > anyone comment on any of these three things? As said in the beginning, there is no use for decorators as methods (perhaps someone can find a use case?) If you move the example above inside the class, you get exactly the same results. HTH, -- Gabriel Genellina From bg_ie at yahoo.com Thu Jan 4 11:20:18 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 4 Jan 2007 08:20:18 -0800 Subject: Python Wrapper for C# Com Object In-Reply-To: References: <1167297178.937748.91790@79g2000cws.googlegroups.com> <1167313715.296081.133170@n51g2000cwc.googlegroups.com> Message-ID: <1167927618.573305.324360@v33g2000cwv.googlegroups.com> Thomas Heller skrev: > bg_ie at yahoo.com schrieb: > > bg_ie at yahoo.com skrev: > > > >> Hi, > >> > >> I wish to write a Python wrapper for my C# COM object but am unsure > >> where to start. I have a dll and a tlb file, and I can use this object > >> in C via the following code - > >> > >> // ConsolApp.cpp : Defines the entry point for the console application. > >> // > >> #include "stdafx.h" > >> #include "windows.h" > >> #include "stdio.h" > >> #import "C:\Documents and Settings\X\Mina dokument\Visual Studio > >> 2005\Projects\X_COMObject\X_COMObject\bin\Debug\X_COMObject.tlb" > >> using namespace X_COMObject; > >> > >> int _tmain(int argc, _TCHAR* argv[]) > >> { > >> CoInitialize(NULL); > >> > >> X_COMObject::XCOM_InterfacePtr p(__uuidof(X_COMObject::XCOM_Class)); > >> XCOM_Interface *X_com_ptr ; > >> X_com_ptr = p ; > >> X_com_ptr->SetID(10); > >> int x = X_com_ptr->GetID(); > >> printf("%d",x); > >> getchar(); > >> > >> return 0; > >> } > >> > >> Can anyone offer me some tips as to how to do this in Python? > >> > >> Thanks very much for your help, > >> > >> Barry. > > > > This is what I've done so far, but I know I'm not doing this correctly. > > Can anyone help me out? > > > > #import pythoncom > > #pythoncom.CoInitialize() > > The above is unneeded if you use comtypes as below (and is unneeded > when using pythoncom, as well). > > > from comtypes.client import GetModule, CreateObject > > > > module = GetModule("C:\\Documents and Settings\\X\\Mina > > dokument\\Visual Studio > > 2005\\Projects\\X_COMObject\\X_COMObject\\bin\\Debug\\X_COMObject.tlb") > > > You don't intantiate the interface, you have to instantiate the COM object. > Something like > > CreateObject("XCOM_Class") > > but of course you have to use the correct argument in the call - the progid > of the COM object. > Alternatively you can use the CoClass from the typelibrary, look into the > generated module in the comtypes\gen directory for a class derived from > comtypes.CoClass. > > InternetExplorer, for example, can be started in these ways: > > # using the progid: > ie = CreateObject("InternetExplorer.Application") > > # using the clsid: > ie = CreateObject("{0002DF01-0000-0000-C000-000000000046}") > > > # using the coclass from the generated module: > mod = GetModule("shdocvw.dll") > ie = CreateObject(mod.InternetExplorer) > > Thomas Thanks very much for your help. I tried running the following code - import win32com.client scanObj = win32com.client.Dispatch("X_COMObject") but im getting the following error - Traceback (most recent call last): File "C:\Python22\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Python25\test.py", line 20, in ? scanObj = win32com.client.Dispatch("Scania_COMObject") File "C:\Python22\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python22\Lib\site-packages\win32com\client\dynamic.py", line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221005, 'Invalid Class String', None, None) I ran my C++ code again and it works fine. I also checked COM Browser and my X_COMObject is present and I'm spelling it right. Any ideas what the problem migth be? Thanks again, Barry. From gagsl-py at yahoo.com.ar Thu Jan 4 22:30:08 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 00:30:08 -0300 Subject: subclassing a module: misleading(?) error message In-Reply-To: <459d687a$1@nntp.zianet.com> References: <459d687a$1@nntp.zianet.com> Message-ID: <7.0.1.0.0.20070105002648.05b86e88@yahoo.com.ar> At Thursday 4/1/2007 17:49, Erik Johnson wrote: >Python 2.3.4 (#1, Feb 7 2005, 15:50:45) >Traceback (most recent call last): > File "", line 1, in ? > File "Sub.py", line 4, in ? > class Sub(Super): >TypeError: function takes at most 2 arguments (3 given) > >Why does python complain about a function here? (it's a class definition >statement, right?) >Is there really a function being called here? >If so: > What function was called? > What two arguments is it expecting? > What three were given? The same thing on Python 2.4.2 (at least) prints a much more meaningful error: Traceback (most recent call last): File "", line 1, in ? TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From Michael.Coll-Barth at VerizonWireless.com Fri Jan 19 16:08:57 2007 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Fri, 19 Jan 2007 16:08:57 -0500 Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: Message-ID: <20070119214644.7709A1E4004@bag.python.org> ::CLAP CLAP:: thank you! I have been in the newsgroups for over 12 years and I never cared about the top/bottom post silliness. All I care about is that the message is clearly written. Everything else is doggerel. > -----Original Message----- > From: Carroll, Barry > > Personally, I don't think top-posting is the most annoying newsgroup > habit. I think it's making a big fuss about minor inconveniences. ::CLAP CLAP:: thank you! I have been in the newsgroups for over 12 years and I never cared about the top/bottom post silliness. All I care about is that the message is clearly written. Everything else is doggerel. The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to 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 me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From parallelpython at gmail.com Thu Jan 11 19:29:40 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 11 Jan 2007 16:29:40 -0800 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <7x8xga215f.fsf@ruckus.brouhaha.com> <1168516936.890690.235300@p59g2000hsd.googlegroups.com> Message-ID: <1168561780.317156.268880@42g2000cwt.googlegroups.com> > > Thus there are different levels of parallelization: > > 1 file/database based; multiple batch jobs > 2 Message Passing, IPC, RPC, ... > 3 Object Sharing > 4 Sharing of global data space (Threads) > 5 Local parallelism / Vector computing, MMX, 3DNow,... > > There are good reasons for all of these levels. > Yet "parallel python" to me fakes to be on level 3 or 4 (or even 5 :-) ), while its just a level 2 > system, where "passing", "remote", "inter-process" ... are the right vocables. In one of the previous posts I've mentioned that ppsmp is based on processes + IPC, which makes it a system with level 2 parallelization, the same level where MPI is. Also it's obvious from the fact that it's written completely in python, as python objects cannot be shared due to GIL (POSH can do sharing because it's an extension written in C). From sargis at ieee.org Fri Jan 19 15:42:29 2007 From: sargis at ieee.org (sargis at ieee.org) Date: 19 Jan 2007 12:42:29 -0800 Subject: ANN: Python Molecular Viewer - 1.4.4 Message-ID: <1169239349.282715.13340@51g2000cwl.googlegroups.com> We are pleased to announce the release of version 1.4.4 of our software tools including: Python Molecular Viewer (PMV), AutoDockTools (ADT) and VISION a visual-programming environment. Installers for binary distributions are available for LINUX, Mac OS X and Windows at: http://mgltools.scripps.edu/downloads The binary distributions contain: - a precompiled Python interpreter version 2.4; (except for windows which requires running the Python installer first) - PMV, ADT, VISION and all dependent Python packages. INSTALLERS: - PackageMaker-based installer - Mac OS X (.dmg extension); - InstallJammer-based installers - Linux and Windows. Note: the windows installer has to be run after Python 2.4 has been installed. LICENSE AGREEMENTS: -------------------------------------- The license agreements are provided on the download site at https://mgltools.scripps.edu/downloads/license-agreements and can also be found in the LICENSE file of the distribution. NEW FEATURES: -------------------------- ADT: autoanalyzeCommands -added new ADanalyze_showBindingSite command as Analyze->Dockings->Visualize Docking in context This display uses (1)spheres centered on atoms in closer-than-vdw-radii contact (2)hydrogen bonds and (3)sections of secondary structure (for sequences of 5 or more adjacent residues in the receptor with atoms close to the ligand) to show the bound ligand in the context of surrounding receptor. autoflexCommands -add explicit warning to caution users that the molecule used to calculate autogrids for AD4 should contain only the non-moving or 'rigid' residues. ConfPlayer -added support for updating the 'BindingSite' display -added support for showing information about singleton clusters -added PopulationPlayer class DlgParser: -added support for parsing the amount of time involved in the calculation -added support for parsing populations which are written when outlev is set to 4 in the AD4 dpf. DockingParameters: -added support for reorient keyword (AD4) -added dpf_written_filename attribute GridParameters: -added gpf_written_filename attribute Added Web Services commands accessible from Run->Web Services. Registered users can now run AutoGrid and AutoDock installed on NBCR cluster. atomTypeTools -fixed problem which sometimes occurred in merging nphs. Previously hydrogens not bonded to anything raised an exception. Now the code checks for the existence of bonds before referencing hydrogens' bonds... NB: now non-bonded hydrogens will not raise an error. Utilities24: prepare_receptor4 -corrected initialization of 'cleanup' on line 70 to match documentation string -improved support for preserving the input atom charge on a specified type to AD4ReceptorPreparation -fixed bug where 'charges_to_add' was not initialized in some cases... summarize_docking_directory.py -new script which reads in all the docking logs in a directory into a single Docking. It clusters the results and outputs a comma-separated list showing number of conformations, number of tors, number of atoms, number of clusters, rmstol used for clustering, energy, etc. By default uses c2-specific getRMSD_custom method (line 176) which should be commented out if not appropriate. summarize_time.py -new script which reads in all the docking logs in a directory and outputs the total amount of time taken. PMV: - New dashboard widget showing a tree representation of molecules and allowing to rapidly execute PMV commands on molecular fragments - New Grid3D commands for rendering 3D Grids. Supports adding and removing grids to Pmv. Grid a show in a table widget used for navigating between grids. Isocontours and orthogonal slices can be computed and displayed. - New Update command under the Help menu allows the user to update Pmv with the latest version of the tools. - New Register button in the About dialog allows a user to register anytime - New BugReport Command to helpCommands. This command is for submitting bugs to Bugzila DataBase from Pmv. - New command for reading and playing GROMACS trajectory files(.trr , .xtc formats) - A new check button in the GUI of the display Sticks and balls command enable licorice representation - A new cartoon outlines rendering mode is available and can be turned on through a button on the button bar. - New 3D labels allow for more fonts, arbitrary sizes, and optional billboarding - Setting the sphere quality to 0 in display CPK or Sticks And Balls no adapts the sphere quality based on the number of displayed atoms. Vision: - New node library for MatPlotLib - Added 2d texture to geometries - Network is now self executable when a user panel is defined - Visual editing for network user panels - "setmatplotlibparams" node in matpltlibNodes for setting rendering options (such as color, grid, size etc) for axes, figures etc. - Added rendering options for Histogram, Plot, Scatter, FigImage nodes. DejaVu: - Graph Tool for adjusting non photo rendering parameters. - Sharp color boundaries for lines, cylinders and surfaces - Invert normal per geometry (and it is exportable) - 3d lighting is now globally switchable - Movables text stickers and 2d images - Introduced specialized GUI per geometry And many bug fixes across all packages. SUPPORT: --------------- The following mailing lists are available: -AutoDock: a community of AutoDock, AutoGrid and AutoDockTools (ADT) users with lots of experience to share http://mgldev.scripps.edu/mailman/listinfo/autodock -PMV for questions regarding the use of PMV; http://mgldev.scripps.edu/mailman/listinfo/pmv -Vision for questions regarding the use of VISION; http://mgldev.scripps.edu/mailman/listinfo/vision -MGLTools support for questions regarding installing the MGLTools. http://mgldev.scripps.edu/mailman/listinfo/mglsupport Please visit our Frequently Asked Questions page if you have any problems installing or running our tools: http://mgltools.scripps.edu/documentation/faq For other inquiries, send an email to mgltools (mgltools at scripps.edu) More information can be found on our web site at http://mgltools.scripps.edu Thank you for using our tools. The MGLTools development team From jura.grozni at gmail.com Sun Jan 28 18:44:33 2007 From: jura.grozni at gmail.com (azrael) Date: 28 Jan 2007 15:44:33 -0800 Subject: Data structure and algorithms In-Reply-To: References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> <1170025297.838143.191740@j27g2000cwj.googlegroups.com> Message-ID: <1170027873.650783.172500@l53g2000cwa.googlegroups.com> i'd like to get more control like in c with pointers. I want to loose the data after disabling: >>> list=[] >>> list.append(Node(1)) >>> list.append(Node(2)) >>> list[0].next=list[1] 1, 2 >>> list.append(Node(3)) >>> list[1].next=list[2] 1,2,3 >>> list[0].next=list[2] 1,3 (but 2 still exists as list[2]) as much simmilar as this: #include #include typedef int element; struct Lis { int values[10000]; int cursor; }; typedef struct Lis list; int FirstL(list *Li){ return(0); } int EndL(list *Li){ return((*Li).cursor); } element NextL(element p, list *Li){ if ((p>=(*Li).cursor) || (p<0)) { printf("Element ne postoji u listi ! \n"); exit(0); } else return(p+1); } element PreviousL(element p, list *Li){ if ((p>(*Li).cursor) || (p<=0)) { printf("Element ne postoji u listi ! \n"); exit(0); } else return(p-1); } element LocateL(int x, list *Li){ int i; i=0; while ((i!= (*Li).cursor) && ((*Li).values[i]!=x)) i++; return(i); } void InsertL(int x, element p, list *Li){ int i; if ((p<=(*Li).cursor) && (p>=0) && ((*Li).cursor<10000)) { for (i=(*Li).cursor; i>=p; i--) (*Li).values[i]=(*Li).values[i-1]; (*Li).cursor++; (*Li).values[p]=x; } else { if((*Li).cursor>=10000) printf("Lista je puna"); else printf("Element ne postoji u listi ! \n"); exit(0); } } void DeleteL(element p, list *Li){ int i; if ((p<(*Li).cursor) && (p>=0)) { for (i=p; i<(*Li).cursor; i++) (*Li).values[i]=(*Li).values[i+1]; (*Li).cursor--; } else { printf("Element ne postoji u listi ! \n"); exit(0); } } int RetrieveL(element p, list *Li){ if ((p<(*Li).cursor) && (p>=0)) return((*Li).values[p]); else { printf("Element ne postoji u listi ! \n"); exit(0); } } void DeleteAllL(list *Li){ (*Li).cursor=0; } void InitL(list *Li){ (*Li).cursor=0; } From bj_666 at gmx.net Tue Jan 30 13:18:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 30 Jan 2007 19:18:18 +0100 Subject: Help me understand this References: Message-ID: In , Jean-Paul Calderone wrote: >>An integer is a primary so 2.__add(1) should be valid. > > A float is, too. 2.__add is a float followed by an identifier. > Not legal. As pointed out elsewhere in the thread, (2). forces > it to be an integer followed by a ".". A space between the integer literal and the dot operator works too: In [1]: 2 .__add__(1) Out[1]: 3 Ciao, Marc 'BlackJack' Rintsch From gert.cuykens at gmail.com Fri Jan 26 12:25:16 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Fri, 26 Jan 2007 18:25:16 +0100 Subject: instancemethod In-Reply-To: <45ba2b72$0$3007$426a34cc@news.free.fr> References: <45b51298$0$8289$426a74cc@news.free.fr> <45ba2b72$0$3007$426a34cc@news.free.fr> Message-ID: > class Obj(object): > pass > > toto = tutu = tata = titi = Obj() > > What's an "instance name" ? > > -- > http://mail.python.org/mailman/listinfo/python-list i would say __object__.__name__[3] == toto And if your obj is a argument like something(Obj()) i would say __object__.__name__[0] == 0x2b7bd17e9910 From carroll at tjc.com Fri Jan 12 19:33:11 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 12 Jan 2007 16:33:11 -0800 Subject: MP3 decoder module? In-Reply-To: <7x4pqvste8.fsf@ruckus.brouhaha.com> References: <7x4pqvste8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Anyone know of a reasonable mp3 decoder library I can call from > Python? Some Googling didn't find anything too promising. It found > Pymedia (which plays mp3's through a sound system).... But I want to > actually decode the mp3 frames and crunch on the audio samples. As I read the Pymedia docs, you can use it to decode frames from an MP3, and operate on the decoded sound data. See http://pymedia.org/tut/dump_wav.html for a discussion. From grante at visi.com Fri Jan 5 10:40:56 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 15:40:56 -0000 Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> Message-ID: <12pssc84huen252@corp.supernews.com> On 2007-01-05, king kikapu wrote: >> > Are they embarassed by their code? > > hehehe...no, just worried about stealing their ideas... They're deluding themselves. The vast majority of ideas aren't worth stealing. If they are worth stealing, you don't need the source code to do it. You can figure out the ideas behind almost all software by running the program for 30 seconds (or just by reading a description of what it's supposed to do). Even sophisticated and intricate algorithms and protocols can be reverse-engineered with or without the source code. Having the source code often doesn't even help very much. -- Grant Edwards grante Yow! Join the PLUMBER'S at UNION!! visi.com From kjanz1899 at gmail.com Sun Jan 14 00:35:23 2007 From: kjanz1899 at gmail.com (Binky) Date: 13 Jan 2007 21:35:23 -0800 Subject: Newbie imap lib question References: <1168611888.009894.271190@51g2000cwl.googlegroups.com> Message-ID: <1168752923.113252.220730@a75g2000cwd.googlegroups.com> Section 6.3.1 of the RFC3501 explains the possible data items the server will return after a SELECT command is issues. You can find RFC3501 here http://www.isi.edu/in-notes/rfc3501.txt. Try using the RECENT method to examine the "extra" data items returned by SELECT. Here's an example >>> M.response('RECENT') ('RECENT', ['0']) If all else faile, you may want to examine the imap library code to see how it parses the SELECT response data. From bearophileHUGS at lycos.com Thu Jan 25 04:59:54 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Jan 2007 01:59:54 -0800 Subject: How can i do this in Python? In-Reply-To: References: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> Message-ID: <1169719194.084162.148380@v33g2000cwv.googlegroups.com> Gabriel Genellina: > import operator,fileinput > mapper = map(operator.itemgetter, [0,1,20,21,2,10,12,14,11,4,5,6]) > for line in fileinput.input(): > fields = line.split() > print '\t'.join(m(fields) for m in mapper) I'm just curious, what's the advantage of using itemgetter there compared to something simpler like this (untested!)? import fileinput positions = [0,1,20,21,2,10,12,14,11,4,5,6] for line in fileinput.input(): fields = line.split() print '\t'.join(fields[m] for m in positions) Bye, bearophile From robert.kern at gmail.com Tue Jan 9 15:36:47 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 14:36:47 -0600 Subject: Newbie - converting csv files to arrays in NumPy In-Reply-To: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> Message-ID: oyekomova wrote: > I would like to know how to convert a csv file with a header row into a > floating point array without the header row. Use the standard library module csv. Something like the following is a cheap and cheerful solution: import csv import numpy def float_array_from_csv(filename, skip_header=True): f = open(filename) try: reader = csv.reader(f) floats = [] if skip_header: reader.next() for row in reader: floats.append(map(float, row)) finally: f.close() return numpy.array(floats) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From muralims80 at gmail.com Tue Jan 30 04:13:25 2007 From: muralims80 at gmail.com (murali iyengar) Date: Tue, 30 Jan 2007 14:43:25 +0530 Subject: message handling in Python / wxPython Message-ID: <5fe216230701300113i4422bae8g97021e07361bfc2b@mail.gmail.com> hi, i have basic knowledge of python and wxPython... now i need to know about message handling in python/wxPython? could anybody pls help me by giving some info on how to handle (in Python), 'the user defined messages' posted from VC++, i dont know how to handle messaes in python. Thanks and Regards, Murali M.S -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Sat Jan 13 17:05:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 13 Jan 2007 22:05:53 GMT Subject: Boilerplate in rich comparison methods References: <1168674664.792869.213260@m58g2000cwm.googlegroups.com> <45a90301$0$7677$4c368faf@roadrunner.com> Message-ID: <5Jcqh.1188$G23.509@newsreading01.news.tds.net> On 2007-01-13, Steven D'Aprano wrote: > On Sat, 13 Jan 2007 10:04:17 -0600, Paul McGuire wrote: > [snip] > > Surely this is only worth doing if the comparison is expensive? > Testing beats intuition, so let's find out... > > class Compare: > def __init__(self, x): > self.x = x > def __eq__(self, other): > return self.x == other.x > > class CompareWithIdentity: > def __init__(self, x): > self.x = x > def __eq__(self, other): > return self is other or self.x == other.x > > Here's the timing results without the identity test: > >>>> import timeit >>>> x = Compare(1); y = Compare(1) >>>> timeit.Timer("x = x", "from __main__ import x,y").repeat() > [0.20771503448486328, 0.16396403312683105, 0.16507196426391602] >>>> timeit.Timer("x = y", "from __main__ import x,y").repeat() > [0.20918107032775879, 0.16187810897827148, 0.16351795196533203] > > And with the identity test: > >>>> x = CompareWithIdentity(1); y = CompareWithIdentity(1) >>>> timeit.Timer("x = x", "from __main__ import x,y").repeat() > [0.20761799812316895, 0.16907095909118652, 0.16420602798461914] >>>> timeit.Timer("x = y", "from __main__ import x,y").repeat() > [0.2090909481048584, 0.1968839168548584, 0.16479206085205078] > > Anyone want to argue that this is a worthwhile optimization? :) Perhaps. But first test it with "==". -- Neil Cerutti From gagsl-py at yahoo.com.ar Mon Jan 8 12:55:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 14:55:57 -0300 Subject: popen, Pipes with programs that expect user input In-Reply-To: <536598837.20070108180654@mail.ru> References: <536598837.20070108180654@mail.ru> Message-ID: <7.0.1.0.0.20070108145148.032a5208@yahoo.com.ar> At Monday 8/1/2007 13:06, Alex wrote: >So far everything works fine, but I encounter a problem with commands >which require some sort of user input; i.e. they don't return >immediately. > >Could someone point out the cause of this? It seems to me that the >interpreter is stuck at this line > data=fouterr.read() > >and it won't go forward unless popen returns. If so, how should the >objective be achieved? Read the docs on the popen2 module, specially the last section on syncronization. Depending on how bad your child process behaves (the date command in this case) you may need to use up to three separate threads for processing stdin, stdout, stderr. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nmm1 at cus.cam.ac.uk Fri Jan 12 12:15:56 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 12 Jan 2007 17:15:56 GMT Subject: Rational Numbers References: Message-ID: In article , Facundo Batista writes: |> Noud Aldenhoven wrote: |> |> > There are a (small) couple of other issues where rational numbers could be |> > handy. That's because rational numbers are exact, irrational numbers (in |> > python) aren't. But these issues are probably too mathematical to be used in |> |> For the sake of me being less ignorant, could you please point me a |> language where irrational numbers are exact? Some of the algebraic languages. (2/3)^(1/5) is held as such and manipulated appropriately. Yes, I know that's "cheating" :-) Regards, Nick Maclaren. From weekender_ny at yahoo.com Mon Jan 22 01:48:52 2007 From: weekender_ny at yahoo.com (John) Date: 21 Jan 2007 22:48:52 -0800 Subject: class explorer for automating IE Message-ID: <1169448532.869501.190530@v45g2000cwv.googlegroups.com> I found this class which was written in 2003. http://xper.org/wiki/seminar/InternetExplorerAutomation Is there a better/more complete version around that someone knows of. Thanks, --j From sjmachin at lexicon.net Thu Jan 11 03:11:25 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2007 00:11:25 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168461822.591030.74360@i56g2000hsf.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168461822.591030.74360@i56g2000hsf.googlegroups.com> Message-ID: <1168503084.828765.196790@77g2000hsv.googlegroups.com> sturlamolden wrote: > oyekomova wrote: > > Thanks for your help. I compared the following code in NumPy with the > > csvread in Matlab for a very large csv file. Matlab read the file in > > 577 seconds. On the other hand, this code below kept running for over 2 > > hours. Can this program be made more efficient? FYI - The csv file was > > a simple 6 column file with a header row and more than a million > > records. > > > > > > import csv > > from numpy import array > > import time > > t1=time.clock() > > file_to_read = file('somename.csv','r') > > read_from = csv.reader(file_to_read) > > read_from.next() > > > datalist = [ map(float, row[:]) for row in read_from ] > > I'm willing to bet that this is your problem. Python lists are arrays > under the hood! > > Try something like this instead: > > > # read the whole file in one chunk > lines = file_to_read.readlines() > # count the number of columns > n = 1 > for c in lines[1]: > if c == ',': n += 1 > # count the number of rows > m = len(lines[1:]) Please consider using m = len(lines) - 1 > #allocate > data = empty((m,n),dtype=float) > # create csv reader, skip header > reader = csv.reader(lines[1:]) lines[1:] again? The OP set you an example: read_from.next() so you could use: reader = csv.reader(lines) _unused = reader.next() > # read > for i in arange(0,m): > data[i,:] = map(float,reader.next()) > > And if this is too slow, you may consider vectorizing the last loop: > > data = empty((m,n),dtype=float) > newstr = ",".join(lines[1:]) > flatdata = data.reshape((n*m)) # flatdata is a view of data, not a copy > reader = csv.reader([newstr]) > flatdata[:] = map(float,reader.next()) > > I hope this helps! From fdelente at mail.cpod.fr Fri Jan 26 16:50:26 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 26 Jan 2007 21:50:26 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> Message-ID: <45ba77a2$0$26693$426a74cc@news.free.fr> > What happens when you try this? > stdscr.addstr(0,0, u"le?on".encode('iso8859-15')) > I don't really expect it to work And it doesn't... As support for 8-bit (and even unicode) is important for my script, is there any hope? Should I switch to slang instead of curses? -- Fabrice DELENTE From nmm1 at cus.cam.ac.uk Tue Jan 9 06:38:09 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 9 Jan 2007 11:38:09 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: |> Rory Campbell-Lange wrote: |> |> > Is using the decimal module the best way around this? (I'm |> > expecting the first sum to match the second). It seem |> > anachronistic that decimal takes strings as input, though. As Dan Bishop says, probably not. The introduction to the decimal module makes exaggerated claims of accuracy, amounting to propaganda. It is numerically no better than binary, and has some advantages and some disadvantages. |> Also check the recent thread "bizarre floating point output". No, don't. That is about another matter entirely, and will merely confuse you. I have a course on computer arithmetic, and am just now writing one on Python numerics, and confused people may contact me - though I don't guarantee to help. Regards, Nick Maclaren. From Barry.Carroll at psc.com Wed Jan 17 13:50:20 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 17 Jan 2007 10:50:20 -0800 Subject: *POLL* How many sheeple believe in the 911 fairy tale and willingto accept an Orwellian doublespeak and enslavement world ? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A7B@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: st911 at rock.com [mailto:st911 at rock.com] > Sent: Wednesday, January 17, 2007 10:23 AM > To: python-list at python.org > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > > > ... buildings collapse all the time when you design to the cold-formed > > strength rather than the hot-formed strength of a material, then heat > > the material removing its tempered strength (which for steel occurs at > > much lower than usual flame temeratures). > > Actually, modern steel frame buildings have never collapsed from > kerosine fire. > Besides there are SERIOUS anomalies indicative of thermate and > explosives. > Yellow hot molten metal were seen trickling down less than hour after > the fires. > Red hot molten metal pools were seen in the rubble weeks after the > collapse. > The building and their contents pulverized to dust from the brisance of > very well > planted and hidden explosives. I was not aware that Alqaeda has > invisible man > technology past the security cameras. > > > And what did this rant have to do with any of the sci.* or programming > > newsgroups you posted it to? > > Your ignoramus is the exact reason why this has to be posted there. > > > David A. Smith > > And why did bldg 7 commit suicide. How was the boeing767 maneouvered > so close to the ground into pentagon? > > Where is the DNA to confirm the identities of 19 in the fairy tale? > > Do you work for the story writing agency ? > Ladies and Gentlemen: PLEASE take this discussion to a more appropriate forum. There are many forums where people will be happy to debate this: physics, firefighting, metallurgy, geopolitics, etc. This forum is about the Python programming language. Let's keep it that way. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From igouy at yahoo.com Sat Jan 20 14:34:46 2007 From: igouy at yahoo.com (Isaac Gouy) Date: 20 Jan 2007 11:34:46 -0800 Subject: Py 2.5 on Language Shootout In-Reply-To: References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> <45B23400.2010906@gmx.de> Message-ID: <1169321686.025356.120340@s34g2000cwa.googlegroups.com> Ramon Diaz-Uriarte wrote: > On 1/20/07, Carl Friedrich Bolz wrote: > > pgarrone at acay.com.au wrote: > > >>> Looking over the benchmarks, one gains the impression that Python is a > > >>> slow language. > > >> What does that even mean - a slow language? > > >> > > > > > > The alioth benchmarks provide a set of numbers by which > > > languages may be compared. > > > > Wrong. The benchmarks provide a set of numbers by which > > _implementations_ of languages can be compared. After all, it is > > possible that someone implements a magic-pixie-dust-interpreter that > > executes Python programs several orders of magnitude fastes than > > CPython. Or you could say that C is slow because if you use CINT, a C > > interpreter ( http://root.cern.ch/root/Cint.html ) to execute it, it is > > slow. > > > Yeah, but this is hair-splitting. Except for Jython, IronPython, and > Stackless, I think when we say "Python is slow/fast" we think CPython > (otherwise, we qualify the implementation). For that matter it is > often said "the GIL ..."; oh, but wait, Stackless ... When we say "Python is slow/fast" what does "slow/fast" mean? > > With other languages (e.g., Common Lisp) the separation between the > language and the implementation is key because, to begin with, there > is something external from, and independent of, any particular > implementation. That is not the case with Python. > > And the example of CINT is hair-splitting to the nth power.To begin > with, I do not think CINT implements the full standard C. But even if > it were, when people think of C they rarely think of CINT. And that's why the existence of CINT is such a stark reminder of the separation between the language and the implementation. When people think of C what do they think of - gcc? tiny-c? intel c? microsoft c? some mythical C implementation? > > I think readers understood the previous poster. > > Best, > > R. > > > > Cheers, > > > > Carl Friedrich Bolz > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Ramon Diaz-Uriarte > Statistical Computing Team > Structural Biology and Biocomputing Programme > Spanish National Cancer Centre (CNIO) > http://ligarto.org/rdiaz From bearophileHUGS at lycos.com Wed Jan 10 20:06:34 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Jan 2007 17:06:34 -0800 Subject: what is the idiom for copy lots of params into self? In-Reply-To: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> Message-ID: <1168477594.373942.265430@77g2000hsv.googlegroups.com> Emin: > This saves a lot of code and makes it easier to see what is going on, > but it seems like there should be a better idiom for this task. Any > suggestions? I know two ways of doing it, one way requires very light code into the __init__ and it uses a decorator that takes the parameters and updates self, but I have seen it's not much reliable in the implementation I have. The other way requires a bit more code into the method, but the function code is quite short, easy to understand, and it seems reliable enough (code from web.py, a bit modified): def selfassign(self, locals): for key, value in locals.iteritems(): if key != 'self': setattr(self, key, value) Used on the first line as: def __init__(self, foo, bar, baz=1): selfassign(self, locals()) Bye, bearophile From bearophileHUGS at lycos.com Mon Jan 22 21:37:53 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Jan 2007 18:37:53 -0800 Subject: Symbols again Message-ID: <1169519873.555022.150280@v45g2000cwv.googlegroups.com> Modifying another recipe, I have defined some symbols again: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/500273 I don't know if this may be useful for something real. Bye, bearophile From time.swift at gmail.com Mon Jan 8 14:08:16 2007 From: time.swift at gmail.com (time.swift at gmail.com) Date: 8 Jan 2007 11:08:16 -0800 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <1168283295.899914.125400@38g2000cwa.googlegroups.com> Wow, I got a lot more feedback than I expected! I can see both sides of the argument, both on technical merits, and more philosophical merits. When I first learned C++ I felt setters/getters were a waste of my time and extra code. When I moved to C# I still felt that, and with their 'Property" syntax I perhaps felt it more. What changed my mind is when I started placing logic in them to check for values and throw expections or (hopefully) correct the data. That's probably reason one why I find it weird in Python Reason two is, as the user of a class or API I *don't care* what is going on inside. All I want visible is the data that I can change. The '_' convention is nice.. I do see that. I guess my old OOP classes are hard to forget about. I feel that the state of an object should be "stable" and "valid" at all times, and if its going into an unstable state - error then, not later. That's why I like being able to protect parts of an instances state. If, as a provider of a calculation engine, I let the user change the internal state of the engine, I have no assurances that my product (the engine) is doing its job... I appreciate all the feed back and enjoyed reading the discussion. It helps me understand why Python community has chosen the road they have. - Thanks. From ptmcg at austin.rr._bogus_.com Sat Jan 6 12:42:37 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 6 Jan 2007 11:42:37 -0600 Subject: C++/Python programmers for a MUD's gamedriver wanted. References: <1168102038.680286.73330@42g2000cwt.googlegroups.com> Message-ID: <459fdf8e$0$4849$4c368faf@roadrunner.com> "Rythin" wrote in message news:1168102038.680286.73330 at 42g2000cwt.googlegroups.com... > Hi everyone. > We are looking for a volunteer co-programmers for a MUD's gamedriver > project. As of now, a gamedriver is divided into two separate but > tightly interconnected systems - C++ driver and Python lib. > > C++ Driver is supposed to be managing memory, proccesses and > communication between them (transparent as far as net is concerned). > Python lib is to define the user's interfaces. Both of them are > designed to work in an object-oriented enviroment, with lib's classes > being driver's child-classes. > Have you considered whether the C++ Driver is even necessary? Python's run-time engine already implements the memory and process management tasks, and does so in compiled C code (and has been tested and retested by hundreds, nay thousands, perhaps even millions of Python users). Interprocess communication can be done using CORBA or Pyro add-ons. You may do better by "letting Python be Python" instead of confining it to limited user graphical and/or text interaction, and then marshaling/unmarshaling commands and responses to and from the C++ layer. Before getting too wrapped up in the C++ core/utility layer, get this (or a prototype) running in pure Python first, measure the performance, and then reimplement in C/Pyrex/ShedSkin/C++ for the performance-intensive bits. -- Paul From konrad.hinsen at laposte.net Thu Jan 11 12:33:07 2007 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Thu, 11 Jan 2007 18:33:07 +0100 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: <9B9711A6-8B6C-4D35-BAF1-373F81DBB4D2@laposte.net> On Jan 8, 2007, at 11:33, Duncan Booth wrote: > The 'parallel python' site seems very sparse on the details of how > it is > implemented but it looks like all it is doing is spawning some > subprocesses > and using some simple ipc to pass details of the calls and results. > I can't > tell from reading it what it is supposed to add over any of the other > systems which do the same. > > Combined with the closed source 'no redistribution' license I can't > really > see anyone using it. I'd also like to see more details - even though I'd probably never use any Python module distributed in .pyc form only. From the bit of information there is on the Web site, the distribution strategy looks quite similar to my own master-slave distribution model (based on Pyro) which is part of ScientificPython. There is an example at http://dirac.cnrs-orleans.fr/hg/ScientificPython/main/? f=08361040f00a;file=Examples/master_slave_demo.py and the code itself can be consulted at http://dirac.cnrs-orleans.fr/hg/ScientificPython/main/? f=bce321680116;file=Scientific/DistributedComputing/MasterSlave.py The main difference seems to be that my implementation doesn't start compute jobs itself; it leaves it to the user to start any number he wants by any means that works for his setup, but it allows a lot of flexibility. In particular, it can work with a variable number of slave jobs and even handles disappearing slave jobs gracefully. Konrad. -- --------------------------------------------------------------------- Konrad Hinsen Centre de Biophysique Mol?culaire, CNRS Orl?ans Synchrotron Soleil - Division Exp?riences Saint Aubin - BP 48 91192 Gif sur Yvette Cedex, France Tel. +33-1 69 35 97 15 E-Mail: hinsen at cnrs-orleans.fr --------------------------------------------------------------------- From nogradi at gmail.com Sat Jan 13 15:48:48 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 13 Jan 2007 21:48:48 +0100 Subject: sqlobject 0.8.0b1 and python 2.5 In-Reply-To: <871wly7k2o.fsf@gmail.com> References: <50st46F1hiu23U1@mid.uni-berlin.de> <871wly7k2o.fsf@gmail.com> Message-ID: <5f56302b0701131248t58629ab5of998aaee1c10d8a7@mail.gmail.com> > > To my knowledge, the 0.8.x series is the current line of development, and has > > made major progress over the previous versions. What makes you think it will > > be stopped developing? And where does a sqlobject2 come from? > > http://www.sqlobject.org/2/ Yes, that's what I meant. The website says: """ So, what is this? This is a project to factor out pieces of SQLObject, and make it more comfortable to use SQLObject in combination with ad hoc queries, to build on SQLObject, and generally to do interesting things. """ as well as """ Right now (Feb 2006) SQLObject 2 is pre-alpha, and is very not compatible with SQLObject 0.X. """ So I was wondering if waiting for sqlobject2 is a good strategy or going ahead with sqlobject. Probably I'll do the latter (the DeprecationWarnings also became clear in the meantime, there was some slight API change between recent versions). From thinker at branda.to Mon Jan 8 02:57:13 2007 From: thinker at branda.to (Thinker) Date: Mon, 08 Jan 2007 15:57:13 +0800 Subject: another SQL implement Message-ID: <45A1F959.7010403@branda.to> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 hello, I have implement a SQL command generator for Python. It uses features and syntax of Python to describe SQL schema & query. Following is a example: from pysqlite2 import dbapi2 as sqlite from pysql import * # # define data source # comprises tables and queries # class my_data_src(data_src): def ds_definition(): class t1(pysql.table): # # define table 't1' # item = pysql.str_f() count = pysql.int_f() pass class t2(pysql.table): # # define table 't2' # item = pysql.str_f() money = pysql.float_f() pass # # define a query 'get_count_and_money_of_item' # get_count_and_money_of_item = \ lambda: (t1 * t2) \ .fields(t1.item, t1.count * t2.money - 30) \ .where((t1.item == t2.item) & (t1.item != pysql._q)) return ds_define() pass cx = sqlite.connect('test .db') db = my_data_src(cx) # create a instance of data source db.init_db() # create tables db.insert(db.t1, item='foo', count=100) db.insert(db.t2, item='foo', money=3.2) db.insert(db.t1, item='boo', count=50) db.insert(db.t2, item='boo', money=3.0) db.update(db.t1, count=140, where=~(db.t1.item == 'foo')) cu = db.get_count_and_money_of_item('foo') rows = cu.fetchall() print rows cu = db.get_count_and_money_of_item('cool') rows = cu.fetchall() print rows db.commit() pass This is example code to define database schema and query. get_count_and_money_of_item is initialized by a lambda expression. It can also be a function. By inherit class data_src and defining method ds_definition, my_data_src is acting as a wrapper of a database. It includes two tables, t1 & t2, and a query, get_count_and_money_of_item. Instantiate a instance of my_data_src with a DB connection, you can create tables (init_db), insert records, update records, and perform queries. get_count_and_money_of_item = \ lambda: (t1 * t2) \ .fields(t1.item, t1.count * t2.money - 30) \ .where((t1.item == t2.item) & (t1.item != pysql._q)) (t1 * t2) means join tables t1 & t2, you can specify fields to be return by query with *.fields(...). *.where() is just like WHERE expression in SQL. get_count_and_money_of_item comprises a free-variable; pysql._q stands as a free-variable waiting for caller specified as parameter when calling get_count_and_money_of_item. cu = db.get_count_and_money_of_item('foo') rows = cu.fetchall() It calls get_count_and_money_of_item() with 'foo' for free-variable. A query returns a cursor defined in DBAPI. Why another SQL ? Why not SQLObject? RDBMS provides powerful query language, it provides performance by reducing traffic between database & application and reducing memory copy. A OR-mapping made RDBMS weak. DBMS is reduced as a indexed storage. Relational algebra is so powerful & effective. Why don't integrate it into Python language? Downloads: The implementation depend on pythk, so you need two modules, pysql & pythk http://master.branda.to/downloads/pysql/pysql-20070108.tar.gz http://master.branda.to/downloads/pythk/pythk-20070108.tar.gz - -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (FreeBSD) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFFoflZ1LDUVnWfY8gRAqw9AJ9UQ5OAOIEWo+ovELQvcKohAkWJtwCfcloq ecOxlrstOZ77Mr9qPxlkBj0= =U12Y -----END PGP SIGNATURE----- From jan-python-list at maka.demon.nl Mon Jan 29 08:16:32 2007 From: jan-python-list at maka.demon.nl (Jan Kanis) Date: Mon, 29 Jan 2007 14:16:32 +0100 Subject: interactive prompt in IDLE Message-ID: Hello everyone, I'm trying to change the interactive python prompt. According to the docs this is done by changing sys.ps1 and sys.ps2 . That works fine when running python interactively from a command line, but when running in IDLE the .ps1 and .ps2 don't seem to exist. I suppose this has something to do with Idle and the python shell in it both running in different processes, with the prompts generated by the Idle process? Does anyone know if and how to change the prompts in IDLE's interactive python? Jan From pavlovevidence at gmail.com Wed Jan 17 02:07:49 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 16 Jan 2007 23:07:49 -0800 Subject: How to convert float to sortable integer in Python In-Reply-To: <1169015814.960023.40310@a75g2000cwd.googlegroups.com> References: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> <1169015814.960023.40310@a75g2000cwd.googlegroups.com> Message-ID: <1169017669.651476.121910@a75g2000cwd.googlegroups.com> shellon wrote: > I'm sorry I mistake the function name, the function is > floatToRawIntBits(), it convert ieee 754 floating point number to > integer, e.g. if f1>f2 then floatToRawBits(f1) > floatToRawBits(f1) You can get the raw bits of a floating point number by packing into a string then unpacking it as an integer, but the invariant you give doesn't hold when you do that. That is, f1>f2 does not guarantee rawbits(f1)>rawbits(f2). So be warned. Python floats are double-precision internally, so the integer returned would have to hold at least 64-bits (i.e., it'd be a long on 32-bit platforms). import struct def double_to_raw_int(d): return struct.unpack("=q",struct.pack("=d",d)) > I want convert floating point number to sortable string to index in > Lucene, so I want first to conver the floating point number to integer > first, and than convert the integer to sortable string? I presume that, by "sortable string", you mean a numerical representation (padded or something), but if all you want is a string containing the bits of the number, struct.pack("=d",d) will get you an 8-byte string representing the bits without having to change it to an integer first. Check the documentation for the struct module if you need a certain endianness. > so How to convert a ieee 754 floating point to raw bits like the java > api floatToRawBits do? See documentation for the struct module. Carl Banks From mail at microcorp.co.za Thu Jan 11 01:17:07 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 11 Jan 2007 08:17:07 +0200 Subject: Is there a way to protect a piece of critical code? References: <000b01c734a0$2f635840$03000080@hendrik> <45A52FD0.60802@holdenweb.com> Message-ID: <00fd01c73548$1f7c3660$03000080@hendrik> "Steve Holden" wrote: > Hendrik van Rooyen wrote: > > Hi, > > > > I would like to do the following as one atomic operation: > > > > 1) Append an item to a list > > 2) Set a Boolean indicator > > > > It would be almost like getting and holding the GIL, > > to prevent a thread swap out between the two operations. > > - sort of the inverted function than for which the GIL > > seems to be used, which looks like "let go", get control > > back via return from blocking I/O, and then "re - acquire" > > > > Is this "reversed" usage possible? > > Is there some way to prevent thread swapping? > > > This seems to me to be a typical example of putting the cart before the > horse. Therefore, please don't think that what follows is directed > specifically at you: it's directed at everybody who thinks that their > problem is something other than it really is (of course, my extensive > experience on c.l.py plus my well-known psychic powers uniquely qualify > me to explain to you that you don't understand your own problem). Yes of course - I see this happening all the time here - have probably done it myself... > > > The question arises in the context of a multi threaded > > environment where the list is used as a single producer, > > single consumer queue - I can solve my problem in various > > ways, of which this is one, and I am curious as to if it is > > possible to prevent a thread swap from inside the thread. > > > Of course you will know what they say about curiosity [1]. > My understanding about it is not as advanced as yours- I was under the possibly false impression that it had something vaguely to do with felines. > You don't say what the Boolean indicator is for. My natural inclination > is to assume it's to say whether there's anything in the list. The > Twisted crew can tell you this is a terrible mistake,. What you should > really do is define a function that waits until there is something to > put on the list and then returns a deferred that will eventually > indicate whether the insertion was successful [2]. > How did you ever guess that it was exactly what I in my misguided zeal to make the code understandable for myself did? As for the Theatrical Twisted way of saying: "Don't call us, we'll call you ! " I don't reeaally have the time to wait... > But your *actual* problem appears to be the introduction of critical > sections into your program, a question about which computer scientists > have written for over forty years now, albeit in the guise of > discussions about how to get a good meal [3]. > Hmmmm - this can get philosophical - Most days, I write in assembler, on bare metal small systems - and would ya believe - no matter how I squirm - some bloody piece of code always turns out to be critical - the hard part is to recognise that it is so when you write it, Instead of having it bite you in the arse whan you are not looking. > I could go on, but I am realising as I write that less and less of this > is really relevant to you. In short, please don't try to reinvent the > wheel when there are wheelwrights all around and a shop selling spare > wheels just around the corner. Python is already replete with ways to > implement critical sections and thread-safe queuing mechanisms [5]. > Now I know that a Youngster like you would not believe me when I tell you that I know about queues and locks, so I won't bother. > I could, of course, say > > http://www.justfuckinggoogleit.com/search.pl?query=python+atomic+operation > > but that would seem rude, which is against the tradition of c.l.py. > Besides which the answers aren't necessarily as helpful as what's been > posted on this thread, so I'll content myself with saying that one's can > often be better spent R'ing TFM than posting on this newsgroup, but that > while Google /may/ be your friend it's not as good a friend as this > newsgroup. > Rudeness is against the tradition? But bluntness is ok? > If it isn't obvious that this post was meant more to amuse regular > readers than inform and/or chastise someone who isn't (yet) one then > please accept my apologies. Fortunately I don't normally go on like this > more than once a year, so now it's hey ho for 2008 [6]. > Happy New Year Steve - I for one have missed your posts lately. I was beginning to feel you don't love me anymore... 8<-------------- some explanatory stuff ------------------ *sigh* - I guess all this is just a nice way of saying "no!" to the question. - Hendrik From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 26 13:27:51 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 26 Jan 2007 19:27:51 +0100 Subject: Mounting shares with python References: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> Message-ID: <51uvh7F1m9svaU1@mid.individual.net> Marcpp wrote: > Hi, when i mount a share with python... > > os.system ("mount -t smbfs -o username=nobody ...") > > the problem is that I'll to be root. Consider modifying /etc/fstab. > Have a comand to send a root password...? > I've tried > > os.system ("su") > os.system ("the password") > > but it doesn't works. Be advised that storing a root password as clear text can be a huge security risk. Use sudo. Regards, Bj?rn -- BOFH excuse #9: doppler effect From mail at microcorp.co.za Fri Jan 26 02:17:28 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 26 Jan 2007 09:17:28 +0200 Subject: The reliability of python threads References: <45B90118.5010408@mvista.com> Message-ID: <01b001c7411d$17e52a20$03000080@hendrik> "Carl J. Van Arsdall" wrote: > Right, I wasn't coming here to get someone to debug my app, I'm just > looking for ideas. I constantly am trying to find new ways to improve > my software and new ways to reduce bugs, and when i get really stuck, > new ways to track bugs down. The exception won't mean much, but I can > say that the error appears to me as bad data. I do checks prior to > performing actions on any data, if the data doesn't look like what it > should look like, then the system flags an exception. > > The problem I'm having is determining how the data went bad. In > tracking down the problem a couple guys mentioned that problems like > that usually are a race condition. From here I examined my code, > checked out all the locking stuff, made sure it was good, and wasn't > able to find anything. Being that there's one lock and the critical > sections are well defined, I'm having difficulty. One idea I have to Are you 100% rock bottom gold plated guaranteed sure that there is not something else that is also critical that you just haven't realised is? This stuff is never obvious before the fact - and always seems stupid afterward, when you have found it. Your best (some would say only) weapon is your imagination, fueled by scepticism... > try and get a better understanding might be to check data before its > stored. Again, I still don't know how it would get messed up nor can I > reproduce the error on my own. > > Do any of you think that would be a good practice for trying to track > this down? (Check the data after reading it, check the data before > saving it) Nothing wrong with doing that to find a bug - not as a general practice, of course - that would be too pessimistic. In hard to find bugs - doing anything to narrow the time and place of the error down is fair game - the object is to get you to read some code that you *know works* with new eyes... I build in a global boolean variable that I call trace, and when its on I do all sort of weird stuff, giving a running commentary (either by print or in some log like file) of what the programme is doing, like read this, wrote that, received this, done that here, etc. A bare useful minimum is a "we get here" indicator like the routine name, but the data helps a lot too. Compared to an assert, it does not stop the execution, and you could get lucky by cross correlating such "traces" from different threads. - or better, if you use a queue or a pipe for the "log", you might see the timing relationships directly. But this in itself is fraught with danger, as you can hit file size limits, or slow the whole thing down to unusability. On the other hand it does not generate the volume that a genuine trace does, it is easier to read, and you can limit it to the bits that you are currently suspicious of. Programming is such fun... hth - Hendrik From paddy3118 at netscape.net Thu Jan 25 14:50:02 2007 From: paddy3118 at netscape.net (Paddy) Date: 25 Jan 2007 11:50:02 -0800 Subject: The reliability of python threads In-Reply-To: References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> Message-ID: <1169754601.992058.205640@q2g2000cwa.googlegroups.com> On Jan 25, 7:36 pm, n... at cus.cam.ac.uk (Nick Maclaren) wrote: > In article <1169751828.986583.47... at j27g2000cwj.googlegroups.com>,"Paddy" writes:|> > |> > |> Three to four months before `strange errors`? I'd spend some time > |> > |> correlating logs; not just for your program, but for everything running > |> > |> on the server. Then I'd expect to cut my losses and arrange to safely > |> > |> re-start the program every TWO months. > |> > |> (I'd arrange the re-start after collecting logs but before their > |> > |> analysis. Life is too short). > |> > > |> > Forget it. That strategy is fine in general, but is a waste of time > |> > where threading issues are involved (or signal handling, or some types > |> > of communication problem, for that matter). > |> > |> Nah, Its a great strategy. it keeps you up and running when all you > |> know for sure is that you will most likely be able to keep things > |> together for three months normally. > |> > |> The OP only thinks its a threading problem - it doesn't matter what the > |> true fix will be, as long as arranging to re-start the server well > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > |> before its likely to go down doesn't take too long, compared to your > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > |> exploration of the problem, and, of course, you have to be able to > |> afford the glitch in availability. > > Consider the marked phrase in the context of a Poisson process failure > model, and laugh. If you don't understand why I say that, I suggest > finding out the properties of the Poisson process! > > Regards, > Nick Maclaren. No, you should think of the service that needs to be up. You seem to be talking about how it can't be fixed rather than looking for ways to keep things going. A little learning is fine but "it can't theoretically be fixed" is no solution. With a program that stays up for that long, the situation will usualy work out for the better when either software versions are upgraded, or OS and drivers are upgraded. (Sometimes as a result of the analysis, sometimes not). Keep your eye on the goal and your more likely to score! - Paddy. From vatamane at gmail.com Wed Jan 24 17:15:47 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 24 Jan 2007 14:15:47 -0800 Subject: Best way to document Python code... In-Reply-To: References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: <1169676947.717450.310380@m58g2000cwm.googlegroups.com> Epydoc is the way to go. You can even choose between various formating standards (including javadoc ) and customize the output using CSS. On Jan 22, 7:51 pm, "Stuart D. Gathman" wrote: > On Mon, 22 Jan 2007 17:35:18 -0500, Stuart D. Gathman wrote: > > The HTML generated by pydoc doesn't link to standard modules properly. > > They are generated as relative links. So it can't be used without > > modification for generating docs for a web page about a python package. > > > I'm struggling with the same issue. Coding Python is so much easier than > > Java. However documenting Java is so much easier than Python. Just > > include doc comments, run javadoc, and voila!Wow! I just tried epydoc, and it is every bit as easy as javadoc and > with similar output. Too bad it isn't standard. But the comments and > docstrings it parses work fine with pydoc also. > > -- > Stuart D. Gathman > Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 > "Confutatis maledictis, flamis acribus addictis" - background song for > a Microsoft sponsored "Where do you want to go from here?" commercial. From clodoaldo.pinto at gmail.com Tue Jan 2 14:52:28 2007 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: 2 Jan 2007 11:52:28 -0800 Subject: How to format a number? Message-ID: <1167767548.895026.88060@n51g2000cwc.googlegroups.com> I want to format a number with thousands separator to the 'pt_br' locale. I'm trying like this: >>> import locale >>> locale.setlocale(locale.LC_ALL, ('pt_br', 'ascii')) 'pt_BR.ISO8859-1' >>> locale.format('%d', 9876, True) '9876' >>> locale.localeconv()['thousands_sep'] '' >>> locale.localeconv()['mon_thousands_sep'] '.' The thousands separator is defined only for the ['mon_thousands_sep'] key and not for the ['thousands_sep'] one. What should be done? Set the ['thousands_sep'] to '.' or somehow build the format string as a monetary number? If any of the former, how? Regards, Clodoaldo Pinto Neto From s.mientki at id.umcn.nl Tue Jan 23 03:44:46 2007 From: s.mientki at id.umcn.nl (stef) Date: Tue, 23 Jan 2007 09:44:46 +0100 Subject: Python Windows Editors In-Reply-To: References: Message-ID: <7d773$45b5cb01$83aef404$30645@news2.tudelft.nl> Laurent Pointal wrote: > W. Watson a ?crit : > >> I downloaded python-2.5.msi and installed it. I believe its editor is >> IDE. I understand there's a Win editor called pythonwin. I believe it's >> in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this >> exe file has just the editor or all of Python. Comments? If not how do I >> get the PythonWin editor by itself? >> >> > Have you take a look at the IDEs page in the Python Wiki (python.org)? > > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > > just what I said, TOO many ;-) and of course how do you keep these pages up-to-date ? Zeus (commercial) isn't mentioned ... SPE which has great credits, but can't be found, and if you find it somewhere, no manual and it crashes within 30 seconds (repeatly) ;-) Not an easy task I guess, but it would be nice to have some voting system, (maybe only to allow voting when you have compared at least 2 programs) that would represent the current state, and in which new programs would have a fair chance to start. cheers, Stef Mientki From grante at visi.com Thu Jan 4 22:29:17 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 03:29:17 -0000 Subject: pow() works but sqrt() not!? References: <1167899693.759071.51450@31g2000cwt.googlegroups.com> Message-ID: <12prhgd718if708@corp.supernews.com> On 2007-01-05, Gabriel Genellina wrote: > At Thursday 4/1/2007 10:12, siggi wrote: > >>Thanks for the explanation. I am astonished what an interpreted >>language is able to do! > > Python is as interpreted as Java. But it's far more interactive -- at least when compared with my limited experience with Java. > Its numerical capabilities are more or less independent of > this fact, I'd say. -- Grant Edwards grante Yow! What PROGRAM are at they watching? visi.com From tiedon_jano at hotmail.com Sun Jan 7 16:11:36 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 07 Jan 2007 21:11:36 GMT Subject: Python cheatsheets In-Reply-To: References: Message-ID: gonzlobo kirjoitti: > Curious if anyone has a python cheatsheet* published? I'm looking for > something that summarizes all commands/functions/attributes. Having > these printed on a 8" x 11" double-sided laminated paper is pretty > cool. > > * cheatsheet probably isn't the right word, but you get the idea. :) http://rgruet.free.fr/ HTH, Jussi From theller at ctypes.org Thu Jan 4 04:08:42 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 04 Jan 2007 10:08:42 +0100 Subject: question on creating class In-Reply-To: <1167895677.041759.230190@42g2000cwt.googlegroups.com> References: <1167895677.041759.230190@42g2000cwt.googlegroups.com> Message-ID: wcc schrieb: > Hello, > > How do I create a class using a variable as the class name? > > For example, in the code below, I'd like replace the line > > class TestClass(object): > with something like > class eval(className) (object): > > Is it possible? Thanks for your help. > > className = "TestClass" > > class TestClass(object): > def __init__(self): > print "Creating object of TestClass..." > > def method1(self): > print "This is a method." > > if __name__ == "__main__": > o = TestClass() > o.method1() > > -- > wcc > You call 'type' to create a new-style class. The signature is: "type(name, bases, dict) -> a new type". >>> def __init__(self): ... print "Creating object of TestClass..." ... >>> def method1(self): ... print "This is a method" ... >>> TestClass = type("TestClass", (), {"__init__": __init__, "method1": method1}) >>> >>> >>> help(TestClass) Help on class TestClass in module __main__: class TestClass(__builtin__.object) | Methods defined here: | | __init__(self) | | method1(self) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __dict__ = | dictionary for instance variables (if defined) | | __weakref__ = | list of weak references to the object (if defined) >>> TestClass() Creating object of TestClass... <__main__.TestClass object at 0x00AED0B0> >>> TestClass().method1() Creating object of TestClass... This is a method >>> Thomas From will at willNOmcguganSPAM.com Mon Jan 8 12:27:28 2007 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Mon, 08 Jan 2007 17:27:28 +0000 Subject: sys.exit versus raise SystemExit In-Reply-To: <1168273151.359419.118640@42g2000cwt.googlegroups.com> References: <45a26b70$0$32019$fa0fcedb@news.zen.co.uk> <1168273151.359419.118640@42g2000cwt.googlegroups.com> Message-ID: <45a27f06$0$31239$da0feed9@news.zen.co.uk> wittempj at hotmail.com wrote: > > sys.exit() raises a SystemExit, see > http://docs.python.org/lib/module-sys.html > Oh I know. I was just wondering if there was some sort of subtle 'best practice' recommendation that I wasnt aware of for using sys.exit over raising the exception manually. In the same way that 'open' is prefered over 'file', even though they appear to do the same thing. Will -- blog: http://www.willmcgugan.com From wangshuhao at sina.com Thu Jan 25 10:20:08 2007 From: wangshuhao at sina.com (Wang Shuhao) Date: Thu, 25 Jan 2007 23:20:08 +0800 Subject: how to unistall a Python package? References: Message-ID: <000601c74094$4d514e20$1400a8c0@mytomato> Third party packages are put into $PYTHONHOME\Lib\site-packages after been installed, so to uninstall them, just go there and delete the directory contains all files of your package. ----- Original Message ----- From: "siggi" Newsgroups: comp.lang.python To: Sent: Thursday, January 25, 2007 10:02 PM Subject: how to unistall a Python package? > Hi all, > > installing a package with 'setup.py' is easy. But how do I uninstall the > package, once I want to get rid of it again? > > Thanks, > > siggi > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From nagle at animats.com Wed Jan 17 20:32:20 2007 From: nagle at animats.com (John Nagle) Date: Thu, 18 Jan 2007 01:32:20 GMT Subject: import vs. subdirectory search Message-ID: <45AED511.8090307@animats.com> Some obscure import issues: I'm running Python 2.3.4 from a CGI script on a shared hosting Linux system. The CGI program is being executed from Apache, as "nobody". I have some local modules installed in "~myname/lib/python"; these include "MySQLdb" and "M2Crypto". Since this is running as "nobody", I append /home/myname/lib/python to sys.path. Within the CGI programs, import MySQLdb # works fine import M2Crypto # works fine import SSL # "No module named SSL" The problem is that SSL is in a subdirectory of the M2Crypto directory, and that's not being searched. I can execute "import M2Crypto.SSL", but that doesn't have the same effect; it puts SSL in a different place in the namespace. I'm trying to avoid that; it causes obscure aliasing problems. On Python 2.4 under Windows 2000, importing from a subdirectory appears to work. Is that a Python 2.3.4 thing, or a Linux thing, or something else? (The idea is to be able to run (mostly) the same Python code on Windows, for test, and Linux, for production.) John Nagle From deets at nospam.web.de Mon Jan 29 14:05:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 Jan 2007 20:05:46 +0100 Subject: List Behavior when inserting new items In-Reply-To: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> Message-ID: <526ut2F1n2q69U1@mid.uni-berlin.de> Drew schrieb: > I'm looking to add an element to list of items, however I'd like to > add it at a specific index greater than the current size: > > list = [1,2,3] > list.insert(10,4) > > What I'd like to see is something like: > > [1,2,3,,,,,,4] > > However I see: > > [1,2,3,4] > > Is there any way to produce this kind of behavior easily? Use a dictionary? If you know how large the list eventually will be, and that each position is filled, you can also use range(n) to create a list. What is your actual usecase? diez From gandalf at designaproduct.biz Tue Jan 9 13:29:16 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 09 Jan 2007 19:29:16 +0100 Subject: how to clean sys.path In-Reply-To: References: Message-ID: <45A3DEFC.4060808@designaproduct.biz> > > So far, I know only the command >>>sys.path.append(r'c:....etc...'), but how > to delete or insert at the beginning of the list, I know not. > You can delete a slice. For example, del sys.path[2:5] More about slicing: http://docs.python.org/ref/slicings.html sys.path is a regular list. List methods: http://docs.python.org/tut/node7.html Best, Laszlo From adamgarstang at googlemail.com Mon Jan 29 14:35:34 2007 From: adamgarstang at googlemail.com (Adam) Date: 29 Jan 2007 11:35:34 -0800 Subject: Conversion of string to integer In-Reply-To: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> References: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> Message-ID: <1170099334.373371.9870@s48g2000cws.googlegroups.com> On Jan 29, 1:55 pm, "jupiter" wrote: > Hi guys, > > I have a problem. I have a list which contains strings and numeric. > What I want is to compare them in loop, ignore string and create > another list of numeric values. You can iterate over the list and use the type() function to work out what each entry and choose what to do with it. type() works like so: ###Code### >>> a = ["test", 1.25, "test2"] >>> if type(a[2]) == str: print "a string" a string >>> ###End Code### Adam From nyenyec at gmail.com Tue Jan 9 08:54:43 2007 From: nyenyec at gmail.com (nyenyec) Date: 9 Jan 2007 05:54:43 -0800 Subject: re.sub and re.MULTILINE In-Reply-To: <1168326636.436910.165360@v33g2000cwv.googlegroups.com> References: <1168316266.374186.271310@42g2000cwt.googlegroups.com> <1168326636.436910.165360@v33g2000cwv.googlegroups.com> Message-ID: <1168350883.587686.310010@m30g2000cwm.googlegroups.com> Paddy wrote: > Check the arguments to re.sub. > > >>> re.sub('(?m)^foo', 'bar', '\nfoo', count=0) > '\nbar' > > - Paddy. Duh! :) I appreciate it, thanks. -- nyenyec From redefined.horizons at gmail.com Sun Jan 7 11:14:04 2007 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 7 Jan 2007 08:14:04 -0800 Subject: Pausing for Python Interpreter error messages... In-Reply-To: <459fb2b6$0$324$426a74cc@news.free.fr> References: <1168058097.855006.229820@s80g2000cwa.googlegroups.com> <459fb2b6$0$324$426a74cc@news.free.fr> Message-ID: <1168186444.362107.147670@i15g2000cwa.googlegroups.com> Thanks Bruno. I'll get the 2.5 python install, and I'm checking out the unit testing module that you mentioned. Scott Huey Bruno Desthuilliers wrote: > redefined.horizons at gmail.com a ?crit : > > I've written a few classes that I have been testing in IDLE. However, > > every time I make a change to the classes based on the testing I have > > to walk through all he steps of preparing the classes for testing > > again. > > > > So I wrote a script that does all the set-up work for me. > > You may want to have a look at the unittest module then: > http://docs.python.org/lib/module-unittest.html > > > The only > > problem is when I run this script using the Python interpreter I can't > > get the command prompt to stay up long enough for me to read the > > message. > > > > How do I get the command prompt to stay up? > > first open the "command prompt", then launch your script from the > command prompt. > > > Is there a way to run my > > script and view the error message in IDLE? > > menu run->run module, or just hit the F5 key. > > > Thanks for the help. > > > > Scott Huey > > > > P.S. - I'm using Windows XP with the latest Python 2.3. > > > > Python 2.3 is years old. Latest is 2.5. From erinhouston at gmail.com Fri Jan 26 11:32:34 2007 From: erinhouston at gmail.com (ina) Date: 26 Jan 2007 08:32:34 -0800 Subject: newbie - returned values from cscript.exe In-Reply-To: <1169666769.242698.70730@j27g2000cwj.googlegroups.com> References: <1169666769.242698.70730@j27g2000cwj.googlegroups.com> Message-ID: <1169829154.071074.209580@h3g2000cwc.googlegroups.com> I did the same thing back before I knew about python and com. I hope this example gets you on the right track. It is just a simple script that does a dir and returns prints it out. import os, sys dCall = "dir" resultFromCall = os.popen(dCall) #get data back from the system call mv = resultFromCall.read() resultFromCall.close() print mv On Jan 24, 12:26 pm, "Rich" wrote: > I am writing my first python script and I'm guessing this is something > obvious but I can't find any examples of doing something like this. I > have a python script that is running a vbscript through cscript.exe. > The vbscript looks up a server name, username, password etc and returns > these values in a delimited list using wscript.echo. I can assign > these values to variables using a Windows batch files with the > following code > > FOR /F "tokens=1-6" %%a in ('cscript /nologo GetServerAccessInfo.vbs"') > do ( > SET DB_SERVER_NAME=%%a > SET DB_NAME=%%b > SET NMDBO_USERNAME=%%c > SET NMDBO_PASSWORD=%%d > SET SU_USERNAME=%%e > SET SU_PASSWORD=%%f > > I can't figure out how to do the same thing using a python script to > call this instead of a batch file. > > I am running the vbscript by using the following command > os.system('cscript /nologo GetServerAccessInfo.vbs') From surekap at gmail.com Thu Jan 25 01:46:26 2007 From: surekap at gmail.com (Prateek) Date: 24 Jan 2007 22:46:26 -0800 Subject: Fast Imaging for Webserver Message-ID: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> Hi. I'm creating a web-application using CherryPy 2.2.1. My application needs to process images (JPG/PNG files) to 1) create thumbnails (resize them) 2) overlay them on a custom background (a simple frame) 3) Overlay 'badges' (small 16x16 images) on top of the final thumbnail I am using PIL 1.1.5 which I have custom compiled on my development machine (MacBook Pro 2.33Ghz Core Duo).. I am using im.thumbnail for step 1 and im.paste for steps 2 and 3. The problem is that this thing is just way too slow. For ab -n 1000 -C session_id=2f55ae2dfefa896f67a80f73045aadfa4b4269f1 http://localhost:8080/imaging/icon/def/128/255 (where def is the name of the image - default in this case - 128 is the size in pixels and 255 is the background color), I am getting: Document Path: /imaging/icon/def/128/255 Document Length: 14417 bytes Concurrency Level: 1 Time taken for tests: 18.664 seconds Complete requests: 1000 Failed requests: 0 Broken pipe errors: 0 Total transferred: 14680000 bytes HTML transferred: 14417000 bytes Requests per second: 53.58 [#/sec] (mean) Time per request: 18.66 [ms] (mean) Time per request: 18.66 [ms] (mean, across all concurrent requests) Transfer rate: 786.54 [Kbytes/sec] received FYI: This request returns a PNG image (image/png) and not html My understanding is that the problem is either with the CherryPy setup (which is likely because even in other cases, i don't get much more than 65 requests per second) or PIL itself (even though I'm caching the background images and source images) Does anyone have a better solution? Is there a faster replacement for PIL? Thanks in advance. Prateek From michele.simionato at gmail.com Mon Jan 15 06:17:57 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jan 2007 03:17:57 -0800 Subject: Python web app. (advice sought) In-Reply-To: <45aae51b.0@entanet> References: <45aae51b.0@entanet> Message-ID: <1168859876.833009.118190@11g2000cwr.googlegroups.com> Duncan Smith wrote: > Hello, > I find myself in the, for me, unusual (and at the moment unique) > position of having to write a web application. I have quite a lot of > existing Python code that will form part of the business logic. This > relies on 3rd party libraries (such as numpy) which would make porting > to e.g. IronPython difficult (I would imagine). I was thinking LAMP > (the P standing for Python, of course), particularly as I was originally > encouraged to go for open source solutions. > > The application will provide some basic statistical analyses of data > contained in database tables and associated plots (R / matplotlib / > graphviz). There will also be some heavier duty Monte Carlo simulation > and graphical modelling / MCMC. The user(s) will need to be able to set > model parameters; maybe even tinker with model structure, so it will be > very interactive (AJAX?). > > I've had a look at Django, Turbogears and Plone, and at the moment I am > torn between Turbogears and Plone. I assume it will be an application with few users and no particular need for security. Read PEP 333, use the wsgiref server which is in the standard library (starting from Python 2.5+), have a look at Paste and write your own solution. At the least this is the way I did it. Michele Simionato From albert.wellens at gmail.com Tue Jan 16 12:02:34 2007 From: albert.wellens at gmail.com (awel) Date: 16 Jan 2007 09:02:34 -0800 Subject: Check a windows service Message-ID: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> Hi, I'm new in python and I would like to know if it's possible to check if a specific windows service is present and if it's possible how can I do? Thanks From horpner at yahoo.com Tue Jan 16 08:37:16 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Jan 2007 14:37:16 +0100 Subject: assert versus print [was Re: The curious behavior of integer objects] References: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> <1168931486.610893.250040@38g2000cwa.googlegroups.com> Message-ID: On 2007-01-16, Ron Adam wrote: > I have to admit that part of why assert seems wrong to me is > the meaning of the word implies something you shouldn't be able > to ignore. While warnings seem like something that can be > disregarded. Experienced C coders expect assert to behave like that. The only reason (I know of) to turn off error checking is to optimize. However, removing tests won't usually make a big enough speed difference to be worth the burthen of testing two different versions of the same source code. So to me the assert statement is either dubious syntax-sugar or dangerous, depending on Python's command line arguments. The warning module would seem to have limited applications. Searching my Python distribution shows that it's used for deprecation alerts, and elsewhere for turning those selfsame alerts off. How copacetic! It is the null module. ;-) -- Neil Cerutti Facts are stupid things. --Ronald Reagan From janencarl at aznex.net Thu Jan 25 20:38:36 2007 From: janencarl at aznex.net (Carl Trachte) Date: Thu, 25 Jan 2007 18:38:36 -0700 Subject: Getting started with Crystal Reports...little help in the far court. References: <1168293388.349793.256790@s80g2000cwa.googlegroups.com> Message-ID: Marc, I've been able to get some Business Objects COM functionality in Business Objects 6.5 (the logging in functionality I have to do through a call to an Excel VBA macro; otherwise things appear to work for what I'm doing). Unfortunately, I don't have experience with Python in Business Objects XI or Crystal Reports. I did have to play with makepy on a couple Business Objects files to get something useful. I believe I eventually struck paydirt with busobj.exe (but don't quote me on it - it's been a while). This information probably isn't terribly useful. The best advice I can give is to try the respective Crystal Reports and Business Objects XI executable files with makepy. If there's no joy there, start working with the dll's and see if they yield something that works. Hopefully someone with a bit more win32 or BO XI experience will chime in. In the meantime, good luck. Carl T. "Mudcat" wrote in message news:1168293388.349793.256790 at s80g2000cwa.googlegroups.com... > I am not that familiar with Crystal Reports, but having read some other > posts I know that the way to integrate the API with Python is through > the COM interface provide by win32all. > > However, I have been unable to find any other information on how to get > started. I've used the COM interface before in integrating Excel and a > couple of other things. So I am familiar with how that works. But there > are at least 40 options dealing with Crystal and Business Objects. I > have no idea which makepy file to create or which one provides the > functionality I need. > > I'm not looking to do much. All I'm really trying to do is provide one > application where a list of crystal reports can be selected and ran in > series. Right now we have a lot of reports that all have to be run > manually (takes a while). So I think all I need api access to is server > selection, parameter selection, and output formats. > > Any pointers in the right direction would be helpful. > > Thanks, > Marc > From bearophileHUGS at lycos.com Wed Jan 17 05:16:35 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 17 Jan 2007 02:16:35 -0800 Subject: How can I create a linked list in Python? In-Reply-To: References: <1168983652.192715.235580@a75g2000cwd.googlegroups.com> Message-ID: <1169028995.133660.299320@m58g2000cwm.googlegroups.com> Marc 'BlackJack' Rintsch: > Python has a list type without the "s, it's a real list. Don't confuse > the *ADT list* with *linked lists* which are just one implementation of > the ADT list. Right, I was mostly talking about (single/double) linked lists :-) Bye, bearophile From nagle at animats.com Thu Jan 25 15:51:51 2007 From: nagle at animats.com (John Nagle) Date: Thu, 25 Jan 2007 20:51:51 GMT Subject: Python does not play well with others In-Reply-To: <7xveiudg4o.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "sjdevnull at yahoo.com" writes: > >>I haven't had a need to do anything with OpenSSL from Python; all >>that takes place in the Apache server > > > That's a reasonable approach for a typical server-side web > application, but there are other types of Python apps that can also > want to use SSL. It's a pain to have to deal with OpenSSL at all, and > I hope that TLSLite (a very incomplete SSL implementation written in > pure Python) one day becomes complete and does all the stuff that JSSE > does. That's the problem. We now have four SSL implementations for Python, none of which let you do all the things OpenSSL can do. The fact that people keep writing new ones, instead of fixing the existing ones, indicates a problem with the development process. Can you build the built-in SSL package without building all of Python? That in itself would be useful. Then the thing could be worked on without too much pain. The built-in SSL package basically works, although it doesn't check anything. It just doesn't get at enough OpenSSL functionality. I think the right way out of this mess is to 1) break out the SSL module so it can be built separately by the usual "python setup.py build" process, 2) add more access functions to the built-in SSL C glue module, 3) bring over such Python parts of M2Crypto as are useful and make them work with the built-in SSL module, and 4) get rid of SWIG. If somebody will do 1), I'll take a look at 2). John Nagle From nunya at busyness.info Wed Jan 10 10:33:14 2007 From: nunya at busyness.info (Lefty Bigfoot) Date: Wed, 10 Jan 2007 15:33:14 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: <0001HW.C1CA63B1059BC980F0203648@news.verizon.net> On Wed, 10 Jan 2007 08:28:33 -0600, jmfbahciv at aol.com wrote (in article ): > In article , > "Elan Magavi" wrote: >> Is that like.. OctaPussy? > > I didn't read their stuff. Are they really trying to put a > round peg in a square hole? Sounds more like an octagonal pole in a round hole. -- Lefty All of God's creatures have a place.......... .........right next to the potatoes and gravy. See also: http://www.gizmodo.com/gadgets/images/iProduct.gif From gagsl-py at yahoo.com.ar Sun Jan 14 22:25:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 00:25:53 -0300 Subject: Conflicting needs for __init__ method In-Reply-To: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070114235851.01f01c18@yahoo.com.ar> At Sunday 14/1/2007 20:32, dickinsm at gmail.com wrote: >Of course, none of this really has anything to do with rational >numbers. There must be many examples of classes for which internal >calls to __init__, from other methods of the same class, require >minimal argument processing, while external calls require heavier and >possibly computationally expensive processing. What's the usual way >to solve this sort of problem? In some cases you can differentiate by the type or number of arguments, so __init__ is the only constructor used. In other cases this can't be done, then you can provide different constructors (usually class methods or static methods) with different names, of course. See the datetime class, by example. It has many constructors (today(), fromtimestamp(), fromordinal()...) all of them class methods; it is a C module. For a slightly different approach, see the TarFile class (this is a Python module). It has many constructors (classmethods) like taropen, gzopen, etc. but there is a single public constructor, the open() classmethod. open() is a factory, dispatching to other constructors depending on the combination of arguments used. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bearophileHUGS at lycos.com Wed Jan 24 20:03:55 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 24 Jan 2007 17:03:55 -0800 Subject: Static variables In-Reply-To: <45b7cfd4$0$16160$426a74cc@news.free.fr> References: <45b7cfd4$0$16160$426a74cc@news.free.fr> Message-ID: <1169687035.433771.177900@v45g2000cwv.googlegroups.com> Bruno Desthuilliers: > And this let you share state between functions: > > def make_counter(start_at=0, step=1): > count = [start_at] > def inc(): > count[0] += step > return count[0] > def reset(): > count[0] = [start_at] > return count[0] > def peek(): > return count[0] > > return inc, reset, peek > > foo, bar, baaz = make_counter(42, -1) > print baaz() > for x in range(5): > print foo() > print bar() > print baaz() An interesting solution, I have never created such grouped clorures. I don't know if this solution is better than a class with some class attributes plus some class methods... Bye, bearophile From bjourne at gmail.com Wed Jan 17 04:03:46 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 17 Jan 2007 10:03:46 +0100 Subject: Conflicting needs for __init__ method In-Reply-To: <873b6abp12.fsf@benfinney.id.au> References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <740c3aec0701160837r33340866w5ddef3e09a0de537@mail.gmail.com> <873b6abp12.fsf@benfinney.id.au> Message-ID: <740c3aec0701170103k29c17df9xdb8c32a3a878ac00@mail.gmail.com> On 1/16/07, Ben Finney wrote: > "BJ?rn Lindqvist" writes: > > > import rational > > rational.rational(45) > > rational.rational(45.0) > > rational.rational([45, 45.5]) > > > > def rational(obj): > > initers = [(int, from_int), (basestring, from_str), (list, from_list)] > > for obj_type, initer in initers: > > if isinstance(obj, obj_type): > > return initer(obj) > > raise ValueError("Can not create a rational from a %r" % type(obj).__name__) > > You've just broken polymorphism. I can't use your factory function > with an instance of my custom type that behaves like a list, but is > not derived from list (or a non-'int' int, or a non-'basestring' > string). Indeed, but I do not think that is fatal. There are many functions in Pythons stdlib that breaks duck typing exactly like that. > Use the supplied value as you expect to be able to use it, and catch > the exception (somewhere) if it doesn't work. That will allow *any* > type that exhibits the correct behaviour, without needlessly > restricting it to a particular inheritance. Can you show an example of that? It seems like that approach would lead to some very convoluted code. -- mvh Bj?rn From jmfbahciv at aol.com Wed Jan 10 09:28:33 2007 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 10 Jan 07 14:28:33 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: In article , "Elan Magavi" wrote: > > wrote in message >news:1168354695.334946.157400 at 51g2000cwl.googlegroups.com... >> Hello all, >> >> I represent Octabox, an Internet Start-up developing a wide-scale >> platform for Internet services. We are very interested to know your >> thoughts on Internet productivity and how it might be improved, and to >> that end we have set up a short survey at our website - >> http://www.octabox.com/productivity_poll.php >> We would very much appreciate if you would take a couple of minutes to >> fill it up and influence our direction and empahsis. >> >> Thanks in advance, >> Octabox Development Team > >Is that like.. OctaPussy? I didn't read their stuff. Are they really trying to put a round peg in a square hole? /BAH From eXt at sidvind.com Thu Jan 11 10:59:45 2007 From: eXt at sidvind.com (eXt) Date: 11 Jan 2007 07:59:45 -0800 Subject: Problem with byte-compiled code Message-ID: <1168531185.036979.43890@o58g2000hsb.googlegroups.com> Hi, I have built some modules in C++to extend python. At first everything worked but then I began splitting my python code into several modules. The application begins in main.py and then imports my other modules. The first time I run the application it works, but when python imports the byte compiled module all I get is a blank window. Moving back all the code into the same source file works. I have found that removing a call to a C++ function solves the problem. However that function is needed and I found that if I print anything inside that function it works. It isn't time related since I tried to sleep instead but that didn't work either. I'm not sure if this is the correct list but I hope someone can help me a bit. The C++ function: TaskScheduler& createTaskScheduler(int threadCnt, const char* logfile){ //print("createTaskScheduler"); TaskScheduler::initialize(threadCnt,logfile); return TaskScheduler::singleton(); } Boost exporting: def("createTaskScheduler", createTaskScheduler, return_value_policy()); Python code: ts = Core.createTaskScheduler(1,'') From danielkleinad at gmail.com Tue Jan 30 14:50:30 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Tue, 30 Jan 2007 19:50:30 GMT Subject: MoinMoin Message-ID: <3b8vr2tj0nc2hra616pm96m2turqm0v0vg@4ax.com> Is it fair game to ask questions about MoinMoin here? If not, can someone recommend a resource please? Dan From ian at excess.org Wed Jan 3 23:13:22 2007 From: ian at excess.org (Ian Ward) Date: Wed, 03 Jan 2007 23:13:22 -0500 Subject: ANN: Urwid 0.9.7.2 - Console UI Library Message-ID: <459C7EE2.7060506@excess.org> Announcing Urwid 0.9.7.2 ------------------------ Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.7.2.tar.gz About this release: =================== This maintenance release significantly improves the performance of Urwid when run in UTF-8 mode. A UTF-8 input handling bug was also fixed. New in this release: ==================== * Improved performance in UTF-8 mode when ASCII text is used. * Fixed a UTF-8 input bug. * Added a clear() function to the the display modules to force the screen to be repainted on the next draw_screen() call. About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From sschwarzer at sschwarzer.net Tue Jan 2 07:25:03 2007 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Tue, 02 Jan 2007 13:25:03 +0100 Subject: simple ftputil ssl client In-Reply-To: <1167589633.246117.130710@42g2000cwt.googlegroups.com> References: <1167589633.246117.130710@42g2000cwt.googlegroups.com> Message-ID: <459A4F1F.8000208@sschwarzer.net> On 2006-12-31 19:27, Croteam wrote: > I trying to make ftputil client that uses ssl security.First I was try > to make that with M2Crypto,but > when I use it, I get the error: > > Traceback (most recent call last): > File "", line 1, in -toplevel- > import M2Crypto > File "C:\Python24\lib\site-packages\M2Crypto\__init__.py", line 15, > in -toplevel- > import m2 > File "C:\Python24\Lib\site-packages\M2Crypto\m2.py", line 28, in > -toplevel- > from __m2crypto import * > ImportError: DLL load failed with error code 182 It seems this problem has nothing to do with ftputil, so it might be best to post the question on the failed import alone with a subject like ImportError for M2Crypto: "DLL load failed with error code 182" or even, since a Google search implies the problem doesn't occur only for M2Crypto, ImportError: "DLL load failed with error code 182" With the current subject, people may think "I don't know ftputil" and don't read your posting at all. You might ask the question with the above subject on the Python-Crypto mailing list which seems to be the best place for M2Crypto-related questions. You should tell the version of M2Crypto and the operating system you use. By the way, have you tried other M2Crypto versions? Can you import the module when the current directory is the one containing the DLL? To check, change to the directory and start the interactive Python interpreter. (If you use an IDE or something similar, as your traceback suggests, that program might change the directory before the import statement runs.) Additionally, you can try to modify sys.path to contain the path of the DLL before invoking the import statement. See also my response on the ftputil mailing list. > ...so now I trying to make it with pyOpenSSL or twistedmatrix ssl,but I > don't know how.If anybody > have any idea or example how to I make it,please help me!!! Now the part specific to ftputil ;-) ... If you can't use M2Crypto, try to make sure that you have a class which is compatible with ftplib.FTP. You can pass such a class as session_factory to ftputil.FTPHost's constructor. If you don't have such a class, you might be able to write it yourself. Stefan -- Dr.-Ing. Stefan Schwarzer SSchwarzer.com - Softwareentwicklung f??r Technik und Wissenschaft http://sschwarzer.com http://www.sschwarzer.net From bdesth.quelquechose at free.quelquepart.fr Wed Jan 31 15:43:43 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 31 Jan 2007 21:43:43 +0100 Subject: Sorting a List of Lists In-Reply-To: <1170266993.041224.75990@a34g2000cwb.googlegroups.com> References: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> <45c08cd3$0$22805$426a74cc@news.free.fr> <1170266993.041224.75990@a34g2000cwb.googlegroups.com> Message-ID: <45c0f88e$0$4321$426a74cc@news.free.fr> Paddy a ?crit : > On Jan 31, 12:35 pm, Bruno Desthuilliers >Also, using comparison functions is usually not the most efficient way >>to do such a sort. In your case, I'd go for a good old >>Decorate/sort/undecorate (AKA schwarzian transform): >> >>events = [evt for date, evt in >> sorted([(evt[2], evt) for evt in events])] >> >>HTH > > > I agree with you B., but see the comments here: > http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting- > efficiency > for information on the relative speeds of rolling your own DSU versus > using itemgetter and key=... Yeps, looks like 2.5 got a real speedup wrt/ itemgetter. Nice to know, and thanks for the link (BTW, this profileit() decorator looks pretty nice too !-) From sergey at fidoman.ru Thu Jan 25 05:55:27 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Thu, 25 Jan 2007 13:55:27 +0300 Subject: module email References: <874pqgf7hb.fsf@smsnet.pl> Message-ID: "Rob Wolfe" wrote in message news:874pqgf7hb.fsf at smsnet.pl... >> p2=email.message.Message() >> p2.set_type("message/rfc822") >> p2.set_payload(m) > > Payload is a _list_ of Message objects (is_multipart() == True) > or a _string_ object (is_multipart() == False) but never just Message > object. 1. If I give m.as_string() into set_payload, result is the same. 2. I don't understand, how message/rfc822 section can accept a list of two or more messages. Can you explain? From wolf_tracks at invalid.com Sun Jan 21 19:33:12 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 22 Jan 2007 00:33:12 GMT Subject: Python Windows Editors In-Reply-To: <1169415514.562496.248950@a75g2000cwd.googlegroups.com> References: <1169415514.562496.248950@a75g2000cwd.googlegroups.com> Message-ID: mensanator at aol.com wrote: > W. Watson wrote: >> I downloaded python-2.5.msi and installed it. I believe its editor is IDE. I >> understand there's a Win editor called pythonwin. I believe it's in the >> download pywin32-210.win32-py2.5.exe, but I'm not sure if this exe file has >> just the editor or all of Python. Comments? If not how do I get the >> PythonWin editor by itself? >> >> BTW, one of the features I did not like of IDE is the limited file Print >> command. It puts everything in 16pt type, and gives no choice over what >> pages should be printed. Maybe there's an option? > > Print your files from Notepad, after all, they're just text files. > But IDLE has more usefull Formatting options. Thanks. Already did it, but used Word. I can get line numbers in that way. From paddy3118 at netscape.net Wed Jan 31 23:46:10 2007 From: paddy3118 at netscape.net (Paddy) Date: 31 Jan 2007 20:46:10 -0800 Subject: how to "free" an object/var ? In-Reply-To: References: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> <1170264406.588032.116550@s48g2000cws.googlegroups.com> Message-ID: <1170305170.533198.215020@l53g2000cwa.googlegroups.com> On Feb 1, 1:45 am, Steven D'Aprano wrote: > On Wed, 31 Jan 2007 09:26:46 -0800, Paddy wrote: > > On Jan 31, 7:34 am, Steven D'Aprano > > wrote: > > [snip] > > >> -- > >> Steven D'Aprano > > > Thanks Stephen for explaining my answer a bit more. > > Ste_ph_en??? > > I know the ph-form of the name is marginally more popular, but dammit my > name is right there just two lines above where Paddy started typing, how > hard is it to get it right? > > It's not like I spell my name with four M's and a silent Q like the famous > author Farles Wickens *wink* > > -- > Steven D'Aprano > who thinks there can never be too many Monty Python references Please accept my most humblest of apologies Steven D'Aprano. I can only think I had a brain seizure between reading, and writing your name, Come to think of it... The Stephen/Steven confusion should only apply when you *hear* the name said? Now I don't read aloud newsgroups to myself; but I do (still), have a head cold. Maybe I should lie down and rest.... - Paddy. From timr at probo.com Mon Jan 1 02:29:05 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 01 Jan 2007 07:29:05 GMT Subject: A question about unicode() function References: <1167571210.084436.311610@48g2000cwx.googlegroups.com> Message-ID: <8udhp21q3jvsdgfqt0a79uab2rrdpffqe7@4ax.com> "JTree" wrote: > >Hi,all > I encountered a problem when using unicode() function to fetch a >webpage, I don't know why this happenned. > My codes and error messages are: > > >Code: >#!/usr/bin/python >#Filename: test.py >#Modified: 2006-12-31 > >import cPickle as p >import urllib >import htmllib >import re >import sys > >def funUrlFetch(url): > lambda url:urllib.urlopen(url).read() > >objUrl = raw_input('Enter the Url:') >content = funUrlFetch(objUrl) >content = unicode(content,"gbk") >print content >content.close() Once you fix the lambda, as Felipe described, there's another issue here. You are telling the unicode function that the string you're passing it is an 8-bit string encoded as gbk. How do you know that? In your specific example, www.msn.com, I can guarantee it will produce the wrong results: www.msn.com is encoded in UTF-8. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py at yahoo.com.ar Wed Jan 10 23:46:34 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 01:46:34 -0300 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168458486.538863.316130@k58g2000hse.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> Message-ID: <7.0.1.0.0.20070111014007.03f76798@yahoo.com.ar> At Wednesday 10/1/2007 16:48, oyekomova wrote: >Thanks for your help. I compared the following code in NumPy with the >csvread in Matlab for a very large csv file. Matlab read the file in >577 seconds. On the other hand, this code below kept running for over 2 >hours. Can this program be made more efficient? FYI - The csv file was >a simple 6 column file with a header row and more than a million >records. > > >import csv >from numpy import array >import time >t1=time.clock() >file_to_read = file('somename.csv','r') >read_from = csv.reader(file_to_read) >read_from.next() > >datalist = [ map(float, row[:]) for row in read_from ] > ># now the real data >data = array(datalist, dtype = float) > >elapsed=time.clock()-t1 >print elapsed Replace that row[:] by row, it's just a waste of time and memory. And see http://www.scipy.org/Cookbook/InputOutput -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jhefferon at smcvt.edu Wed Jan 31 07:57:18 2007 From: jhefferon at smcvt.edu (Jim) Date: 31 Jan 2007 04:57:18 -0800 Subject: error messages containing unicode In-Reply-To: References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> <1170160464.576122.62230@h3g2000cwc.googlegroups.com> Message-ID: <1170248238.032665.207180@m58g2000cwm.googlegroups.com> Thanks Steve, I appreciate your patience. On Jan 31, 1:39 am, Steven D'Aprano wrote: > If the built-in isn't Unicode aware, subclassing it won't magically make > it so :-) Oh, I agree. If I have a string mesg that is unicode-not-ascii and I say try: raise Exception mesg except Exception, err: print "Trouble"+mesg then I have problems. I however am under the impression, perhaps mistaken, that the built-in exceptions in the library will return as error strings only ascii. (I take as evidence of my understanding that the built-in exceptions have a __str__() method but do not have an explicit __unicode__() and so rely on a unicode(err) call being passed on to __str__(). But as I've said above, I've been wrong so many times before. ;-) My main point about the built-ins is that I want to catch them along with my own exceptions. That's what I meant by the next paragraph. My class myException is a subclass of Exception so I can catch my stuff and the standard stuff with an all-in-one panic button. > > > For instance, I write a lot of CGI and I want to wrap everything in a > > try .. except. > > try: > > main() > > except Exception, err: > > print "Terrible blunder: ",str(err) > > so that the err can be one of my exceptions, or can be one that came > > with Python. > > (And, that I can see, err.args can be either the relevant > > string or a tuple containing the relevant string and the documentation > > is silent on whether in the built-in exceptions if err.args is a tuple > > then the string is guaranteed to be first in the tuple.) > > Does it matter? Just print the tuple. In truth, it does matter. In that example, for instance, some error message is passed on to the user and I don't want it to be too bad. "Database cannot be opened" is better than a "(u'Database cannot be opened,1)"-type thing. Besides which, Python is a nice language, and I'm certain there is a nice way to do this; it is just that I'm having trouble making it out. > >> (2) convert the file name to ASCII before you store it; or > > > I need the non-ascii information, though, which is why I included it > > in the error message. > > If you have the exception captured in "err", then you can grab it with > err.where_i_put_the_unicode. I want a method of grabbing it that is the same as the method used by the built-ins, for the uniformity reasons that I gave above. That I could make out, the documentation was silent on what is the approved way to grab the string. > >> (3) add a __str__ method to your exception that is Unicode aware. > > > I have two difficulties with this: (1) as above I often raise Python's > > built-in exceptions and for those __str__() is what it is, and > > Then don't use the built-in exception. If it won't do what you want it do > do, use something else. I use my exceptions for errors in my logic, etc. But not being perfect, sometimes I raise exceptions that I had not anticipated; these are built-ins. > > (2) this > > goes against the meaning of __str__() that I find in the documentation > > in ref/customization.html which says that the return value must be a > > string object. > > I didn't mean return a unicode object :) > > You're absolutely correct. Your __str__ would need to return a string > object, which means encoding the Unicode correctly to get a string object > without raising an exception. > > e.g. something like this maybe (untested, not thought-through, probably > won't work correctly, blah blah blah): > > def __str__(self): > s = self.args.encode('ascii', 'replace') > return "Unicode error converted to plain ASCII:\n" + s > > or whatever encoding scheme works for your application. I did discuss this suggestion from another person above. That would mean either (a) throwing away the unicode-not-ascii parts of the error message (but I want those parts, which is why I put them in there) or (b) hard-coding the output encoding for error strings in hundreds of error cases (yes, I have hundreds) or (c) passing as a parameter the errorEncoding to each function that I write. That last case doesn't seem to be to be a likely best practice for such a nice language as Python; I want a way to get the unicode object and go forward in the program with that. > It can take whatever you want it to take: > > class MyStupidException(Exception): > def __init__(self, dayofweek, breakfast="spam and baked beans", > *everythingelse): > self.day = dayofweek > self.breakfast = breakfast > self.args = everythingelse > def __str__(self): > s = "On %s I ate %s and then an error '%s' occurred." % \ > (self.day.title(), self.breakfast, self.args) > return s > > >>> raise MyStupidException('monday', 'cheese', 'bad things', 'happened', 2) > > Traceback (most recent call last): > File "", line 1, in ? > __main__.MyStupidException: On Monday I ate cheese and then an error > '('bad things', 'happened', 2)' occurred. Thank you for the example; I learned something from it. But as I mentioned above, I need to guard against the system raising built-ins also and so I am still a bit puzzled by how to get at the error strings in built-ins. In case anyone is still reading this :-) someone else suggested the err.message attribute. I had missed that in the documentation somehow, but on rereading it, I thought he had solved my problem. However, sadly, I cannot get Python to like a call to err.message: .......................................................... $ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> try: ... raise Exception, 'this is the error message' ... except Exception, err: ... print "result: ",err.message ... result: Traceback (most recent call last): File "", line 4, in ? AttributeError: Exception instance has no attribute 'message' >>> ...................................................................................... So, in case it helps anyone, I am going with this: ..................................................................................... def errorValue(err): """Return the string error message from an exception message string. err exception instance Note: I cannot get err.message to work. I sent a note to clp on Jan 29 2007 with a related query and this is the best that I figured out. """ return err[0] class jhError(StandardError): """Subclass this to get exceptions that behave correctly when you do this. try: raise subclassOfJhError, 'some error message with unicode chars' except subclassOfJhError, err mesg='the message is '+unicode(err) """ def __unicode__(self): return errorValue(self) class myException(jhError): pass .................................................................................... No doubt I'll discover what is wrong with it today. :-) Jim From martin at v.loewis.de Thu Jan 4 03:33:17 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Jan 2007 09:33:17 +0100 Subject: minidom utf-8 encoding In-Reply-To: <1167868380.481121.154880@42g2000cwt.googlegroups.com> References: <1167868380.481121.154880@42g2000cwt.googlegroups.com> Message-ID: <459cbbce$0$15834$9b622d9e@news.freenet.de> fscked schrieb: > Hi guys/gals. > > I am trying to write and xml file from data parsed from a csv. > > I can get everything to work except that I cannot get minidom to do --> > ? which needless to say is driving me nuts. > > Any suggestions? Works fine for me: py> d = minidom.Document() py> r = d.createElement("root") py> r.appendChild(d.createTextNode(u"\xf6")) py> d.appendChild(r) py> d.toxml() u'\n\xf6' py> print d.toxml() ? Regards, Martin From ruan at jcmills.com Thu Jan 18 19:31:20 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Thu, 18 Jan 2007 19:31:20 -0500 Subject: How to pass arguments to the function embedded in the timeit.Timer() Message-ID: Hi Does anybody know how to pass multiple arguments to the function tested in timeit.timer() in python? I googled and found how to pass one argument: x=10000 mytime = timeit.Timer( setup="from Createlst import createlst", stmt= "createlst(%s)"%(x) ) But how can I extend it to two or more arguments? Like this: p1=createlst.createlst(10000) p2=createlst.createlst(10000) mytime = timeit.Timer(setup="from list_concat_copy import list_concat_copy", stmt="list_concat_copy.list_concat_copy(%x,%y)"%p1,p2 ) I don't know how to end the timeit.Timer. Should it be (%x,%y)"%p1,p2 or (%x,%y)"%p1,%p2 or (%x,%y)"(%p1%p2) . I tried and none worked. I just got error message like global variable "A' not defined. Can anybody help? Thanks! From gert.cuykens at gmail.com Fri Jan 5 23:34:54 2007 From: gert.cuykens at gmail.com (gert) Date: 5 Jan 2007 20:34:54 -0800 Subject: attribute decorators Message-ID: <1168058094.179442.173650@s34g2000cwa.googlegroups.com> Would it not be nice if you could assign decorators to attributes too ? for example class C: @staticattribute data='hello' or class C: @privateattribute data='hello' From consmash at gmail.com Wed Jan 24 12:57:09 2007 From: consmash at gmail.com (consmash at gmail.com) Date: 24 Jan 2007 09:57:09 -0800 Subject: Noob Question: Force input to be int? In-Reply-To: <1169546377.017596.43840@k78g2000cwa.googlegroups.com> References: <1169546377.017596.43840@k78g2000cwa.googlegroups.com> Message-ID: <1169661429.273191.14010@v45g2000cwv.googlegroups.com> On 23 Sty, 10:59, wd.jons... at gmail.com wrote: > Hello everyone! > I have a piece of code that looks like this: > > if len(BuildList) > 0: > print "The script found %d game directories:" % len(BuildList) > print > num = 0 > for i in BuildList: > print str(num) +" " + i > num = num + 1 > print > print "Select a build number from 0 to " + str(len(BuildList) - 1) > buildNum = int(raw_input('Select build #> ')) > > while buildNum > (len(BuildList) -1) or buildNum <= -1: > print > print "Error: Invalid build number!" > print "Select a build number from 0 to " + str(len(BuildList) - > 1) > print > buildNum = int(raw_input('Select build: ')) > > The problem is with the while buildNum-loop. If the user enters a > non-numeric value in the buildNum input, the scripts throws an > exception. I need to constrict the user to ONLY use integers in the > input box. How can I solve this issue? Also if you would like to try mentioned approach 'Look before you leap', this code should be quite clear: buildNumber = ('foo', 'bar') n = len(buildNumber) loop = True while loop: input = raw_input('select a build number from 0 to %d: ' % (n-1)) if input.isdigit(): ch = int(input) loop = not ch in range(n) # if ch is NOT in range of [0, n), then it is ok to loop if loop: print 'Error! Invalid build number' print 'Choice: %d' % ch In fact I don't know if it applies to python, but in conventional languages it is a bad habit to use exceptions for every simple test as it takes time to jump around code. So, correct me please. From weekender_ny at yahoo.com Mon Jan 22 01:03:53 2007 From: weekender_ny at yahoo.com (John) Date: 21 Jan 2007 22:03:53 -0800 Subject: html + javascript automations = [mechanize + ?? ] or somethingelse? In-Reply-To: References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> <1169441279.556814.16770@38g2000cwa.googlegroups.com> Message-ID: <1169445833.722792.53680@a75g2000cwd.googlegroups.com> I tried it, didnt work with the python25 distribution msi file that is on python.org But activestate python worked. Now I can open IE using COM. What I am trying to figure out is how to click an x,y coordinate on a page in IE automatically using COM. How about typing something automatically...Any ideas? Thanks, --j Gabriel Genellina wrote: > "John" escribi? en el mensaje > news:1169441279.556814.16770 at 38g2000cwa.googlegroups.com... > > > My python2.5 installation on windows did not come with "win32com". > > How do I install/get this module for windows? > > Look for the pywin32 package at sourceforge.net > > -- > Gabriel Genellina From evan at binarymanipulations.com Tue Jan 2 02:14:38 2007 From: evan at binarymanipulations.com (Evan Carmi) Date: Tue, 2 Jan 2007 07:14:38 +0000 (UTC) Subject: how to move files based on file-ending from dirs and subdirs to specific dir? Message-ID: hey, i am trying to move files with a specific file-ending (.msf) to dir above their current location. my code so far works as long as all the files are on the same dir level. but how can i make it work if there are multiple subdirs with files inside of them on different dir levels? my code so far is: --- top = 'f:\\test\\mail' import os, time, itertools #walk and find all files allfiles = [] for root, dirs, files in os.walk(top, topdown=False): for name in files: allfiles.append(os.path.join(root, name)) #remove all non .msf files index = [] for match in allfiles: if match.endswith('.msf'): index.append(match) indexdest = [] indexdest = ['%s\\..\\..\\%s\\%s\\%s' % (x , time.strftime('%Y%m%d%H%M%S'), os.path.basename(os.path.normpath(x+'\\..')), os.path.basename(x)) for x in ind ex] #\\.. to remove the ending and than basename to add it back on indexdest = [os.path.normpath(i) for i in indexdest] indexdest = [i.replace('Mail', 'backups-msf') for i in indexdest] for a, b in itertools.izip(index, indexdest): os.renames(a, b) -- i want the .msf files to be in a dir on the same level as where the top string points to (in this case f:\test\backups-msf). thanks, Evan p.s. is there a more accurate word for a directory level or something on the same "tier" of a directory? From ggrp1.20.martineau at dfgh.net Fri Jan 5 19:10:15 2007 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 5 Jan 2007 16:10:15 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: <1168042215.514023.121560@s80g2000cwa.googlegroups.com> Stef Mientki wrote: > Not sure I wrote the subject line correct, > but the examples might explain if not clear > > > *** first attempt *** > class pin: > def __init__ (self): > self.Name = 'Unknown Pin' > > aap = pin() # create an instance > aap.Name = 'aap' # set it's name > print aap.Name # print it's name > # but why should I set it's name ?? > print 'aap' # I can just as well print a constant string !! > # (ok there will be an extra check) While I agree that it's likely you're confusing Python objects and names, Python *is* an interpreted language and therefore very flexible. Here's a snippet showing one way to remove the 'redundancy'. (Be forewarned that doing things like this is highly distasteful to some people.) ### non-redundant example ### import sys class Pin: def __init__(self, name, namespace=None): self.name = name if namespace == None: # default to caller's globals namespace = sys._getframe(1).f_globals namespace[name] = self Pin('aap') # create a Pin object named 'aap' Pin('aap2') # create a Pin object named 'aap2' print aap.name print aap2.name -Martin From michael at mustun.ch Tue Jan 2 13:42:44 2007 From: michael at mustun.ch (mm) Date: Tue, 02 Jan 2007 19:42:44 +0100 Subject: array of class Message-ID: <459AA7A4.40901@mustun.ch> How can I do a array of class? s1=[] ## this array should hold classes ## class definition class Word: word="" ## empty words... INIT for i in range(100): ## 0..99 s1.append(Wort) s1[0].word="There" s1[1].word="should" s1[2].word="be" s1[3].word="different" s1[4].word="classes" ... but it's not. print s1 ------------ [, , , , , , ........ ----------- Here, this "classes" are all at the same position in memory. So there are no different classes in the array. So I access with s1[0], s1[1], s1[2], etc. always the same data. Any idea? -- Michael From gagsl-py at yahoo.com.ar Thu Jan 18 09:29:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 11:29:36 -0300 Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> Message-ID: "Cecil Westerhof" escribi? en el mensaje news:45af6f47$0$322$e4fe514c at news.xs4all.nl... >I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I > can not time the time used to import time, but os and sys do not take more > as a millisecond. My script itself takes 3 or 4 milliseconds. But > importing > cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is > there a way to make this more fast? The import off cgi makes the script at > least 20 times as slow. Something like mod-python is not a possibility. I > could use it on my test machine, but not at the osting provider. Surely os was imported earlier, and was already loaded. sys is a builtin module. But I think your problem is not how much time takes importing cgi, but how much time takes launching a new python process on each request. -- Gabriel Genellina From chrisspen at gmail.com Fri Jan 12 19:54:11 2007 From: chrisspen at gmail.com (Chris) Date: 12 Jan 2007 16:54:11 -0800 Subject: AlphaBeta Search Message-ID: <1168649650.163717.263240@38g2000cwa.googlegroups.com> I know this probably seems trivial, but I can't seem to find the bug in my alphabeta search implementation. I'm testing it with the game of tic-tac-toe. If the first player plays in a corner, the correct move is to play in the center, but for some reason my code thinks the center and remaining corner positions are all equally good moves. I adopted my code almost exactly from the pseudo-code posted in the wikipedia article (http://en.wikipedia.org/wiki/Alpha-beta_pruning). Can anyone point out if I'm doing anything clearly wrong, or if the pseudo-code isn't correct? Any help is appreciated. infinity = 1e99999999 def alphaBeta(root, maxDepth=10): """Search game to determine best action; use alpha-beta pruning.""" player = root.turn def is_terminal(node, depth): '''The default test cuts off at depth d or at a terminal state.''' return depth > maxDepth or node.isGameOver() def heuristic_value(node): '''Returns heuristic value of game relative to the turn in the root game.''' player1Score,player2Score = node.getScore() if node.turn == player: score = player1Score-player2Score else: score = player2Score-player1Score return score def search(node, alpha, beta, depth): if is_terminal(node, depth): return heuristic_value(node) for nextNode in node.getNextNodes(): v = alpha = max(alpha, -search(nextNode, -beta, -alpha, depth+1)) if alpha >= beta: break return v # Evaluate all choices. choices = map(lambda node: (search(node, -infinity, infinity, 0), node.actionHistory[-1]), root.getNextNodes()) # Chose best action. score,action = max(choices) return action From usenet200701 at tobyinkster.co.uk Wed Jan 31 04:17:40 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Wed, 31 Jan 2007 09:17:40 +0000 Subject: Web File System References: <1170059509.601069.153290@q2g2000cwa.googlegroups.com> Message-ID: anthony.cutrone wrote: > Files and folders have to be in an SQL database, mounted in ext3-like > system. File would be identified by a single ID, and links with names > should be connected on these IDs. Take a look at FUSE. Also, have you considered subversion? -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From http Wed Jan 17 17:21:29 2007 From: http (Paul Rubin) Date: 17 Jan 2007 14:21:29 -0800 Subject: Would a Dutch speaker please check this wiki page please? References: Message-ID: <7xwt3l47me.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > http://wiki.python.org/moin/Selcuk_Altun > > I suspect it's junk since it doesn't seem to mention Python and the website > it mentions doesn't seem to exist. Still, just in case... I'm not a dutch speaker but treating it as garbled german-english "captcha", I think it says: Welcome to the site www.keriwar.nl. The site is online and if you have questions, first read the FAQ. Googling "keriwar" finds http://www.webscripters.be/leden/profiel.php?member=keriwar Anyway I think you can junk the page. From sturlamolden at yahoo.no Tue Jan 16 23:58:02 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 16 Jan 2007 20:58:02 -0800 Subject: How can I create a linked list in Python? In-Reply-To: <45ad5104$0$393$426a74cc@news.free.fr> References: <45ad5104$0$393$426a74cc@news.free.fr> Message-ID: <1169009882.408482.43360@q2g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > Implementing linked lists in Python is not a great deal - it just > doesn't make much sens. It does make sence, as there are memory constraints related to it. Python lists are arrays under the hood. This is deliberately. Dynamic arrays grows faster than lists for the common "short list" case, and because indexing an array is O(1) instead of O(N) as it is for linked lists. You can easily break the performance of Python lists by adding objects in the middle of a list or appending objects to the end of long lists. At some point the list can not grow larger by a simple realloc, as it would crash with other objects on the heap, and the whole list must be replaced by a brand new memory segment. Also linked lists are an interesting theoretical concept in computer science. Understanding how dynamic datastructures work and their limitations are a key to understanding algorithms and how computers work in general. The simplest way of implementing a linked list in Python is nesting Python lists. One may e.g. type something like: #create mylist = [] # push mylist = [someobject, mylist] # pop mylist = mylist[1] #iterate cur = mylist while cur: cur = cur[1] This is actually single linked list that behaves like a stack, i.e. the last added element sits on top and one needs to iterate the list to get to the first. Those who know Lisp should be familiar with the concept of creating dynamic data structures form nesting lists; it may be more unfamiliar to C and Pascal programmers, as these languages do not support such constructs. In Python one may also use a more explicit solution involving classes for expressing linked lists, which would be more familiar to C and Pascal programmers. In any case, making linked lists are trivial in Python. From larry.bates at websafe.com Mon Jan 15 19:33:13 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 15 Jan 2007 18:33:13 -0600 Subject: Watch log In-Reply-To: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> References: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> Message-ID: Salvatore Di Fazio wrote: > Hi guys, > I've an application that writes a log file. > I need to write an application with python that will read this file. > > I would like wait until a new line will be write in the file. > > Something like the "watch cat Log" command on Linux os. > > How can I check the eof and restart the reading? > You didn't provide much info so here goes. If you use the logger module built into Python you can set up a logger that uses sockets. Have your program log to a socket and have the other program read from the socket. That way you will always have the latest log entries in the monitor program. If you can't control the program that writes the log file, have your monitoring program look for change in the length of the logfile (you can use the os.stat module for this). When it changes, open the file, seek to the old length and read bytes up to the new length and close the logfile. What is read will be the new log entry (or entries). Reset the logfile length high water mark and loop. Hope information helps. -Larry Bates From subscriber100 at rjs.org Fri Jan 12 11:03:29 2007 From: subscriber100 at rjs.org (Ray Schumacher) Date: Fri, 12 Jan 2007 08:03:29 -0800 Subject: threads - was:Is there a way to protect a piece of critical code? Message-ID: <6.2.3.4.2.20070112073246.02e7e950@pop-server.san.rr.com> "Hendrik van Rooyen" wrote: > Similarly discrete background thread jobs can be used > in a functional style this way: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491280 > ( an alternative for the laborious OO-centric threading. With the various options available, many of which I haven't used (CallQueue for example), I am wondering what the "best" methodology to use is for a 2-task example on a dual core processor for my next project: -One task is an ADC data collection/device driver whose sole job in life is to fill a numpy "circular buffer" with data from an external ADC device at high speed and expose a pointer - programmatically complex but functionally distinct from the analysis task. It is I/O bound and spends time waiting on the ADC. -The main task is analysis of that data in near-real time with FFT, correlations etc, and computationally bound. It needs to have read access to the array and a pointer, and kill the ADC task when desired. Thoughts/opinions are humbly requested, Ray From mail at microcorp.co.za Fri Jan 19 03:57:23 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 19 Jan 2007 10:57:23 +0200 Subject: Would a Dutch speaker please check this wiki page please? References: <45af4735$0$322$e4fe514c@news.xs4all.nl> Message-ID: <010101c73bd4$750de960$03000080@hendrik> "Martin P. Hellwig" wrote: > Stef Mientki wrote: > > skip at pobox.com wrote: > >> Got a note about a new page on the Python Wiki: > >> > >>>>>>> "Wade" == Wade McDaniel writes: > >> > >> http://wiki.python.org/moin/Selcuk_Altun > >> > >> I suspect it's junk since it doesn't seem to mention Python and the > >> website > >> it mentions doesn't seem to exist. Still, just in case... > > The only (incorrect) Dutch sentence on the whole site is: > > "Welkom op me site www.keriwar.nl", > > which should have been > > "Welkom op mijn site www.keriwar.nl" > > but that could be explained, while his name "Selcuk Altun" is not > > orginated from the Netherlands. > > I just expect that he is trying to setup a wiki, > > but that's too soon to give it a judgement. > > > > cheers, > > Stef Mientki > >> > >> Thx, > >> > >> Skip > > Could be Afrikaans too, but the page is gone now so I can't check. No its not Afrikaans - the "me" would have had to be "my" and "site" would have been "webwerf" - literally "web yard"... Some Flemish dialect, perhaps? - Hendrik From bdesth.quelquechose at free.quelquepart.fr Thu Jan 11 15:50:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 11 Jan 2007 21:50:48 +0100 Subject: globals accros modules In-Reply-To: <3137a$45a6851a$d443bb3a$24085@news.speedlinq.nl> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> <45a66cea$0$289$426a34cc@news.free.fr> <3137a$45a6851a$d443bb3a$24085@news.speedlinq.nl> Message-ID: <45a69cca$0$321$426a74cc@news.free.fr> Stef Mientki a ?crit : > Bruno Desthuilliers wrote: > >> stef a ?crit : (snip) >>> You can explain your collegaes, that >>> - the startindex of arrays changes from 1 to 0 >>> - slices are upto, instead of including the final border >>> - indention is th? key >>> And tell them about all beautiful things in Python, >>> but tell them that they are going to loose all their globals ??? >> >> >> It's a feature. Globals are definitively a BadThing(tm). > > > yes, I know, but my audience will accept that only in the long term. Unless you clearly explain the benefits... Any code relying on the existence of a global is: 1/ dependent on the existence of this global 2/ harder to understand FWIW, I'm currently fixing a simple Delphi program that's using quite a few globals, and since I'm not familiar with ObjectPascal (my experience with Pascal boils down to a few cs101 stuff like implementing a linked list, some 6 or 7 years ago), I'm losing a lost of time with these [bip] globals... > But maybe this idea works: > > > global var1 > global var2 > The 'global' statement only makes sens within a function, and it's only a declaration, not a definition (-> it won't bind the following name by itself - only tell the interpreter that this name is to be considered as belonging to the module's namesepace ). The minimal working example requires that you assign a default value: # myglobs.py meaning_of_life = 42 # another.py import myglobs print myglobs.meaning_of_life > > > import Ugly_MatLab_Globals > > def some_function(): > import Ugly_MatLab_Globals You don't have to reimport it here... > > (btw who owns the BadThing tm ;-) I Do(tm) !-) From bj_666 at gmx.net Sun Jan 7 05:30:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 07 Jan 2007 11:30:54 +0100 Subject: AES256 in PyCrypto References: <1168134542.337448.261510@s34g2000cwa.googlegroups.com> Message-ID: In <1168134542.337448.261510 at s34g2000cwa.googlegroups.com>, mirandacascade wrote: > Would the following Python code perform AES256 encryption on plainText > from Crypto.Cipher import AES > x = AES.new(a, AES.MODE_CBC, iv) > x.encrypt(plainText) > > assuming: > a = the key value > iv = an initialization vector > ? `a` must be of length 32 for AES256. And the length of `plainText` must be a multiple of 16 because it's a block cypher algorithm. Ciao, Marc 'BlackJack' Rintsch From wleftwich at gmail.com Thu Jan 4 08:48:05 2007 From: wleftwich at gmail.com (Wade Leftwich) Date: 4 Jan 2007 05:48:05 -0800 Subject: Iterate through list two items at a time References: <12pmahqc7kclbfc@corp.supernews.com> <1167882211.696350.271620@s34g2000cwa.googlegroups.com> <1167913980.320964.264860@s34g2000cwa.googlegroups.com> Message-ID: <1167918485.053278.206990@s34g2000cwa.googlegroups.com> Peter Otten wrote: > Wade Leftwich wrote: > > > from itertools import groupby > > > > def chunk(it, n=0): > > if n == 0: > > return iter([it]) > > def groupfun((x,y)): > > return int(x/n) > > grouped = groupby(enumerate(it), groupfun) > > counted = (y for (x,y) in grouped) > > return ((z for (y,z) in x) for x in counted) > > > >>>> [list(x) for x in chunk(range(10), 3)] > > [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] > > > >>>> [x for x in chunk(range(10), 3)] > > [, > > , > > , > > ] > > Note that all but the last of these generators are useless: > > >>> chunks = [x for x in chunk(range(10), 3)] > >>> [list(x) for x in chunks] > [[], [], [], [9]] # did you expect that? > In [48]: chunkgen = chunk(range(10), 3) In [49]: for x in chunkgen: ....: print list(x) ....: ....: [0, 1, 2] [3, 4, 5] [6, 7, 8] [9] > Peter That's an interesting gotcha that I've never run into when using this function, because in practice I never put the generator returned by chunk() inside a list comprehension. In [51]: chunkgen = chunk(range(10), 3) In [52]: [list(x) for x in chunkgen] Out[52]: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] But, as you pointed out -- In [57]: chunkgen = chunk(range(10), 3) In [58]: chunks = list(chunkgen) In [59]: [list(x) for x in chunks] Out[59]: [[], [], [], [9]] So apparently when we list(chunkgen), we are exhausting the generators that are its members. And if we do it again, we get rid of the [9] -- In [60]: [list(x) for x in chunks] Out[60]: [[], [], [], []] I'll admit that chunk() is needlessly tricky for most purposes. I wrote it to accept a really lengthy, possibly unbounded, iterator and write out 10,000-line files from it, and also to play with Python's new functional capabilities. -- Wade From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 11 12:14:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 11 Jan 2007 18:14:52 +0100 Subject: What about this? References: <1168525050.536736.74590@i39g2000hsf.googlegroups.com> Message-ID: <50n9kcF1g30l4U2@mid.individual.net> new wrote: > www.magicoz.com > amazing Yeah, it *is* really amazing that someone dares to spam for such an unprofessional homepage. Even too stupid to include a doctype ... Bj?rn -- BOFH excuse #61: not approved by the FCC From horpner at yahoo.com Thu Jan 18 08:23:57 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 18 Jan 2007 13:23:57 GMT Subject: A note on heapq module References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <45ad0f6c$1@nntp0.pdx.net> <1168982702.903306.152940@m58g2000cwm.googlegroups.com> <1169118077.035345.321580@11g2000cwr.googlegroups.com> Message-ID: On 2007-01-18, bearophileHUGS at lycos.com wrote: > Neil Cerutti: >> One more idea, cribbed from the linked list thread elsewhere: >> it might be nice if your Heap could optionally use an >> underlying collections.deque instead of a list. I don't know >> how excellent Python's deque is, but it's possible a deque >> would provide a faster heap than a contiguous array. C++'s >> std::deque is the default implementation of C++'s >> std::priority_queue for that reason (unless I'm confused >> again). > > If you have some minutes you can do few speed tests and show us > the code and the timing results... I'll see what I can come up with. I'll have to test using the native Python implementation, which should work with deque, rather than the optimized C implementation, which doesn't. Unfortunately the inability to take advantage of the C implementation of heapq might swamp any possible advantage of using deque instead of list in a Heap class. -- Neil Cerutti -- Posted via a free Usenet account from http://www.teranews.com From jwaixs at gmail.com Fri Jan 12 13:52:55 2007 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Fri, 12 Jan 2007 18:52:55 +0000 Subject: Rational Numbers In-Reply-To: References: Message-ID: On 1/12/07, Facundo Batista wrote: > > Noud Aldenhoven wrote: > > > There are a (small) couple of other issues where rational numbers could > be > > handy. That's because rational numbers are exact, irrational numbers (in > > python) aren't. But these issues are probably too mathematical to be > used in > > For the sake of me being less ignorant, could you please point me a > language where irrational numbers are exact? I'm not sure, but I tought MAPLE could do it. This language has been designed for solving mathimatical equotations (and other simulair stuf) and could handle irrational numbers. But ofcourse irrational numbers could never be exact when printed in an g-notation (g > 1) system. But now I mention that sentense is wrong... it should be: "That's because rational numbers are exact, but in python they aren't most of the time." To make irrational numbers exact in python should be, I think, more unefficient than making rational numbers. But they could be very handy too for calculating maths or physics equotations. Regards, Noud -- <:3 )~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent at kentsjohnson.com Tue Jan 2 15:13:56 2007 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 02 Jan 2007 20:13:56 GMT Subject: Some basic newbie questions... In-Reply-To: <1167326253.557372.124110@a3g2000cwd.googlegroups.com> References: <1167324002.516960.319870@79g2000cws.googlegroups.com> <12p7tah6gbtq53d@corp.supernews.com> <1167326253.557372.124110@a3g2000cwd.googlegroups.com> Message-ID: <459ABD03.4030808@kentsjohnson.com> jonathan.beckett wrote: I'm just finding it a bit weird that some of the built in functions are > static, rather than methods of objects (such as len() being used to > find the length of a list). Another explanation here: http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm Kent From fsck_spam at telenet.be Wed Jan 17 14:07:30 2007 From: fsck_spam at telenet.be (Rikishi 42) Date: Wed, 17 Jan 2007 20:07:30 +0100 Subject: Making a simple script standalone References: <5d1084-5j7.ln1@whisper.very.softly> <45AD6442.6050209@websafe.com> Message-ID: On Wednesday 17 January 2007 00:48, Larry Bates wrote: >> There is nothing graphical, nothing fancy about the script. >> The only imports are: os, stat, string and time. >> >> Any suggestions on an - easy and clear - path to follow ? > I use py2exe and inno installer. Works great. Thanks, I will look into it. Hope it's not as heavy as py2exe... -- Research is what I'm doing, when I don't know what I'm doing. (von Braun) From martin at v.loewis.de Wed Jan 3 14:57:53 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 20:57:53 +0100 Subject: Cannot build 2.5 on FC6 x86 In-Reply-To: <502e72F1eh7ngU1@mid.individual.net> References: <502e72F1eh7ngU1@mid.individual.net> Message-ID: <459c0ac1$0$28366$9b622d9e@news.freenet.de> Paul Watson schrieb: > ./configure > make > make test > > The result appears to hang after the test_tkl... line. I had to kill > the 'make test' process which terminated it. Any suggestions? There isn't (or shouldn't be) any "test_tkl..." line. What precisely was the line, and how long did you wait until you thought it hangs? Regards, Martin From paul at boddie.org.uk Mon Jan 15 11:02:10 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 15 Jan 2007 08:02:10 -0800 Subject: check if there is data in stdin without blocking References: <4PMqh.47441$X97.9536@newsfe18.lga> Message-ID: <1168876929.239494.93830@v45g2000cwv.googlegroups.com> hg wrote: > import select [...] > File "/home/philippe/Desktop/select.py", line 4, in ? Consider which module Python is trying to import here: the standard library select module or your own program? Paul From Laurent.LAFFONT-ST at adixen.fr Mon Jan 15 05:52:19 2007 From: Laurent.LAFFONT-ST at adixen.fr (Laurent.LAFFONT-ST at adixen.fr) Date: Mon, 15 Jan 2007 11:52:19 +0100 Subject: Class list of a module Message-ID: > Looks rather simple to me... Anyway, you could avoid calling getattr > twice, if you iterate over vars(aModule).itervalues() > def getClassList(aModule): > return [cls for cls in vars(aModule).itervalues() > if inspect.isclass(cls)] > (And note that there is no need for using \ at the line ends, because > of the []) That's what I've been looking for. Thank you. Regards, Laurent Laffont From nospam at nospam.com Tue Jan 9 23:42:48 2007 From: nospam at nospam.com (Mark T) Date: Tue, 9 Jan 2007 20:42:48 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) References: <2BBAEE949D384D40A2B851287ADB6A4304595A6D@eugsrv400.psc.pscnet.com> Message-ID: <9JednRBqruZ18znYnZ2dnUVZ_sadnZ2d@comcast.com> "Gabriel Genellina" wrote in message news:mailman.2505.1168387540.32031.python-list at python.org... > At Tuesday 9/1/2007 20:31, Carroll, Barry wrote: > >>I've spent about a day investigating our "too many open files" error. I >>found the following: >> >> 1. Windows XP allows a Python 2.5 script to open 509 concurrent >> files. > > And do you actually need so many open files simultaneously? > Try to close them explicitely when you finish working on them - do not > rely on GC for closing files. This has *always* been the recomended > practice (except maybe, inside a short script that finishes quickly). > On Python 2.5 you can use the new `with` statement. > > > -- > Gabriel Genellina > Softlab SRL After a quick scan of this thread, I didn't see the actual source for your call to the file's close(). Is it perhaps "file.close" and not "file.close()"? Forgotten parentheses won't give an error and won't close the file. >>> f=file('blah.txt','wt') >>> f >>> f.close >>> f >>> f.close() >>> f >>> -Mark Tolonen From cfbolz at gmx.de Mon Jan 22 06:05:07 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Mon, 22 Jan 2007 12:05:07 +0100 Subject: Py 2.5 on Language Shootout In-Reply-To: <624934630701211513t3a3e28a5ua7387c9ee2f5790e@mail.gmail.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> <45B23400.2010906@gmx.de> <1169321686.025356.120340@s34g2000cwa.googlegroups.com> <1169331552.918850.282920@a75g2000cwd.googlegroups.com> <624934630701211513t3a3e28a5ua7387c9ee2f5790e@mail.gmail.com> Message-ID: <45B49A63.9000601@gmx.de> Ramon Diaz-Uriarte wrote: >> In England the corresponding expression is "Counting Angels on a >> Pinhead" >> http://dannyayers.com/2001/misc/angels.htm >> > > Thanks, that is neat. I find the discussion on the sex of the angels, > well, sexier. But we are probably a few hundred years late to start a > catholic-protestant religious war here :-). > NOBODY expects the Spanish Inquisition! Our chief weapon is surprise...surprise and fear...fear and surprise. From facundo at taniquetil.com.ar Thu Jan 11 15:14:13 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 11 Jan 2007 20:14:13 +0000 (UTC) Subject: Rational Numbers References: Message-ID: Noud Aldenhoven wrote: > When I was programming in a mathematical project I began to wonder if python > supports rational numbers[1]. In a language like magma[2] it's not such a > problem. Does python supports something simular? Python does not have rational numbers. There's a (rejected) PEP about this, PEP-239: http://www.python.org/dev/peps/pep-0239/ Maybe you also want to read the section "Why not rational?" of PEP-327... http://www.python.org/dev/peps/pep-0327/#why-not-rational ...and even take a look to gmpy: http://gmpy.sourceforge.net/ Question: Why do you say that it's a problem? Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From simon at brunningonline.net Fri Jan 12 15:22:04 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 12 Jan 2007 20:22:04 +0000 Subject: dynamic argument name for functions In-Reply-To: References: Message-ID: <8c7f10c60701121222p2187225fn3e0559388a83a16e@mail.gmail.com> On 1/12/07, mark wrote: > I want to pass a value to an argument of a function. The argument name is > dynamic and is stored in a > variable. How do I call the function using with arg_name and value as the > parameters. > thanks > mark > > For ex: > def function(arg1='None', arg2='None', arg3='None'): > print arg1 > print arg2 > print arg3 > > > arg_name = 'arg1' > arg_value = 'i am passing a value to argument 1' > function(???????) Untested: function(**{arg_name: arg_value}) -- Cheers, Simon B simon at brunningonline.net From python.technofreak at gmail.com Fri Jan 19 22:44:07 2007 From: python.technofreak at gmail.com (Parthan SR) Date: Sat, 20 Jan 2007 09:14:07 +0530 Subject: **argv can't work In-Reply-To: References: Message-ID: <9d6d3deb0701191944k604a6ff8u3cea7c88cbe45f04@mail.gmail.com> On 1/20/07, Jm lists wrote: > > hello members, > > See my script piece below: > > def testB(shift,**argv): > print "first argument is %s" %shift > print "all other arguments are:",argv > > testB('mails','Jen','Jen at att.com','Joe','Joe at aol.com') > > It can't work at all.please help tell me the reasons.thanks. > > It works for me, check this one : >>> def argtst(x, **y): ... print "first arument is %s" % x ... print "other arguments are", y ... >>> argtst(x=10,a=1,b=2,c=3) first arument is 10 other arguments are {'a': 1, 'c': 3, 'b': 2} (!) : Do not use the name 'argv' for the second argument. -- With Regards, TechnoFreak -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Mon Jan 29 16:17:13 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 29 Jan 2007 22:17:13 +0100 Subject: Compiling extension with Visual C++ Toolkit Compiler - MSVCR80.dll In-Reply-To: <1170103633.189538.216620@v45g2000cwv.googlegroups.com> References: <1170103633.189538.216620@v45g2000cwv.googlegroups.com> Message-ID: <45BE6459.7050303@v.loewis.de> alexandre_irrthum at yahoo.com schrieb: > The library seems to build correctly (producing Polygon.py and > cPolygon.pyd), but when I import it I get the following message from > python.exe: "This application has failed to start because MSVCR80.dll > was not found". I thought that this might be due to Python trying to > link against the .dll from Microsoft Visual C++ Express 2005, also > installed on my PC, instead of MSVCR71.dll. So I've removed MS Visual C > ++ Express 2005, and any trace of it from my environment variables, > but that doesn't seem to change anything. > > Any help would be greatly appreciated. Can you find out where msvcrt.lib comes from? If you manage to copy the linker command line, I think link.exe has a way of telling you where it picked up the file. If that won't work, and you find multiple copies of msvcrt.lib on your disk, you can use dumpbin /all on each of them to find out which one is right. Regards, Martin From Anders+news at Arnholm.nu Tue Jan 23 08:13:49 2007 From: Anders+news at Arnholm.nu (Anders Arnholm) Date: Tue, 23 Jan 2007 14:13:49 +0100 Subject: Getting to an SSH account over a HTTP proxy References: <51jt71F1k884hU1@mid.uni-berlin.de> Message-ID: Jorgen Grahn skriver: > I am pretty sure there is. Or at least TCP-over-HTTP, or IP-over-HTTP. An > acquaintance of mine used it to tonnel home through a corporate firewall. I > think -- I didn't want to know the details. Ypu can tunnel ip over anything. (Even email if you like...) Nu tunnel out from that company was based on http-proxy. A small program called connect (the final version I used was by Shun-ichi Goto and under GPL.) Bascilly it makes a http-proxt connect to an other site (my sshd) Then using sshd and pppd as program inte other end makes a good way to tunnel IP also :-) / Anders -- http://anders.arnholm.nu/ Keep on Balping From paddy3118 at netscape.net Wed Jan 31 13:09:53 2007 From: paddy3118 at netscape.net (Paddy) Date: 31 Jan 2007 10:09:53 -0800 Subject: Sorting a List of Lists In-Reply-To: <45c08cd3$0$22805$426a74cc@news.free.fr> References: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> <45c08cd3$0$22805$426a74cc@news.free.fr> Message-ID: <1170266993.041224.75990@a34g2000cwb.googlegroups.com> On Jan 31, 12:35 pm, Bruno Desthuilliers wrote: > apoth... at gmail.com a ?crit : > > > I can't seem to get this nailed down and I thought I'd toss it out > > there as, by gosh, its got to be something simple I'm missing. > > > I have two different database tables of events that use different > > schemas. I am using python to collate these records for display. I do > > this by creating a list of lists that look roughly like this: > > > events = [['Event URL as String', 'Event Title as String ', Event Date > > as Datetime], ...] > > Then you should not use a list of lists, but a list of tuples. > > > > > I then thought I'd just go events.sort(lambda x,y: x[2] > it a day. That didn't work. But then lamda functions like to be very > > simple, maybe object subscripts aren't allowed (even though I didn't > > get an error). So I wrote a comparison function that looks much as you > > would expect: > > > def date_compare(list1, > > list2): > > x = list1[2] > > y = list2[2] > > if > > x>y: > > return > > 1 > > elif > > x==y: > > return > > 0 > > else: # > > x > return -1 > > > But as before sorting with this function returns None. > > > What have I overlooked? > > Lol. > > I guess this is a FAQ. list.sort() performs a destructive in-place sort, > and always return None. This is in the FineManual: > > bruno at bruno:~$ python > Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> help(list.sort) > Help on method_descriptor: > > sort(...) > L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; > cmp(x, y) -> -1, 0, 1 > > You may want to use sorted(iterable, cmp=None, key=None, reverse=False) > if you don't want to sort in-place. > > Also, using comparison functions is usually not the most efficient way > to do such a sort. In your case, I'd go for a good old > Decorate/sort/undecorate (AKA schwarzian transform): > > events = [evt for date, evt in > sorted([(evt[2], evt) for evt in events])] > > HTH I agree with you B., but see the comments here: http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting- efficiency for information on the relative speeds of rolling your own DSU versus using itemgetter and key=... - Paddy. From vgvr620034 at gmail.com Tue Jan 30 04:36:15 2007 From: vgvr620034 at gmail.com (raghu) Date: 30 Jan 2007 01:36:15 -0800 Subject: Diff between opening files in 'r' and 'r+' mode Message-ID: <1170149775.253373.318960@q2g2000cwa.googlegroups.com> i want to know the difference between 'r' mode and 'r+' mode 1.i = open('c:\python25\integer.txt','w')-------->for writiing i.write('hai')--------->written some content in text file i = open('c:\python25\integer.txt','r')---->for reading print i.read()---->for printing the contents in that text file i = open('c:\python25\integer.txt','w')---------->for writing i.write('how')-----------?Rewrite the contents print i.read() [MY QUESTION]:i want to read the text file contents cant it be done by giving (print i.read())? Before going to next question [I deleted all the contents in the text file] 2.i = open('c:\python25\integer.txt','r+')-----For reading and writing i.write('hai')--------->written some content to text file print i.read()--------->{? ?('c:\python25\integer.txt','w') i write('') print i.read()how') i = open('c:\python25\integer.txt','r') print i.read() i = open('c:\python25\integer.txt','w') i.write() i = open('c:\python25\integer.txt','r') print i.read() } --->Thats what i saw on interpreter(In curly braces) when i ran the script [MY QUESTION]:1.from where the above in curly braces is printed?and i have written only 'hai' to the text file 2.Should i recall again the opening of the file in 'r' mode to read the file? From tundra at tundraware.com Wed Jan 31 12:07:47 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Wed, 31 Jan 2007 11:07:47 -0600 Subject: What is the dummy statement that do nothing in Python? In-Reply-To: References: Message-ID: <45C0CCE3.2080601@tundraware.com> Dongsheng Ruan wrote: > I remember that in python there is some kind of dummy statement that just > holds space and does nothing. > > I want it to hold the place after a something like if a>b: do nothing > > I can't just leave the space blank after if statement because there will be > error message. > > Does anybody know what to insert there? > > Thanks! > > if a > b: pass From horpner at yahoo.com Thu Jan 25 09:02:54 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 25 Jan 2007 14:02:54 GMT Subject: Please have a look at this class References: <1169735908.009109.7460@a75g2000cwd.googlegroups.com> Message-ID: On 2007-01-25, antred wrote: > While working on a program I encountered a situation where I'd > construct a largish data structure (a tree) from parsing a host > of files and would end up having to throw away parts of my > newly built tree if a file turned out to contain invalid data. The first idea that occurs to me is to provide a merge function for your data structure, which you use to merge in another tree object when that data is known to be valid. So the process would work like this: temp_tree = process(the_file) if temp_tree.is_valid(): real_tree.merge(temp_tree) > > > u = Unrollable() > u.someValue = 3.14 > u.aString = 'Hi there' > > # If we decide we want to keep those changes ... > u.commit() > > # Or we could have reverted to the original. This would have restored > the state prior to the last call to commit() (or simply the > state at the beginning, if there hasn't been a call to commit > yet). > #u.rollback() > > > > The basic idea behind this is that each instance of the > Unrollable class keeps an internal dictionary (which, in lieu > of a better name I'm currently calling 'sand box') to which all > changed attribute values are saved (attribute changes are > intercepted via __setattr__). Then, with a call to commit(), > all attributes are transferred to the instance's __dict__ > dictionary and hence become actual attributes per se. A nice use for this class might be to pass large mutable objects to a functions as if it were immutable without needing to copy them. Unfortunately it only works for one level of call. I think. -- Neil Cerutti -- Posted via a free Usenet account from http://www.teranews.com From postbox.holger at gmx.net Thu Jan 11 11:11:27 2007 From: postbox.holger at gmx.net (Holger) Date: Thu, 11 Jan 2007 17:11:27 +0100 Subject: Frequency spectrum with fft of a real valued array...? Message-ID: Dear all, I need to do a FFT on an array of 20k real values. Origin of the sampled data is a sinus wave with light harmonics. The goal is an frequency spectrum with the magnitudes of the first 50. harmonics. I addressed python like: test_arr = src_data_dict[ channel ][0:19599] target_data_dict[ channel ] = FFT.fft(test_arr,n=50,axis=-1) This results in an array of complex values but with unexpected big coefficients... (much higher than the original signal magnitudes) How do I get the absolute magnitudes of the harmonics, which are much lower than the resulting absolute values of the coefficients? The result should be like this: 1.harmonic (50 Hz) 1,0 2.harmonic (100 Hz) 0,01 3.harmonic (100 Hz) 0,08 4.harmonic (100 Hz) 0,0035 etc. at the moment I get a resulting array like: CH1 (1729.80103418+0j) (366.689810532+19.5196963754j) (370.688444025+32.162562652j) (372.122246668+46.9545880507j) (379.273599053+59.0724599622j) (369.889589421+75.9247281559j) (381.070551892+99.07345873j) (378.800462354+106.761629308j) (375.014128346+131.34177586j) (389.110601354+149.320740829j) (389.23247472+158.909042086j) (398.875237165+197.86980788j) (397.927158223+196.858459101j) (402.455325066+234.651276425j) (411.599088579+256.32156894j) (414.469935576+254.512014918j) (417.198515262+291.400509132j) (426.745545674+320.769421334j) (433.987466212+321.929780157j) (446.124386798+350.810581686j) (455.876025379+383.099789898j) (458.083277747+405.592129477j) (470.908512117+433.929598454j) (482.083855098+468.256188814j) What does it mean to me? How do I get to the wanted frequenca spectrum??? .. btw The maximum magnitudes of the original data are app. 70 peak Thanks in advance for your help!!! Regards Holger From gandalf at designaproduct.biz Fri Jan 5 11:40:45 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 17:40:45 +0100 Subject: importing / loading a module / class dynamically In-Reply-To: References: Message-ID: <459E7F8D.3040302@designaproduct.biz> > .../.../../plugin/name1/name1.py > .... > .../.../../plugin/namen/namen.py > > > I block at the beginning and tried this (test.py is a real file) > >>>> s = 'test.py' >>>> eval ('import ' + s) >>>> import test.py # This is invalid import test # This MAY be valid import name1.name1 # Most probably this is what you want if you have the aforementioned directory stucture from name1 import name1 # Or this? You must also: 1. Have the 'plugin' dir in your sys.path 2. Have at least an empty plugin/name1/__init__.py file Another alternative is to have plugins/__init__.py and do something like: from plugins.name1 import name1 You should not overcomplicate things anyway. If you do not need these name1...namen directories for sure, then just drop them. Hint: try this (untested) import os fnames = os.listdir('plugins') for fname in fnames: if os.path.isdir(fname): root,ext = os.path.splitext(fname) cmd = "from plugins.%s import %s" % (root,root) print "I should eval this:",cmd Best, Laszlo > Traceback (most recent call last): > File "", line 1, in -toplevel- > eval ('import ' + s) > File "", line 1 > import test.py > From practicalperl at gmail.com Sat Jan 20 04:30:24 2007 From: practicalperl at gmail.com (Jm lists) Date: Sat, 20 Jan 2007 17:30:24 +0800 Subject: Does eval has the same features as Perl's? Message-ID: Hello members, I want to know does the "eval" in python have the same features as in Perl (capture errors)? For example,in perl I can wrote: $re = eval { 1 / 0 }; Though 1/0 is a fatal error but since it's in "eval" block so the perl interpreter doesn't get exit. Thanks again. From bborcic at gmail.com Wed Jan 24 06:08:58 2007 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 24 Jan 2007 12:08:58 +0100 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <1169582795.882496.209750@a75g2000cwd.googlegroups.com> References: <45b6231b$1_2@news.bluewin.ch> <1169582795.882496.209750@a75g2000cwd.googlegroups.com> Message-ID: imageguy wrote: > > I was looking for ( and still am searching for) similiar functionality. > Specifically I would like to be able to capture a small area of the > screen (a number or a code) and convert this to text that can be used > in my application. There is a windows executable version of gnu ocr at http://jocr.sourceforge.net/download.html that (in combination with screen capture capability that pywinauto distributes) sort of can do that. An issue is that it's not exceedingly accurate, for instance it recognizes "2" as "1" (in the font that er, counts for me). I could probably manage such imprecisions but I would rather have an exact solution. ... > > I work with wxPython and Win32 applications exclusively. > > So if I can be of any help or assistance, please let me know. > > Geoff. > Thanks for the offer, I will keep it in mind, Boris Borcic From tundra at tundraware.com Mon Jan 8 12:36:58 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 08 Jan 2007 11:36:58 -0600 Subject: Walking The Right Path In-Reply-To: References: Message-ID: Peter Otten wrote: > Tim Daneliuk wrote: > >> IOW, is there a way to return a symlink-based path which contains >> the symlink pointer as is was *defined* not as it expands? > > os.readlink() > > Peter Thanks - I couldn't find it because it was right in front of my nose :) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From nospam at riddergarn.dk Sun Jan 28 06:10:46 2007 From: nospam at riddergarn.dk (Scripter47) Date: Sun, 28 Jan 2007 12:10:46 +0100 Subject: Array delete Message-ID: <45BC84B6.9080505@riddergarn.dk> Hey, Can someone plz make a function for that takes a array, and then search in it for duplicates, if it finds 2 or more items thats the same string then delete all except 1. Short: it deletes all duplicates in a array thanks From rweth at cisco.com Sat Jan 6 15:38:05 2007 From: rweth at cisco.com (rweth) Date: Sat, 06 Jan 2007 12:38:05 -0800 Subject: nntplib downloads content with extra linebreaks In-Reply-To: References: <1168110213.436860@sj-nntpcache-1.cisco.com> <1168112276.194982@sj-nntpcache-1.cisco.com> Message-ID: <1168115885.739704@sj-nntpcache-1.cisco.com> Klaus Alexander Seistrup wrote: > Rweth wrote: > >> for aline in buf: >> bufHeal.append(aline.replace('\r\n', '\n')) > > What does one single aline look like? > >> s.body(id,afile) > > Does the 'afile' contain a filename or a filepointer? > > Cheers, > so afile contains a filename. One single aline looks like so: '' From jan.m.danielsson at gmail.com Tue Jan 23 00:17:15 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 23 Jan 2007 06:17:15 +0100 Subject: Removing outdated files Message-ID: <45b59949@griseus.its.uu.se> Hello all, I have a backup system which produces files using the following pattern: .. For instance: documents.2007-01-01.tar.bz2.gpg documents.2007-01-02.tar.bz2.gpg . . . system_files.2007-01-01.tar.bz2.gpg system_files.2007-01-02.tar.bz2.gpg . . . etc. Obviously, I have little need for *all* those files. What I want to do is to delete old files according to this pattern: - Keep all backup files which are two weeks, or less, old - If backups are more than two weeks old, then keep only the latest one for each week. - If backups are more than two months old, then keep only the latest one for each month. - If backups are more than two years old, then keep only the latest one for each year. I have generated a list of files, parsed the date from the entries, and created date object from them. I have a list where I have grouped the "basenames" together. I.e. (lists in a list): documents 2007-01-01 2007-01-02 . . . system_files 2007-01-01 2007-01-02 . . . Now all I have to do is iterate through the date-lists for each of the basenames, and apply the rules! Well.. How does one group by week, for instance? I'd like to create a new set of lists which looks like this: basename:documents week:01 2007-01-01 2007-01-02 week:02 2007-01-07 2007-01-08 Date-grouping is dead easy in SQL, but I don't feel like resorting to postgresql just for this. :-) I've been looking at the datetime.date class, but I can't see any easy way to parse the week number from it. I could calculate this information by brute force -- but I get a feeling that there are functions in Python to extract week numbers from a date. -- Kind regards, Jan Danielsson ------------ And now a word from our sponsor ------------------ For a quality usenet news server, try DNEWS, easy to install, fast, efficient and reliable. For home servers or carrier class installations with millions of users it will allow you to grow! ---- See http://netwinsite.com/sponsor/sponsor_dnews.htm ---- From anton.hartl at gmail.com Tue Jan 16 11:15:54 2007 From: anton.hartl at gmail.com (Anton Hartl) Date: Tue, 16 Jan 2007 16:15:54 +0000 (UTC) Subject: Segfault with tktreectrl on python-2.5 on linux References: <1168884154.116074.308720@s34g2000cwa.googlegroups.com> <1168941826.062298.229080@51g2000cwl.googlegroups.com> Message-ID: On 2007-01-16, klappnase wrote: >> Solutions: >> >> a) convince Python developers to prefix ALL new (wrt. 2.5) >> global symbols with a prefix like "_PyAST_" or equivalent; >> this would be consistent with how it is done anyway, >> unfortunately the new AST symbols deviate from this practise >> (there are symbols like "Assert", "If", "Then", ...) >> >> or b) apply an equivalent rule to the global symbols in >> tktreectrl that are global by accident, i.e. because >> of the way the library is structured and built >> > > Anton, you're cool, Well :) understanding this bug required a looong stare at the gdb stacktrace and a short experiment with loading shared libraries to verify my understanding with a simple example. > > actually renaming Ellipsis to Py_Ast_Ellipsis in ast.c and Python-ast.c > seems to fix this. Alternatively renaming Ellipsis to TkTc_Ellipsis in tktreectrl works too; that's what I did :) > What I don't understand, isn't it very likely that such things will > happen when names like "Ellipsis" or "Slice" and "Index" (which I also > found in Python-ast.c) are being used, or are the treectrl people doing > something they should avoid? IMHO global symbols that do not actually have any use outside the respective library should follow a naming convention that minimizes the probablity of name clashes like this. I.e. both the new AST symbols in Python 2.5 and the global symbols in tktreectrl should be prefixed appropriately. > I think the answer to this might be important when deciding to whom I > should send a bug report :) The bug report should go to both; I actually contacted Jeremy Hylton as a main contributor of the new AST code two weeks ago but didn't get any response. Regards, Anton PS Thanks for your work on TkinterTreectrl! From bearophileHUGS at lycos.com Sat Jan 20 05:53:47 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 20 Jan 2007 02:53:47 -0800 Subject: Py 2.5 on Language Shootout In-Reply-To: <1169275613.093797.67320@v45g2000cwv.googlegroups.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> Message-ID: <1169290427.621392.173490@38g2000cwa.googlegroups.com> pgarrone at acay.com.au: > In reality the choice would be C++ because of OO and STL. I have seen that when Python+Psyco are too much slow, D language is a good sweet half point between Python and C++ :-) Fast as C++ and with a simpler syntax and semantics (Pyrex isn't bad, but D gives high-level things at higher speed). And in the future ShedSkin and RPython may become options too. Bye, bearophile From kylotan at gmail.com Tue Jan 2 11:58:58 2007 From: kylotan at gmail.com (Ben Sizer) Date: 2 Jan 2007 08:58:58 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> Message-ID: <1167757137.942280.32270@42g2000cwt.googlegroups.com> Gabriel Genellina wrote: > At Saturday 30/12/2006 21:55, Ben Sizer wrote: > > >python setup.py install > > > >On Unix, you'd run this command from a shell prompt; on Windows, you > >have to open a command prompt window (``DOS box'') and do it there; " > > > >Pretty much none of the instructions in that part of the docs will work > >without you altering your path beforehand. Python's cross-platform > >nature means people rightly expect the same instructions to work on > >Linux and Windows from a standard installation. Right now, they don't. > > Notice that there is NO need to alter the system path. You just have > to tell Windows where python.exe resides; there is a per-application > path located at > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths. > In order to launch Python just writing "python" at the command > prompt, the installer should -instead of playing with the system > path- create a new key below App Paths, named "python.exe", and set > its default value to the full path of the installed python executable. > See > http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/fileassociations/fa_perceived_types.asp >From what I can tell, that is solely for file associations. If so, it will work if you type "setup.py install" but not if you type "python setup.py install". For instance, I have an entry for Firefox in that part of the registry, but if you try executing "firefox" at the command line, it fails. It also doesn't solve the issue of utility scripts being added to Python's scripts directory. -- Ben Sizer From beliavsky at aol.com Fri Jan 5 21:20:50 2007 From: beliavsky at aol.com (Beliavsky) Date: 5 Jan 2007 18:20:50 -0800 Subject: Dividing integers...Convert to float first? In-Reply-To: References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> <459E8C77.3020603@rpath.com> Message-ID: <1168050050.353467.185040@s80g2000cwa.googlegroups.com> Thomas Ploch wrote: > Jonathan Smith schrieb: > > Thomas Ploch wrote: > >> redefined.horizons at gmail.com schrieb: > >>> I'm still pretty new to Python. I'm writing a function that accepts > >>> thre integers as arguments. I need to divide the first integer by te > >>> second integer, and get a float as a result. I don't want the caller of > >>> the function to have to pass floats instead of integers. How do I > >>> convert the arguments passed to the function into floats before I do > >>> the division? Is this necessary, or is their a better way? > >>> > >>> Thanks, > >>> > >>> Scott Huey > >>> > >> > >> Yes, it is necessary. If you divide two integers, the result will be an > >> integer. > >> > >> >>> 1/2 > >> 0 > >> > >> You need the function float() -> float because a division between > >> integers and floats will have floats as their results > >> > >> >>> float(1)/2 > >> 0.5 > > > > > >>>> from __future__ import division > >>>> 1/2 > > 0.5 > > > > -smithj > > > > aahh, I have been tought so many things about python that are actually > so old, that I am starting to feel embarrassed. > > That brings me to the point, that learning a language X at university > always brings you to a point where you know (almost) everything, but in > reality know nothing because course material is too old... If you learned C or Fortran 10 years ago, the constructs you learned still have the same meaning, even though new features have been added in C99 or Fortran 95. Mr. van Rossum appears to value backwards compatibility less than the C or Fortran standards committees do, although I am sure he is introducing incompatibilities only after serious consideration. If the C or Fortran committees tried to change the meaning of int/int, they would be shot. If you want to be confident that your code will run, unchanged, 10 years from now on the hardware and OS that will then be common, Python 2.x is not the language to use, unfortunately. From what I have read, Python 3 will break things more fundamental than int/int. From anil.jupiter9 at gmail.com Mon Jan 29 08:55:33 2007 From: anil.jupiter9 at gmail.com (jupiter) Date: 29 Jan 2007 05:55:33 -0800 Subject: Conversion of string to integer Message-ID: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> Hi guys, I have a problem. I have a list which contains strings and numeric. What I want is to compare them in loop, ignore string and create another list of numeric values. I tried int() and decimal() but without success. eq of problem is #hs=string.split(hs) hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"] j=0 for o in range(len(hs)): print hs[o],o p=Decimal(hs[o]) if p > 200: j+=j print "-"*5,j print "*"*25 I could be the best way to solve this ......? @nil From gagsl-py at yahoo.com.ar Sun Jan 7 13:06:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 10:06:46 -0800 Subject: strange for loop construct In-Reply-To: <12ptf5bl21f2teb@corp.supernews.com> References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> <12ptf5bl21f2teb@corp.supernews.com> Message-ID: <1168193206.598957.257700@38g2000cwa.googlegroups.com> Mark Elston ha escrito: > If you have a Python installation you should be able to find the > "Whats New" section of the docs. List comprehensions are described > pretty well in the "What's new in Python 2.0?" section. This gives > some simple examples as well as the rationale behind them. Where do you find the "What's new" for previous releases? I have to read them online. -- Gabriel Genellina From jfabiani at yolo.com Thu Jan 11 16:05:56 2007 From: jfabiani at yolo.com (johnf) Date: Thu, 11 Jan 2007 13:05:56 -0800 Subject: Learning Python book, new edition? References: Message-ID: Demel, Jeff wrote: > This email is intended only for the individual or entity to which it is > addressed. ?This email may contain information that is privileged, > confidential or otherwise protected from disclosure. Dissemination, > distribution or copying of this e-mail or any attachments by anyone other > than the intended recipient, or an employee or agent responsible for > delivering the message to the intended recipient, is prohibited. If you > are not the intended recipient of this message or the employee or agent > responsible for delivery of this email to the intended recipient, please > notify the sender by replying to this message and then delete it from your > system. ?Any use, dissemination, distribution, or reproduction of this > message by unintended recipients is strictly prohibited and may be > unlawful. So what happens with google bots etc... Information provided in the email could be helpful to others that are NOT the original recipient. And what happens to the archive stuff? John From huayang.xia at gmail.com Thu Jan 4 16:42:42 2007 From: huayang.xia at gmail.com (Huayang Xia) Date: 4 Jan 2007 13:42:42 -0800 Subject: subclassing a module: misleading(?) error message In-Reply-To: <459d687a$1@nntp.zianet.com> References: <459d687a$1@nntp.zianet.com> Message-ID: <1167946962.471424.47780@42g2000cwt.googlegroups.com> So you know you are subclassing a module. There is an answer @ http://www.velocityreviews.com/forums/showpost.php?p=1819038&postcount=2 On Jan 4, 3:49 pm, "Erik Johnson" wrote: > I ran into a problem I didn't understand at first. I got part of it figured > out. Let me first demonstrate the original problem: > > > cat Super.pyclass Super(object): > def __init__(self): > self._class = 'Super' > def hello(self): > print "%s says 'Hello'" % self._class > > > cat Sub.pyimport Super > > class Sub(Super): > def __init__(self): > self._class = 'Sub' > > > pythonPython 2.3.4 (#1, Feb 7 2005, 15:50:45) > [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> from Super import Super > >>> from Sub import SubTraceback (most recent call last): > File "", line 1, in ? > File "Sub.py", line 4, in ? > class Sub(Super): > TypeError: function takes at most 2 arguments (3 given) > > My question is NOT "What's wrong here?" > (The answer to that is that the import in Sub.py should be: from Super > import Super > i.e., I tried to use the module itself where I meant to subclass the class > defined in that module). > > My questions are: > > Why does python complain about a function here? (it's a class definition > statement, right?) > Is there really a function being called here? > If so: > What function was called? > What two arguments is it expecting? > What three were given? > > Thanks, > -ej From gagsl-py at yahoo.com.ar Wed Jan 24 12:21:44 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 14:21:44 -0300 Subject: Simple Matrix class In-Reply-To: <1169617221.481444.135820@v45g2000cwv.googlegroups.com> References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070124141952.03497450@yahoo.com.ar> At Wednesday 24/1/2007 02:40, Paul McGuire wrote: > > The points should be aligned on a log-log plot to be a power function. > > As Robert Kern stated before, this problem should be not worse than > > O(n**3) - how have you implemented it? > > >Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05 >X 3**n. So either reimplement it better, or place a notice in BIG letters to your users about the terrible time and memory penalties of using inverse() -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From oyekomova at hotmail.com Sat Jan 13 14:13:57 2007 From: oyekomova at hotmail.com (oyekomova) Date: 13 Jan 2007 11:13:57 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> Message-ID: <1168715634.695961.14710@l53g2000cwa.googlegroups.com> Thanks to everyone for their excellent suggestions. I was able to acheive the following results with all your suggestions. However, I am unable to cross file size of 6 million rows. I would appreciate any helpful suggestions on avoiding memory errors. None of the solutions posted was able to cross this limit. >>> Data size 999999 Elapsed 31.60352213 >>> ================================ RESTART ================================ >>> Data size 1999999 Elapsed 63.4050884573 >>> ================================ RESTART ================================ >>> Data size 4999999 Elapsed 177.888915777 > Data size 5999999' Traceback (most recent call last): File "C:/Documents/some.py", line 27, in read_test() File "C:/Documents/some.py", line 21, in read_test data = array(data, dtype = float) MemoryError Robert Kern wrote: > Travis E. Oliphant wrote: > > > If you use numpy.fromfile, you need to skip past the initial header row > > yourself. Something like this: > > > > fid = open('somename.csv') > > # I think you also meant to include this line: > header = fid.readline() > > > data = numpy.fromfile(fid, sep=',').reshape(-1,6) > > # for 6-column data. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From aahz at pythoncraft.com Mon Jan 29 20:43:58 2007 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2007 17:43:58 -0800 Subject: The reliability of python threads References: Message-ID: In article , Carl J. Van Arsdall wrote: >Aahz wrote: >> >> My response is that you're asking the wrong questions here. Our database >> server locked up hard Sunday morning, and we still have no idea why (the >> machine itself, not just the database app). I think it's more important >> to focus on whether you have done all that is reasonable to make your >> application reliable -- and then put your efforts into making your app >> recoverable. >> >Well, I assume that I have done all I can to make it reliable. This >list is usually my last resort, or a place where I come hoping to find >ideas that aren't coming to me naturally. The only other thing I >thought to come up with was that there might be network errors. But >i've gone back and forth on that, because TCP should handle that for me >and I shouldn't have to deal with it directly in pyro, although I've >added (and continue to add) checks in places that appear appropriate >(and in some cases, checks because I prefer to be paranoid about errors). My point is that an app that dies only once every few months under load is actually pretty damn stable! That is not the kind of problem that you are likely to stimulate. >> I'm particularly making this comment in the context of your later point >> about the bug showing up only every three or four months. >> >> Side note: without knowing what error messages you're getting, there's >> not much anybody can say about your programs or the reliability of >> threads for your application. > >Right, I wasn't coming here to get someone to debug my app, I'm just >looking for ideas. I constantly am trying to find new ways to improve >my software and new ways to reduce bugs, and when i get really stuck, >new ways to track bugs down. The exception won't mean much, but I can >say that the error appears to me as bad data. I do checks prior to >performing actions on any data, if the data doesn't look like what it >should look like, then the system flags an exception. > >The problem I'm having is determining how the data went bad. In >tracking down the problem a couple guys mentioned that problems like >that usually are a race condition. From here I examined my code, >checked out all the locking stuff, made sure it was good, and wasn't >able to find anything. Being that there's one lock and the critical >sections are well defined, I'm having difficulty. One idea I have to >try and get a better understanding might be to check data before its >stored. Again, I still don't know how it would get messed up nor can I >reproduce the error on my own. > >Do any of you think that would be a good practice for trying to track >this down? (Check the data after reading it, check the data before >saving it) What we do at my company is maintain log files. When we think we have identified a potential choke point for problems, we add a log call. Tracking this down will involve logging the changes to your data until you can figure out where it goes wrong -- once you know where it goes wrong, you have an excellent chance of figuring out why. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From masteroftheluffers at hotmail.com Tue Jan 9 09:33:21 2007 From: masteroftheluffers at hotmail.com (luffmusse) Date: 9 Jan 2007 06:33:21 -0800 Subject: Survey respondents needed for masters thesis Message-ID: <1168353200.954036.160540@m30g2000cwm.googlegroups.com> We are two students from the Royal Institute of Technology in Stockholm, Sweden (http://www.kth.se/eng/). We are currently doing our masters thesis in Applied Information Technology where we specialize in security. As a part of this thesis we will do a survey where we compare general information about software organizations and software projects with certain aspects and activities specific for the creation of secure software. We would really appreciate if you participated in this survey to help us with this masters thesis. Please feel free to spread information about this survey to your colleagues or any friends you have in the software industry. All answers we can get are helpful to us! The survey is available at http://support.objectplanet.com/opinio/s?s=12074 Gustav Ringbom (gringbom [at] kth.se) Christoffer Bergman (chr83 [at] kth.se) From david at boddie.org.uk Wed Jan 24 09:28:49 2007 From: david at boddie.org.uk (David Boddie) Date: 24 Jan 2007 06:28:49 -0800 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: <45b69f63$0$24463$88260bb3@free.teranews.com> Message-ID: <1169648929.902359.117790@v45g2000cwv.googlegroups.com> On Jan 24, 3:00 pm, Giovanni Bajo wrote: > Thus, it is well possible to write internal GPL software, using the Qt Open > Source library, and to release/distribute/use it *ONLY* internally. http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic > Also, it > should be made clear that a company can of course relicense its own > proprietary libraries as GPL for internal usage only, so that they can be > linked to other GPL libraries "legally". That seems to be a reasonable approach, though it seems to me that the GPL grants even "internal" users certain rights. > [[ Another page of similar babble is the one where they try to convince you > that you cannot use the Qt Open Source edition to develop a software, and then > buy the commercial edition only the day before you want to release it as non > open-source. I can't even understand how they can even try to support such a > nonsense position. You're free to develop your software for years as GPL > without distributing it, and then relicense your own code whenever you want. > They're obviously just trying to scare people. ]] That's nothing to do with any restrictions in the GPL; it's more to do with purchasing a commercial license. Obviously, if you're operating a dual licensing scheme, it's not in your interest to encourage people to pretend to write open source software up until the day it is released as a closed source product. That sort of behaviour is not exactly inviting mutual trust between vendor and customer, is it? David From http Thu Jan 18 10:46:18 2007 From: http (Paul Rubin) Date: 18 Jan 2007 07:46:18 -0800 Subject: Would a Dutch speaker please check this wiki page please? References: <45af8edf$0$336$e4fe514c@news.xs4all.nl> Message-ID: <7x8xg0s5h1.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > Indeed it's not Afrikaans but just incorrect use of Dutch and not > related to python. It was apparently posted by someone with a .be address, so I'll guess it was written a Belgian French speaker who knows some Dutch. The "me" vs "mijn" error sounds like something a French speaker might have done. From vithi99 at hotmail.com Mon Jan 15 13:53:18 2007 From: vithi99 at hotmail.com (vithi) Date: 15 Jan 2007 10:53:18 -0800 Subject: How to write code to get focuse the application which is open from server In-Reply-To: References: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> <45a0dae2$0$8948$4c368faf@roadrunner.com> <1168837895.073936.270330@11g2000cwr.googlegroups.com> Message-ID: <1168887198.362699.176110@51g2000cwl.googlegroups.com> Dennis, I am sorry that was a typing error. I try like that app.Print.OK.Click() but it was not working. The printer window was not IdentifiedIs their any method I can use to achive the same goal. How the window title was used as class name?. Could you please help me to solve this problem. thanks this is the error meassage Traceback (most recent call last): File "C:\Python24\test1.py", line 10, in -toplevel- app.Print.Ok.CloseClick() File "c:\python24\pywinauto\pywinauto\application.py", line 237, in __getattr__ ctrls = _resolve_control( File "c:\python24\pywinauto\pywinauto\application.py", line 854, in _resolve_control ctrl = _get_ctrl(criteria) File "c:\python24\pywinauto\pywinauto\application.py", line 622, in _get_ctrl dialog = controls.WrapHandle( File "c:\python24\pywinauto\pywinauto\findwindows.py", line 62, in find_window windows = find_windows(**kwargs) File "c:\python24\pywinauto\pywinauto\findwindows.py", line 177, in find_windows windows = findbestmatch.find_best_control_matches( File "c:\python24\pywinauto\pywinauto\findbestmatch.py", line 483, in find_best_control_matches raise MatchError(items = name_control_map.keys(), tofind = search_text) MatchError: Could not find 'Print' in '['', u'Transparent Windows Client0', u'Transparent Windows Client2', u'Transparent Windows Client1', u'Print - \\\\Remote', u'Transparent Windows Client', u'Print - \\\\RemoteTransparent Windows Client']' This is the code import sys import time import application app = application.Application() qi=app.window_(title_re = ".*ArcView.*") time.sleep(2) qi.TypeKeys("%FP") time.sleep(2) app.Print.Ok.CloseClick() Dennis Lee Bieber wrote: > On 14 Jan 2007 21:11:35 -0800, "vithi" declaimed > the following in comp.lang.python: > > > > > my code goes like that > > "goes like"? Don't type similarities from memory -- cut&paste the > actual code (or, preferably, a stripped down version that you've > actually run) that shows the behavior in question. > > > app=application.Application() > > qi = app.window_(title_re = ".*arcMap.*") > > qi.TypeKeys("%FP") > > app,Print.OK.Click() > > > And what is that last line supposed to be doing. "app,anything" is > two separate objects: an application object, and something called Print > with an attribute called OK which itself has a method called Click > > I suspect, at a minimum, that last line is supposed to be > > app.Print.OK.Click() > ^ period, not From edquichan at yahoo.com Thu Jan 18 12:27:33 2007 From: edquichan at yahoo.com (EdG) Date: 18 Jan 2007 09:27:33 -0800 Subject: Traversing the properties of a Class Message-ID: <1169141253.332211.12790@38g2000cwa.googlegroups.com> I'm using Python version 2.4 and I created a class with some properties like: def GetCallAmount(self): return somedata def GetCallCurrency(self): return somemoredata more....defs..etc. CallAmount = property(GetCallAmount,None,None,None) CallCurrency = property(GetCallCurrency, None, None, None) more....properies..etc. For debugging purposes, I would like to traverse the class listing out all the properties. From gagsl-py at yahoo.com.ar Mon Jan 8 20:47:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 22:47:36 -0300 Subject: Non-blocking pipes during subprocess handling In-Reply-To: <22q5q25jn7dfti18rv1tshj7os5a0gm27r@4ax.com> References: <22q5q25jn7dfti18rv1tshj7os5a0gm27r@4ax.com> Message-ID: <7.0.1.0.0.20070108224528.00fd0238@yahoo.com.ar> At Monday 8/1/2007 22:09, Tom Plunket wrote: >I'm using subprocess to launch, well, sub-processes, but now I'm >stumbling due to blocking I/O. > >Is there a way for me to know that there's data on a pipe, and possibly >how much data is there so I can get it? Currently I'm doing this: Using a thread for each stream is the safest way, specially if you can't control the child process. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bcannon at gmail.com Sun Jan 7 00:49:50 2007 From: bcannon at gmail.com (bcannon at gmail.com) Date: 6 Jan 2007 21:49:50 -0800 Subject: Got questions to pose to the Python-Dev panel at PyCon? Message-ID: On the first conference day of PyCon after lunch there is going to be a discussion panel for Python-Dev (see http://us.pycon.org/apps07/schedule/ for the schedule). It is going to be moderated by Steve Holden and is slated to have myself (Brett Cannon), Andrew Kuchling (AMK), Neal Norwitz, and Jeremy Hylton on the panel. But in order to make the panel a success we need some questions. We will have a portion of time open to questions from the floor, but we would also like to have some questions lined up. If you have any questions you would like to have answered by the panel, please add them to http://us.pycon.org/TX2007/PythonDevPanel . The wiki page will be considered the definitive location of collected questions so please do not leave any questions as a reply to this announcement as it will not get noticed. I do not know if there will be an audio or video recording of the panel discussion, but there is a decent chance if last year's PyCon is any indication. Plus someone in the audience might be kind enough to type up a transcript and post it online. Thanks in advance to anyone who contributes a question. -Brett C. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jan 9 13:13:06 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 09 Jan 2007 19:13:06 +0100 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <50i49iF1fvo3rU1@mid.individual.net> Nick Maclaren wrote: > No, don't. That is about another matter entirely, It isn't. Regards, Bj?rn -- BOFH excuse #366: ATM cell has no roaming feature turned on, notebooks can't connect From arkanes at gmail.com Wed Jan 10 10:10:04 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 10 Jan 2007 09:10:04 -0600 Subject: Need startup suggestions for writing a MSA viewer GUI in python In-Reply-To: References: Message-ID: <4866bea60701100710g7bed1dd9t916e7cc8f4386399@mail.gmail.com> On 1/10/07, Joel Hedlund wrote: > Hi! > > I've been thinking about writing a good multiple sequence alignment > (MSA) viewer in python. Sort of like ClustalX, only with better zoom and > pan tools. I've been using python in my work for a couple of years, but > this is my first shot at making a GUI so I'd very much appreciate some > ideas from you people to get me going in the right direction. Despite my > GUI n00b-ness I need to get it good and usable with an intuitive look > and feel. > > What do you think I should do? What packages should I use? > > For you non-bioinformatic guys out there, an MSA is basically a big > matrix (~1000 cols x ~100 rows) of letters, where each row represents a > biological sequence (gene, protein, etc...). Each sequence has an ID > that is usually shorter than 40 characters (typically, 8-12). Usually, > msa visualizers color the letters and their backgrouds according to > chemical properties. > > I want the look and feel to be pretty much like a modern midi sequencer > (like cubase, nuendo, reason etc...). This means the GUI should have > least three panes; one to the left to hold the IDs, one in the bottom to > hold graphs and plots (e.g: user configurable tracks), and the main one > that holds the actual MSA and occupies most of the space. The left and > bottom panes should be resizable and foldable. > > I would like to be able to zoom and pan x and y axes independently to > view different portions of the MSA, and the left and bottom panes should > follow the main pane. I would also like to be able to use drag'n'drop on > IDs for reordering sequences, and possibly also on the MSA itself to > shift sequences left and right. Furthermore, I would like to be able to > select sequences and positions (individually, in ranges or sparsely). I > would like to have a context sensitive menu on the right mouse button, > possibly with submenus. Finally, I'd like to be able to export printable > figures (eps?) of regions and whole MSAs. > > I'm thinking all three panes may have to be rendered using some sort of > scalable graphics because of the coloring and since I'd like to be able > to zoom freely. I'll also need to draw graphs and plots for the tracks. > Is pygame good for this, or is there a better way of doing it? > > I want my viewer to behave and look like any other program, so I'm > thinking maybe I should use some standard GUI toolkit instead, say PyQT > or PyGTK? Would they still allow me to render the MSA nicely? > > Does this seem like a humongous project? > > Thanks for taking the time! > /Joel Hedlund This will probably be a major, but not humongous project. wxPython, pyGTk, and pyQt all have the architecture and basics you'll need, it will probably be about the same amount of work to create in all of them. Pick the one that best suites your licensing and platform needs. From cvanarsdall at mvista.com Wed Jan 31 18:13:59 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 31 Jan 2007 15:13:59 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <20070131222016.25807.1107543360.divmod.quotient.5093@ohm> References: <20070131222016.25807.1107543360.divmod.quotient.5093@ohm> Message-ID: <45C122B7.6000701@mvista.com> Jean-Paul Calderone wrote: > [snip] >> >> > > You're right. Learning new things is bad. My mistake. > > Jean-Paul > That isn't what I said at all. You have to look at it from a cost/benefit relationship. Its a waste of time/money to learn something complex to do something simple. For the simple things, use a simple solution. KISS. When he has an application that would require something more complex, it would be at that point he should consider using it for a project. Unless the OP has a desire to learn this technology, then more power to him. I, however, do not believe that would be the best approach for a simple problem. Knowing the appropriate tool for the job is a trait of an good engineer. -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From vithi99 at hotmail.com Wed Jan 31 16:29:24 2007 From: vithi99 at hotmail.com (vithi) Date: 31 Jan 2007 13:29:24 -0800 Subject: win32com.client Message-ID: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> Hi Any one tell me where I can get (or download) python modules win32com or win32com.client because I have to use "Dispatch" thanks From albert.wellens at gmail.com Wed Jan 17 14:03:15 2007 From: albert.wellens at gmail.com (awel) Date: 17 Jan 2007 11:03:15 -0800 Subject: Check a windows service References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> <1168967374.568967.173690@11g2000cwr.googlegroups.com> <1168985869.099273.13630@38g2000cwa.googlegroups.com> <1169030185.707886.229920@51g2000cwl.googlegroups.com> Message-ID: <1169060595.905108.167190@l53g2000cwa.googlegroups.com> Thanks for all 'cause you've really helped me Just one thing in the last line for the specific service, you' ve writted : > print service but I think it is : > print service.Caption Tim Golden a ?crit : > awel wrote: > > Sorry, but could you give me an example with a real service 'cause I've > > tried this script but nothings happened, no error, nothings ; even if I > > launch it in cmd prompt. > > Well, as that example said, it was designed to show > automatic services which are not running. If you don't > have any then nothing will show. I assumed you could > use this as a starting point. > > To list all services try this: > > > import wmi > > c = wmi.WMI () > for service in c.Win32_Service (): > print service.Caption > > > > To show a specific service: > > > import wmi > > c = wmi.WMI () > for service in c.Win32_Service (Caption="Task Scheduler"): > print service > > > > TJG From chris at wavestore.com Fri Jan 26 12:21:40 2007 From: chris at wavestore.com (Christopher Mocock) Date: Fri, 26 Jan 2007 17:21:40 +0000 Subject: Handling empty form fields in CGI Message-ID: <45BA38A4.5000903@wavestore.com> Hi all, Bit of a python newbie so need a little help with a CGI script I'm trying to write. I've got it working fine as long as the fields of the form are filled in correctly, however I need to be able to accept blank entries. Therefore I want to convert any empty entries to an empty string. For example, if I call the following CGI script as: http://localhost/cgi-bin/test.cgi?myfield=hello ...it prints hello in the browser. But if I call it as: http://localhost/cgi-bin/test.cgi?myfield= I get an exception. I want it to treat myfield as an empty string and not throw an exception. Any suggestions? Thanks in advance, Chris. Script below: #!/usr/bin/env python2 # Import CGI and CGI debug libraries import cgi import cgitb; cgitb.enable() def test(): value=form["myfield"].value print value # Start of main code print 'Content-type: text/html' print # Get the contents of the query string form = cgi.FieldStorage() test() From http Thu Jan 25 07:37:06 2007 From: http (Paul Rubin) Date: 25 Jan 2007 04:37:06 -0800 Subject: While loop with "or"? Please help! References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> Message-ID: <7xac07uvt9.fsf@ruckus.brouhaha.com> wd.jonsson at gmail.com writes: > while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM while userinp not in 'yYnN': ... Or maybe more generally: while userinp.lower() not in 'yn': # case independent test ... From nick at craig-wood.com Tue Jan 9 07:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 09 Jan 2007 06:30:06 -0600 Subject: Non-blocking pipes during subprocess handling References: <22q5q25jn7dfti18rv1tshj7os5a0gm27r@4ax.com> Message-ID: Tom Plunket wrote: > I'm using subprocess to launch, well, sub-processes, but now I'm > stumbling due to blocking I/O. > > Is there a way for me to know that there's data on a pipe, and possibly > how much data is there so I can get it? You might want to check out this modification to subprocess which does non-blocking pipes. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 I personally think something like that should be built into subprocess -- Nick Craig-Wood -- http://www.craig-wood.com/nick From Thomas.Ploch at gmx.net Sun Jan 7 10:52:13 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 16:52:13 +0100 Subject: Why less emphasis on private data? In-Reply-To: <7x3b6mzwkl.fsf@ruckus.brouhaha.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> Message-ID: <45A1172D.7010609@gmx.net> Paul Rubin schrieb: > Thomas Ploch writes: >> Me neither, although I have to say that the '__' prefix comes pretty >> close to being 'private' already. It depends on the definition of >> private. For me, private means 'not accessible from outside the >> module/class'. > > class A: > __x = 3 > > class B(A): > __x = 4 # ok > > class C(B): > __x = 5 # oops! > > Consider that the above three class definitions might be in separate > files and you see how clumsy this gets. I don't understand why this should be oops, even if they are in different files. >>> a = A() >>> print a._A__x 3 >>> b = B() >>> print b._B__x 4 >>> c = C() >>> print c._C__x 5 >>> dir(c) ['_A__x', '_B__x', '_C__x', '__doc__', '__module__'] >>> print c._A__x 3 >>> print c._B__x 4 From bdesth.quelquechose at free.quelquepart.fr Sat Jan 20 13:54:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Jan 2007 19:54:26 +0100 Subject: Win GUI application: avoiding DOS console In-Reply-To: References: Message-ID: <45b25ec1$0$16367$426a74cc@news.free.fr> Siggi a ?crit : > Hi all, > > how do I avoid the DOS console show-up when starting a WinXP GUI application > with mouseclick on the respective Python file? rename yourfile.py to yourfile.pyw From adonis at REMOVETHISearthlink.net Mon Jan 22 15:40:57 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Mon, 22 Jan 2007 20:40:57 GMT Subject: Best way to document Python code... In-Reply-To: <1169492869.101706.253620@38g2000cwa.googlegroups.com> References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: Scott Huey wrote: > I am working on a Python module and I would like to prepare some API > documentaiton. I managed to find epydoc after some searching online. > > Is there a standard way to document the API for Python modules? Is > epydoc the best way to go if there is no standard? Are there other ways > to document a Python API? > > Thanks, > > Scott Huey > The "standard" is to use docstrings i.e., class MyModule: """ This module does something """ def someMethod(self): """ This method does something, accepts args/returns value etc. """ Then one way to view the docstrings is to start a python shell, import your module, and do help(MyModule) i.e., module: mymodule.py class: MyModule do in the shell: import mymodule help(mymodule.MyModule) Then Python will generate a quick help interface for your module. I suspect epydoc uses docstrings but I *may* be wrong, since I have never used epydoc. But a quick look at pydoc (not to be confused with epydoc) which is part of the standard library allows you to generate documentation in HTML format, and/or serve it over web with its built-in HTTP server. pydoc: http://docs.python.org/lib/module-pydoc.html Hope this helps. Adonis From hg at nospam.org Wed Jan 3 08:25:46 2007 From: hg at nospam.org (hg) Date: Wed, 03 Jan 2007 14:25:46 +0100 Subject: array of class / code optimization References: <6UPmh.6785$hr3.92@newsfe24.lga> <4MQmh.145$jr6.14@read3.inet.fi> Message-ID: <7jUmh.25917$9e.12558@newsfe20.lga> Neil Cerutti wrote: > On 2007-01-03, Jussi Salmela wrote: >> hg kirjoitti: >>> mm wrote: >>> >>>> Yes, it was the (), equivalent to thiks like new() create new object >>>> from class xy. >>>>> s1.append(Word) >>>> s1.append(Word()) >>>> >>>> But I was looking for a "struct" equivalent like in c/c++. >>>> And/or "union". I can't find it. >>>> >>>> Maybe you know a source (URL) "Python for c/c++ programmers" or things >>>> like that. >>>> >>>> >>>> Yes, I konw whats an object is... >>> >>> >>> A struct in C is unrelated to a struct in C++ as a struct in C++ _is_ a >>> class. >>> >>> >>> hg >> >> What does your sentence mean, exactly? If I take a C file xyz.c >> containing a struct definition S, say, rename it to be xyz.cpp >> and feed it to a C++ compiler, the S sure remains a struct and >> the C++ compiler has no difficulty in handling it as a struct, >> so ?!? > > That's true. > > But it's also true that > > struct foo { > int x, y; > }; > > is exactly equivalent to: > > class foo { > public: > int x, y; > }; > > The only difference between struct and class in C++ is the > default access specification of its members. > > -- > Neil Cerutti > For those of you who have children and don't know it, we have a nursery > downstairs. --Church Bulletin Blooper And that is what I meant. hg From weekender_ny at yahoo.com Mon Jan 22 02:06:25 2007 From: weekender_ny at yahoo.com (John) Date: 21 Jan 2007 23:06:25 -0800 Subject: class explorer for automating IE In-Reply-To: <1169448532.869501.190530@v45g2000cwv.googlegroups.com> References: <1169448532.869501.190530@v45g2000cwv.googlegroups.com> Message-ID: <1169449585.832667.325370@11g2000cwr.googlegroups.com> Is there an analogue of IE Mechanize in python? http://search.cpan.org/src/ABELTJE/Win32-IE-Mechanize-0.009/README Thanks, --j On Jan 22, 1:48 am, "John" wrote: > I found this class which was written in 2003. > > http://xper.org/wiki/seminar/InternetExplorerAutomation > > Is there a better/more complete version around that someone knows of. > > Thanks, > --j From nmm1 at cus.cam.ac.uk Mon Jan 15 04:02:41 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jan 2007 09:02:41 GMT Subject: Maths error References: In article , Tim Roberts writes: |> "Hendrik van Rooyen" wrote: |> |> >> What I don't know is how much precision this approximation loses when |> >> used in real applications, and I have never found anyone else who has |> >> much of a clue, either. |> >> |> >I would suspect that this is one of those questions which are simple |> >to ask, but horribly difficult to answer - I mean - if the hardware has |> >thrown it away, how do you study it - you need somehow two |> >different parallel engines doing the same stuff, and comparing the |> >results, or you have to write a big simulation, and then you bring |> >your simulation errors into the picture - There be Dragons... |> |> Actually, this is a very well studied part of computer science called |> "interval arithmetic". As you say, you do every computation twice, once to |> compute the minimum, once to compute the maximum. When you're done, you |> can be confident that the true answer lies within the interval. The problem with it is that it is an unrealistically pessimal model, and there are huge classes of algorithm that it can't handle at all; anything involving iterative convergence for a start. It has been around for yonks (I first dabbled with it 30+ years ago), and it has never reached viability for most real applications. In 30 years, it has got almost nowhere. Don't confuse interval methods with interval arithmetic, because you don't need the latter for the former, despite the claims that you do. |> For people just getting into it, it can be shocking to realize just how |> wide the interval can become after some computations. Yes. Even when you can prove (mathematically) that the bounds are actually quite tight :-) Regards, Nick Maclaren. From beej at beej.us Tue Jan 30 04:34:01 2007 From: beej at beej.us (Beej) Date: 30 Jan 2007 01:34:01 -0800 Subject: Help me understand this In-Reply-To: References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> Message-ID: <1170146755.446429.90720@v45g2000cwv.googlegroups.com> On Jan 29, 11:47 pm, Steven D'Aprano wrote: > Outside of a print statement (and also an "except" statement), commas > create tuples. And function calls: >>> 3, (3,) >>> type(3,) >>> type((3,)) But here's one I still don't get: >>> type(2) >>> type((2)) >>> (2).__add__(1) 3 >>> 2.__add__(1) File "", line 1 2.__add__(1) ^ SyntaxError: invalid syntax -Beej From jakub.stolarski at gmail.com Mon Jan 8 05:29:15 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 8 Jan 2007 02:29:15 -0800 Subject: Walking The Right Path References: Message-ID: <1168252155.427645.316470@38g2000cwa.googlegroups.com> Tim Daneliuk napisal(a): > Ah yes, moral philosophy and python all come together... Er, that is to day: > > Imagine you have this situation on a *nix filesystem: > > Symlink A: /foo -> /usr/home > Symlink B: /bar -> /foo/username > > > If I do this: > > import os > print os.path.realpath("/bar") > > I get this (as one would expect): > > /usr/home/username > > However, what if I want to get back the result in this form: > > /foo/username > > > IOW, is there a way to return a symlink-based path which contains > the symlink pointer as is was *defined* not as it expands? > One way (but very ugly): print os.path._resolve_link('/bar') From gagsl-py at yahoo.com.ar Fri Jan 19 11:59:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 13:59:37 -0300 Subject: when format strings attack References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> Message-ID: "Nick Maclaren" escribi? en el mensaje news:eoqr1s$khg$1 at gemini.csx.cam.ac.uk... > In article , > "Gabriel Genellina" writes: > |> > |> Pure Python programs are not affected, but a review of the C > implementation > |> should be made to see if any (variant of) printf is used without a > proper > |> format. Anyway I doubt you could find something, because the > vulnerability > |> is so well known for ages. > > Not really. There are LOTS of vulnerabilities that have been known > for ages and are still legion. The reason that this is unlikely is > that it is both easy to spot and trivial to fix. Yes... Anyway, unless someone actually *do* revise the code, if it's easy or not has no importance. I think that some automated tools were used to find problems, but I don't know if this specific vulnerability was searched. -- Gabriel Genellina From csselo at gmail.com Sat Jan 6 14:35:28 2007 From: csselo at gmail.com (csselo at gmail.com) Date: 6 Jan 2007 11:35:28 -0800 Subject: search mail by date with imaplib Message-ID: <1168112128.062140.308400@v33g2000cwv.googlegroups.com> Hi I am looking for a code sample which searches mail by date with imaplib example: get email from 01.01.2007 to now how can I change imaplib search parameters? From mattheww at chiark.greenend.org.uk Fri Jan 26 13:28:32 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 26 Jan 2007 18:28:32 +0000 (GMT) Subject: assertions to validate function parameters References: Message-ID: Steven D'Aprano wrote: > The less your function does, the more constrained it is, the less > testing you have to do -- but the less useful it is, and the more work > you put onto the users of your function. Instead of saying something > like > a = MyNumericClass(1) > b = MyNumericClass(6) > # more code in here... > # ... > result = f(a, b) > you force them to do this: > a = MyNumericClass(1) > b = MyNumericClass(6) > # more code in here... > # ... > # type-cast a and b to keep your function happy > result = f(int(a), int(b)) > # and type-cast the result to what I want > result = MyNumericClass(result) I have a question for you. Consider this function: def f(n): """Return the largest natural power of 2 which does not exceed n.""" if n < 1: raise ValueError i = 1 while i <= n: j = i i *= 2 return j If I pass it an instance of MyNumericClass, it will return an int or a long, not an instance of MyNumericClass. In your view, is this a weakness of the implementation? Should the author of the function make an effort to have it return a value of the same type that it was passed? -M- From horpner at yahoo.com Sat Jan 20 08:46:25 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 20 Jan 2007 13:46:25 GMT Subject: OT Annoying Habits (Was: when format strings attack) References: Message-ID: On 2007-01-20, Nick Maclaren wrote: > > In article , > "Carroll, Barry" writes: >|> >|> My thanks to Aahz and the others who responded. I also did some >|> Googling on my own. I found out that top-posting is the norm in the >|> e-mail world. Bottom- and inline-posting are the norm in the newsgroup >|> world. =20 > > Sorry, even that is not so. I have been using Email since the 1960s, > and top-posting has been used only by the inconsiderate. ...or the beleaguered. Since my school's IT switched to Exchange, correct email composition is really annoying. The only way to do it is to manually cut into a real editor, and then past back in the entire message. This is not worth the hassle for interoffice communication, since everyone else is stuck with stupid top-posting, too. It's been an interesting journey, from some unix-based terminal email, to Lotus Notes (ARRGH!), then a happy time using IMAP, and now back to (ARRGH!). -- Neil Cerutti From martin at v.loewis.de Mon Jan 8 03:36:02 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 08 Jan 2007 09:36:02 +0100 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <1168243875.143604.269720@q40g2000cwq.googlegroups.com> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <45A1F1D9.8070206@v.loewis.de> <1168243875.143604.269720@q40g2000cwq.googlegroups.com> Message-ID: <45A20272.3020401@v.loewis.de> Frank Millman schrieb: > If there is something wrong with the SQL statement, I do not want to > crash the server, I want to notify the client that there was something > wrong, so that the offending module can be corrected and reloaded. Right. In a distributed system, you should propagate the error (in some form) to the client. Then the question is what the best form is: IMO, you should keep as much information as possible. This means you either return the Python exception to the client, to be re-raised on the client side, or you log the exception on the server side, and just return to the client the information that the full error message has been logged. In any case: this should happen on the middleware layer, i.e. the place that does the communication. Wrt. the OP's code, I still maintain that all of his approaches to "silence" the exception are flawed. Exception handling should either recover from the error (e.g. by adjusting the environment, then retrying) or abort the execution. In a distributed case, "abort the execution" may not mean "terminate the program", but instead "immediately abort execution of the current request and return an error to the client". Regards, Martin From exarkun at divmod.com Wed Jan 10 09:19:22 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 10 Jan 2007 09:19:22 -0500 Subject: maximum number of threads In-Reply-To: Message-ID: <20070110141922.11447.451680748.divmod.quotient.12156@ohm> On Wed, 10 Jan 2007 12:11:59 -0200, Felipe Almeida Lessa wrote: >On 1/10/07, Laurent Pointal wrote: >>This is a system configurable limit (up to a maximum). >> >>See ulimit man pages. >> >>test >> >> ulimit -a >> >>to see what are the current limits, and try with >> >> ulimit -u 2000 >> >>to modify the maximum number of user process (AFAIK each thread use a >>process entry on Linux) > >I don't think it's only this. Indeed you are correct. The actual limit you are hitting is the size of your address space. Each thread is allocated 8MB of stack. 382 threads consumes about 3GB of address space. Even though most of this memory isn't actually allocated, the address space is still used up. So, when you try to create the 383rd thread, the kernel can't find anyplace to put its stack. So you can't create it. Try reducing your stack size or reducing the number of threads you create. There's really actually almost no good reason to have this many threads, even though it's possible. exarkun at charm:~$ python Desktop/test.py 50 100 150 200 250 300 350 Exception raised: can't start new thread Biggest number of threads: 382 exarkun at charm:~$ ulimit -Ss 4096 exarkun at charm:~$ python Desktop/test.py 50 100 150 200 250 300 350 400 450 500 550 600 650 700 750 Exception raised: can't start new thread Biggest number of threads: 764 exarkun at charm:~$ Jean-Paul From cvanarsdall at mvista.com Fri Jan 26 12:30:21 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 26 Jan 2007 09:30:21 -0800 Subject: Mounting shares with python In-Reply-To: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> References: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> Message-ID: <45BA3AAD.5050906@mvista.com> Marcpp wrote: > Hi, when i mount a share with python... > > os.system ("mount -t smbfs -o username=nobody ...") > > the problem is that I'll to be root. > Have a comand to send a root password...? > I've tried > > os.system ("su") > os.system ("the password") > > but it doesn't works. > > I do a lot of that type of stuff. Just setup sudo access for that user and have it state no password. I also do that stuff on remote machines, similarly, setup ssh such that you don't need to use a password. It will work :) -c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From michele.simionato at gmail.com Fri Jan 5 11:01:17 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 5 Jan 2007 08:01:17 -0800 Subject: program deployment In-Reply-To: <1168010377.179056.220500@s80g2000cwa.googlegroups.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> Message-ID: <1168012877.398078.59120@s80g2000cwa.googlegroups.com> king kikapu wrote: > > > Are they embarassed by their code? > > hehehe...no, just worried about stealing their ideas... I believe that shipping just the bytecode is a pretty effective way to stop 99% of programmers from reading your code. Yes, in theory they could decompile it, but in practice, programmers are lazy. Look, I am so lazy that usually I don't read the source code, even if it is there in plain! Of course, if you only ship the bytecode and your code has bugs, the tracebacks will be less explicit and it will be more difficult for you to support your users. Also, you will stop the users that could fix the bug for you from doing so and you will rule out the possibility of getting help for free. Think about that. If it was that easy to steal non-trivial ideas from the source code, we will not complain all the time about about how difficult is to understand the code written by others. Michele Simionato From robert.kern at gmail.com Wed Jan 17 20:44:29 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 17 Jan 2007 19:44:29 -0600 Subject: Units of measurement In-Reply-To: <1169082689.148793.312130@51g2000cwl.googlegroups.com> References: <7x8xg1xr62.fsf_-_@ruckus.brouhaha.com> <1169082689.148793.312130@51g2000cwl.googlegroups.com> Message-ID: Russ wrote: > Robert Kern wrote: >> And there was another one announced here sometime in the past year or so, IIRC, >> but I don't recall the name of it or that of the author. :-( > > Perhaps you are referring to the scalar class at > http://RussP.us/scalar.htm Yup, you're the one. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From vgvr620034 at gmail.com Wed Jan 17 09:31:23 2007 From: vgvr620034 at gmail.com (raghu) Date: 17 Jan 2007 06:31:23 -0800 Subject: How can i eval subindex on list[ ][ ] ? In-Reply-To: References: <1168988937.512029.192800@q2g2000cwa.googlegroups.com> Message-ID: <1169044283.798684.220660@11g2000cwr.googlegroups.com> its working for me i think its better to mention the value of i and j for both lists or you might have done mistake while formatting strings it should be %s for strings and %d for numbers if any subelement in lists does not formatted properly it may lead to error From beej at beej.us Sun Jan 28 21:50:52 2007 From: beej at beej.us (Beej) Date: 28 Jan 2007 18:50:52 -0800 Subject: IP address In-Reply-To: References: Message-ID: <1170039052.541186.326990@j27g2000cwj.googlegroups.com> On Jan 28, 2:26 am, Klaus Alexander Seistrup wrote: > Scripter47 wrote: > > How do i get my ip address? > > > in cmd.exe i just type "ipconfig" then it prints: > > ... > > IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 > > ... > > how can i do that in python??#v+ > > python -c 'import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' This is extremely unlikely to return 192.168.1.10. :-) (It will give you the address of your firewall or whatever is your gateway to the outside world... which is a cool thing to know, but I'm not sure it's what the op's after.) -Beej From chrisspen at gmail.com Sat Jan 13 11:54:56 2007 From: chrisspen at gmail.com (Chris) Date: 13 Jan 2007 08:54:56 -0800 Subject: AlphaBeta Search In-Reply-To: <1168693959.611167.80050@s34g2000cwa.googlegroups.com> References: <1168649650.163717.263240@38g2000cwa.googlegroups.com> <1168693959.611167.80050@s34g2000cwa.googlegroups.com> Message-ID: <1168707293.848867.264050@q2g2000cwa.googlegroups.com> bearophileH... at lycos.com wrote: > Chris wrote: > > I know this probably seems trivial, but I can't seem to find the bug in > > my alphabeta search implementation. > > This is another alphabeta implementation (all the nicest algorithms are > inside this AIMA codebase): > http://aima.cs.berkeley.edu/python/games.html > > Later when you program works you can find this helpful to improve your > algorithm: > http://citeseer.ist.psu.edu/11954.html Thanks. I actually already knew about the AIMA implementation, and used that and an alternative version on wikipedia to fix my code. It turns out my heuristic_value function was incorrect. I've also managed to get it working with a transposition table, which has really sped things up. From shanugulati at gmail.com Sun Jan 28 03:54:15 2007 From: shanugulati at gmail.com (Shaine) Date: 28 Jan 2007 00:54:15 -0800 Subject: New Way to Search the Information - Ogleo.com - An Integrated Search Message-ID: <1169974455.636306.257550@p10g2000cwp.googlegroups.com> We have just launched a new Search Tool - http://www.ogleo.com Kindly have a look and give us your suggestions here: Ogleo Discussion Forum http://forum.ogleo.com Links: ====== Ogleo Home Page - http://www.ogleo.com Ogleo Traffic Details - http://ogleo.com/traffic Ogleo Discussion Forums - http://forum.ogleo.com About Ogleo.com =============== Ogleo.com is an integrated search tool which integrates various services to serve best of the web to its users. Ogleo word has been derived from word Ogle \O"gle\, n, which means to look at. At this time we have integrated 5 different services in Ogleo.com i.e. Web Results, Questions and Answers, Dictionary Definitions, Encyclopedia Content and Images. Our Mission Ogleo's aim is to integrate the information which is available with various content providers so that anyone can access the world's information in a single click. Future Plans In future we have planned to integrate more services in Ogleo.com e.g. News, Shopping, Photos, Videos, Whois, Jobs, Directories, Groups and Yellow Pages etc. ===Please don't forget to forward this message to your friends=== ALSO DON'T FORGET TO MAKE OGLEO.COM YOUR HOME PAGE Thanks Ogleo.com Team From bearophileHUGS at lycos.com Thu Jan 18 06:01:17 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Jan 2007 03:01:17 -0800 Subject: A note on heapq module In-Reply-To: References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <45ad0f6c$1@nntp0.pdx.net> <1168982702.903306.152940@m58g2000cwm.googlegroups.com> Message-ID: <1169118077.035345.321580@11g2000cwr.googlegroups.com> Neil Cerutti: > One more idea, cribbed from the linked list thread elsewhere: it > might be nice if your Heap could optionally use an underlying > collections.deque instead of a list. > I don't know how excellent Python's deque is, but it's possible a > deque would provide a faster heap than a contiguous array. C++'s > std::deque is the default implementation of C++'s > std::priority_queue for that reason (unless I'm confused again). If you have some minutes you can do few speed tests and show us the code and the timing results... Bye, bearophile From collinstocks at gmail.com Fri Jan 5 17:59:11 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Fri, 5 Jan 2007 17:59:11 -0500 Subject: I will be proposing this PEP Message-ID: <4c0048df0701051459m7abf0662r69060ce9faff6bc4@mail.gmail.com> Attached is a PEP which I will be proposing soon. If you have any questions, comments, or suggestions, please email them to me with the subject "Adding Built-in Class Attributes PEP" -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- PEP: XXX Title: Adding Built-in Class Attributes Version: $Revision$ Last-Modified: $Date$ Author: Collin Stocks Status: Draft Type: Standards Track Content-Type: text/plain Created: 03-Jan-2007 Python-Version: 2.6 Post-History: Abstract Python currently allows users to create their own __setattr__, __getattr__ and __delattr__ member functions inside a class. This is all well and dandy, but it causes programmers to have to find a different way to set, get, and delete attributes within those functions. In __delattr__ and __getattr__, this usually is not a problem, because you can just get or delete those from __dict__, the built-in dictionary in a class. __setattr__ is more of a problem, because, if self.my_attr does not exist, self.__dict__['my_attr']="some value" raises an exception. This PEP proposes to add __setattr__, __getattr__ and __delattr__ as built-in member functions of all Python class objects. Rationale Many programs that use classes need to create their own __setattr__, __getattr__ and __delattr__ member functions. If not done carefully, this can cause recursion errors (something that increases the learning curve for newbies). This is also not very object oriented. Really, does it make sense to use objects of two different types to refer to the same object? This PEP does not propose to remove __dict__, just to add a more sensical way to access the attributes of a class. This will prevent recursion, make Python code make more sense and introduce a more object oriented and correct way of handling class attributes. Specification: Any class created by a Python file will have the __setattr__, __getattr__ and __delattr__ member functions built into it upon initiation. This would allow programmers to create copies of these functions, and then create their own, which call on the copies in order to change attributes. For example, suppose you wanted to make the attribute readOnlyAttr read-only: In the current version of Python, you must do something like this: class blah: def __init__(self): self.readOnlyAttr=1 def __setattr__(self,name,value): try: assert name=="readOnlyAttr" print 1 self.__dict__[name] print 2 raise TypeError, "Cannot change a readonly attribute" except KeyError: self.__dict__[name]=value except AssertionError: self.__dict__[name]=value The downside to this is obvious: This is an enormous amount of code to do a simple thing, and must be cleverly thought out. Most would say that this is not Pythonic. Here is what that code would look like following this proposal: class blah: def __init__(self): self.readOnlyAttr=1 self.save_setattr=self.__setattr__ #makes a copy of the # previous, built-in __setattr__() def __setattr__(self,name,value): #this function is created # after __init__() has been called if name=="readOnlyAttr": raise TypeError, "Cannot change a readonly attribute" else: self.save_setattr(name,value) This code is much smaller and more readable. It also does not use __dict__[], which is a dictionary representation of the class. Since blah().__dict__ and blah() refer to the same object in the current version of Python, we are not able to take full advantage of object orientation, because this causes class objects to really have two different types. This PEP does not propose to remove __dict__[] (maybe in Python 3000 __dict__[] will be removed); It just proposes a way to take a fuller advantage of object orientation. Another example: Suppose you wanted to create your own __setattr__() member function, but you were deriving your class from another class that may or may not have that member function already. Suppose also, that you want to use that function after filtering through your own __setattr__() member function. This is how that might be done in the current version of Python: class blah(derivitive): def __init__(self): try: self.save_setattr=self.__setattr__ self.__setattr__=self.new_setattr except: self.__setattr__=self.new_setattr def new_setattr(self,name,value): #... #code block #... try: self.save_setattr(name,value) except: self.__dict__[name]=value The obvious downside to this, is again, that it is too long, and it is not pythonic. It is in fact, quite the reverse: clever. A newbie would never think up that code! Here is what that code would look like following this proposal: class blah(derivitive): def __init__(self): #this saves a copy of the old __setattr__ # member function, whether it is the original # built-in one, or the one that was derived self.save_setattr=self.__setattr__ def __setattr__(self,name,value): #this function is created after # __init__() has been called #... #code block #... self.save_setattr(name,value) #this calls the previously # active __setattr__() member function This code is also much smaller and more readable! Better yet, it looks almost exactly the same as the proposed code in the last example! All a newbie needs to see is one example of how to use the __setattr__() member function, and s/he is able to make it do whatever s/he wants, without having to learn all about the try/except blocks, or even much about manipulating function objects. This proposal also applies the same concept to the __getattr__() and __delattr__() member functions. Here is an example class that follows through with the same concept as before: class blah(derivitive): def __init__(self): self.save_setattr=self.__setattr__ self.save_getattr=self.__getattr__ self.save_delattr=self.__delattr__ def __setattr__(self,name,value): #this function is created after # __init__() has been called #... #code block #... self.save_setattr(name,value) #this calls the previously active # __setattr__() member function def __getattr__(self,name): #this function is created after # __init__() has been called #... #code block #... return self.save_getattr(name) #this calls the previously # active __getattr__() member function def __delattr__(self,name): #this function is created after # __init__() has been called #... #code block #... self.save_delattr(name) #this calls the previously active # __delattr__() member function This is so much simpler than in the current version of python! This proposal avoids recursion, and gives a more logical and direct way to get around the problems caused by __getattr__(), __setattr__() and __delattr__(). Something that has not been mentioned previous to this, but was shown in the examples, was that __init__() was called BEFORE the functions __getattr__(), __setattr__() and __delattr__() below it were created. This sort of turns __init__() into a "magic" member function, as it is called after everything above it was created, and before the aforementioned member functions below it were created. This may cause some incompatability issues which will be resolved later under . Motivation: In the current version of Python, the problems caused by __getattr__(), __setattr__() and __delattr__() are a pain to get around. For example, when they are created, they immediatly overwrite any __getattr__(), __setattr__() or __delattr__() member functions that were derived from other classes. As shown in the specification, there are ways to get around this, but they are very newbie unfriendly; they require a much more detailed knowledge of the language to find. This PEP proposes a way in which it takes a minimal knowledge of Python in order to be able to write classes which take advantage of the __getattr__(), __setattr__() and __delattr__() member functions. Also, in the current version of Python, __getattr__(), __setattr__() and __delattr__() are easy causes of recursion errors. This PEP proposes a way in which it is more difficult to make the mistake of causing a recursion error. And, since the code needed to make __getattr__(), __setattr__() and __delattr__() work is less, if a recursion error is caused, it is much easier to find and fix than with the current version of Python. Backwards Compatability: Since __init__() in class objects is called before any __getattr__(), __setattr__() and __delattr__() member functions that appear below it are created, the following things done by __init__() may not behave as expected in older programs: setting an attribute getting an attribute deleting an attribute referencing __getattr__(), __setattr__() and __delattr__() member functions These incompatabilities, however, are only a problem if __getattr__(), __setattr__() and/or __delattr__() have been written below where the __init__() member function has been written. A solution that comes to mind is to evaluate, but not run, __init__() to see if there are still any references to each of the original (meaning built-in or derived) __getattr__(), __setattr__() and __delattr__() member functions. For each one, if there still is a reference, then the the original member function is kept; if there isn't still a reference, then the original member function is discarded, and the new member function is used in its place. The __init__() function is then called with the decided class namespace. This is only a minor incompatability, and others are welcome to suggest their own solutions to this problem. Another possible solution to this problem is to simply leave __init__() alone, and include another special member functions of all classes that is called immediately after all of the functions above it have been created, but before any of the code below it has been interpreted. This function's name would be __setup__(). This is a fitting name, because it is able to control the way that the class is created, before the class has initialized. This only leaves a minute incompatability, if someone for some reason decided in an older program to put the __setup__() function in their class. Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End: From steveo at syslang.net Tue Jan 9 13:23:49 2007 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 9 Jan 2007 13:23:49 -0500 (EST) Subject: Question about using "with" Message-ID: >From the tutorial, they said that the following construct will automatically close a previously open file descriptor: ------------------- #! /usr/bin/python import sys for nn in range ( 1, len(sys.argv ) ): print "arg ", nn, "value = ", sys.argv[nn] with open(sys.argv[nn]) as f: for line in f: print line, ------------------ but when I run it (with args) I get: 591 > ./cat.py cat.py File "./cat.py", line 6 with open(sys.argv[nn]) as f: ^ SyntaxError: invalid syntax 592 > This example came from http://docs.python.org/tut/node10.html down in section 8.7 Am I missing something? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From dakman at gmail.com Mon Jan 22 10:06:02 2007 From: dakman at gmail.com (dakman at gmail.com) Date: 22 Jan 2007 07:06:02 -0800 Subject: module check In-Reply-To: <1169477715.178874.223290@51g2000cwl.googlegroups.com> References: <1169477715.178874.223290@51g2000cwl.googlegroups.com> Message-ID: <1169478362.573925.37760@l53g2000cwa.googlegroups.com> I'm at work so I can't test this, but I do beleive the inspect module can help you out. If it can't you can always try import the module in a try-catch statement, catching ImportError, however ImportError may be raised if the module you imported has trouble loading another module, but it shouln't be to hard to track down where the ImportError came from, a traceback object can give a lot more information than you would beleive. Victor Polukcht wrote: > Can anybody suggest a correct way of checking in python module exists > and correctly installed from python program. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 31 12:29:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 31 Jan 2007 18:29:04 +0100 Subject: Python **kwargs ? In-Reply-To: <1170263432.199403.175290@k78g2000cwa.googlegroups.com> References: <1170263432.199403.175290@k78g2000cwa.googlegroups.com> Message-ID: <45c0d194$0$6737$426a74cc@news.free.fr> johnny a ?crit : > What is **kwargs mean in python? When you put double **, does it mean > passing by reference? Nope. Python as support for both positional (*args) and named (**kwargs) varargs. > For example: > def redirect_to(request, url, **kwargs): means that redirect_to expect a positional 'request' arg, a positional 'url' argument, and any other arbitrary named arguments. You'll find all relevant doc in the FineManual(tm): http://www.python.org/doc/current/tut/node6.html#SECTION006720000000000000000 HTH From kloro2006 at gmail.com Sat Jan 27 21:32:29 2007 From: kloro2006 at gmail.com (tom arnall) Date: Sat, 27 Jan 2007 18:32:29 -0800 Subject: working model of a microcoded computer Message-ID: <45c3b3a0$0$16272$88260bb3@free.teranews.com> This is somewhat off topic, but I think many programmers would be interested to look at a working model of a microcoded computer at: ? ? ? ? tomspages.com ? ? ? ? click on the link for 'Hack the Com puter Model.' It conveys among other things the physical events that underlie execution of a microcode instruction and, by extension, of machine language. I would like very much to get people's feedback on the thing. Thanks, tom arnall north spit, ca usa -- Posted via a free Usenet account from http://www.teranews.com From bignose+hates-spam at benfinney.id.au Fri Jan 19 20:37:06 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 Jan 2007 12:37:06 +1100 Subject: float comparison confusion References: <1169250923.146916.206430@s34g2000cwa.googlegroups.com> Message-ID: <87odou4gxp.fsf@benfinney.id.au> "chrolson at gmail.com" writes: > Type "help", "copyright", "credits" or "license" for more information. > >>> cmp(20.10, 20.9) > -1 > > Why is cmp returning -1 instead of returning positive integer? >>> 20.10 < 20.9 True >>> 20.1 < 20.9 True >>> 20.10 == 20.1 True What leads you to expect otherwise? -- \ "A society that will trade a little liberty for a little order | `\ will lose both, and deserve neither." -- Thomas Jefferson, in | _o__) a letter to Madison | Ben Finney From deets at nospam.web.de Wed Jan 3 10:53:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Jan 2007 16:53:22 +0100 Subject: C/C++, Perl, etc. to Python converter References: Message-ID: <5021riF1e2347U1@mid.uni-berlin.de> mm wrote: > > Is there a Perl to Python converter? > Or in general: a XY to Python converter? > > Is see, that Python is much better then Perl anyway. > But for beginners, they whant to konw how is this done with Python etc. > > Sure, there are some docus out there in the internet. But a converter? Nope. Different languages have different idioms, translating them to each other - while technically possible, at least to some extend - won't result in anything that a human being can work with. Diez From david at boddie.org.uk Wed Jan 24 16:43:42 2007 From: david at boddie.org.uk (David Boddie) Date: 24 Jan 2007 13:43:42 -0800 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: <45b69f63$0$24463$88260bb3@free.teranews.com> Message-ID: <1169675022.054728.76610@a75g2000cwd.googlegroups.com> On Jan 24, 11:54 am, Harry George wrote: > It is all interpretation -- even after some cases have wandered > through the courts. Mostly the trolltech statements indicate their > intent to sue. That right there tells me I want to go elsewhere. Well, one could alternatively read the GPL, look at the FSF FAQs, consult a lawyer, or talk to the Trolltech salespeople. I'd suggest to the original poster that they do one or more of those things instead of relying on your interpretation and guesswork. David From steve at REMOVE.THIS.cybersource.com.au Sat Jan 13 14:09:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 14 Jan 2007 06:09:09 +1100 Subject: Boilerplate in rich comparison methods References: <7x8xg71j3t.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 12 Jan 2007 23:28:06 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> class Parrot: >> def __eq__(self, other): >> return self.plumage() == other.plumage() >> def __ne__(self, other): >> return self.plumage() != other.plumage() >> def __lt__(self, other): >> return self.plumage() < other.plumage() [snip more boilerplate code] > If it's that uniform I think you can just use __cmp__: Good point -- I had somehow picked up the mistaken idea that __cmp__ was depreciated in favour of rich comparisons. -- Steven. From dfh at forestfield.co.uk Wed Jan 3 06:45:08 2007 From: dfh at forestfield.co.uk (David Hughes) Date: 3 Jan 2007 03:45:08 -0800 Subject: Using codecs.EncodedFile() with Python 2.5 Message-ID: <1167824708.700486.249020@h40g2000cwb.googlegroups.com> I used this function successfully with Python 2.4 to alter the encoding of a set of database records from latin-1 to utf-8, but the same program raises an exception using Python 2.5. This small example shows the problem: import codecs fo = open('test.dat', 'w') fo.write('G\xe2teaux') fo.close() fi = open("test.dat",'r') fx = codecs.EncodedFile(fi, 'utf-8', 'latin-1') astring = fx.readline() print astring ustring = unicode(astring, 'utf-8' ) print repr(ustring) print ustring.encode('latin-1') print ustring.encode('utf-8') Python 2.4 gives: G??teaux u'G\xe2teaux' G?teaux G??teaux which I believe is correct, while 2.5 produces Traceback (most recent call last): File "test_codec.py", line 8, in astring = fx.readline() File "C:\Python25\lib\codecs.py", line 709, in readline data = self.reader.readline() File "C:\Python25\lib\codecs.py", line 471, in readline data = self.read(readsize, firstline=True) File "C:\Python25\lib\codecs.py", line 418, in read newchars, decodedbytes = self.decode(data, self.errors) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-3: invalid data Is there a genuine problem here, or have I been misusing this function? -- Regards David Hughes From joshua at eeinternet.com Fri Jan 5 19:44:01 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Fri, 05 Jan 2007 15:44:01 -0900 Subject: Doing date/time + TZ math in python Message-ID: <459ee41c$0$4805$88260bb3@free.teranews.com> I've read docs (datetime, time, pytz, mx.DateTime), googled, and experimented. I still don't know how to accomplish what I want to accomplish. I'm loading up a bunch of date/time data that I then need to do math on to compare it to the current date/time. I can get the current time easily enough: currentTime = datetime.datetime.now(pytz.timezone('America/Anchorage')) Then, I want to import data/time pairs that are in "%Y-%m-%d %H:%M:%S" format. So, I do: For each loop, extract time data, blah, blah, then: readingTime = datetime.datetime(rYr, rMo, rDay, rHr, rMin, rSec, tzinfo=pytz.timezone('America/Anchorage')) The problem is, how do I create a datetime object and tell it that it's America/Anchorage *daylight savings time* instead of whatever the system is currently set at? pytz only has America/Anchorage, and I saw no way to tell it explicitly that the timezone is in Daylight instead of Standard time (e.g. using AKST vs. AKDT for the time zone). I'm sure there is a way to do it, and I'm sure it's quite simple, but it hasn't jumped out at me yet. Is there a module that I haven't seen that would be better suited for this? Thanks! j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From gert.cuykens at gmail.com Mon Jan 15 19:48:05 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Tue, 16 Jan 2007 01:48:05 +0100 Subject: for v in l: Message-ID: is there a other way then this to loop trough a list and change the values i=-1 for v in l: i=i+1 l[i]=v+x something like for v in l: l[v]=l[v]+x From codecraig at gmail.com Wed Jan 24 12:18:38 2007 From: codecraig at gmail.com (abcd) Date: 24 Jan 2007 09:18:38 -0800 Subject: Thoughts on using isinstance In-Reply-To: References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> Message-ID: <1169659118.685902.197390@v45g2000cwv.googlegroups.com> Well my example function was simply taking a string and printing, but most of my cases would be expecting a list, dictionary or some other custom object. Still propose not to validate the type of data being passed in? Thanks. From __peter__ at web.de Tue Jan 2 04:16:30 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Jan 2007 10:16:30 +0100 Subject: doctesting References: Message-ID: belinda thom wrote: > I'd like to write a tester script that I can place in one place (say > ~/bin/python/tester.py) and then have it visible to me at the cmd- > line (by setting the path variable appropriately). I have had no > luck in getting it to work, however. > > It appears like the doctest code itself assumes that all modules to > be imported lie in some directory other than the one I invoked the > tester.py script from. In particular, simple imports in a .txt file > like: > > >>> import foo > > fail even though I've started the script in a directory that contains > file foo.py > > I only achieve success when I manually copy tester.py into this same > directory (symlinks don't fix the problem). > > This is a real drag b/c it means I have to copy this tester.py > routine into _every_ directory that contains a .txt python unit test > file. From a code-reuse point of view, this is pretty hideous... For an executable script to be reachable its path must be listed in the PATH environment variable whereas Python's import mechanism relies on PYTHONPATH (and ultimately on sys.path). http://docs.python.org/tut/node8.html#SECTION008110000000000000000 Peter From not at set.se Tue Jan 23 18:09:07 2007 From: not at set.se (Daniel) Date: Wed, 24 Jan 2007 00:09:07 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? References: Message-ID: I've downloaded both the wxPython and the PyQt4 package, and by the first impression I must say that the PyQt4 system had a very compelling presentation. From what I can understand from the feedback I've gotten so far is that the wxPython is a better choice when it comes to compability (with linux), and it's free even if I want to create applications and sell them. So, from what I understand I will have to go with PyQt4 since (from my understanding): 1. I will not sell the applications I'm working with since they will only be used by the internal QA at a computer game company. 2. There seems to be a lot of documentation available for PyQt4. 3. PyQt4 seems to be easier to learn. 4. My programs does not need to support Linux or Unix. Or am I wrong? Flame people, for the love of God, flame!! :) -Daniel From researchbase at gmail.com Fri Jan 19 08:18:13 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Fri, 19 Jan 2007 18:48:13 +0530 Subject: confused on python rpc with apache, is it possible? Message-ID: hello all. I will like to know if the following combination is possible. I have looked around on google and did not find any thing productive so bothering the list: sorry. I am developing a distributed application which will have 3 layers namely the thin client written in wxpython, an application layer on a server and a database server of course. database and application server will be on same physical machine. what I want to know is if I can use python as the base for developing the application layer as an rpc server and use apache server to handle http remote procedure requests from the client? if yes then what basic configuration settings I will need? I believe I must first have apache recognise python interpreter and then do some settings in apache so that it knows that what is happening is not a web page request but an xml-rpc application created in python. can some one guide me? thanks Krishnakant. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 11 12:11:06 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 11 Jan 2007 18:11:06 +0100 Subject: Learning Python book, new edition? References: Message-ID: <50n9daF1g30l4U1@mid.individual.net> Demel, Jeff wrote: > Does anyone know if there's a plan in the works for a new edition > of Learning Python? The current edition (2nd) is a few years old > and looks like it only covers Python 2.3. IIRC, differences to 2.4 are in it, too. > This email is intended only for the individual or entity to which > it is addressed. Mails are _by_definition_ intended only for the addressee. :) Regards, Bj?rn -- BOFH excuse #57: Groundskeepers stole the root password From richfahey at gmail.com Wed Jan 24 14:26:09 2007 From: richfahey at gmail.com (Rich) Date: 24 Jan 2007 11:26:09 -0800 Subject: newbie - returned values from cscript.exe Message-ID: <1169666769.242698.70730@j27g2000cwj.googlegroups.com> I am writing my first python script and I'm guessing this is something obvious but I can't find any examples of doing something like this. I have a python script that is running a vbscript through cscript.exe. The vbscript looks up a server name, username, password etc and returns these values in a delimited list using wscript.echo. I can assign these values to variables using a Windows batch files with the following code FOR /F "tokens=1-6" %%a in ('cscript /nologo GetServerAccessInfo.vbs"') do ( SET DB_SERVER_NAME=%%a SET DB_NAME=%%b SET NMDBO_USERNAME=%%c SET NMDBO_PASSWORD=%%d SET SU_USERNAME=%%e SET SU_PASSWORD=%%f I can't figure out how to do the same thing using a python script to call this instead of a batch file. I am running the vbscript by using the following command os.system('cscript /nologo GetServerAccessInfo.vbs') From CRhode at LacusVeris.com Mon Jan 8 11:12:01 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Mon, 8 Jan 2007 10:12:01 -0600 Subject: help: code formatter? In-Reply-To: References: Message-ID: <20070108161200.GA5048@loki> siggi wrote this on Mon, Jan 08, 2007 at 03:33:21PM +0100. My reply is below. > Is there a simple code formatter that first removes all indentations > and then refomats correctly? Why, yes, there is: http://lacusveris.com/PythonTidy/PythonTidy.python -- .. Chuck Rhode, Sheboygan, WI, USA .. 1979 Honda Goldwing GL1000 (Geraldine) .. Weather: http://LacusVeris.com/WX .. 26? ? Wind W 17 mph From gheissenberger at gmail.com Thu Jan 11 18:42:07 2007 From: gheissenberger at gmail.com (gheissenberger at gmail.com) Date: 11 Jan 2007 15:42:07 -0800 Subject: Python nuube needs Unicode help In-Reply-To: <50nv1uF1hje7oU1@mid.uni-berlin.de> References: <1168550858.233814.292900@p59g2000hsd.googlegroups.com> <50nv1uF1hje7oU1@mid.uni-berlin.de> Message-ID: <1168558927.031778.240940@i56g2000hsf.googlegroups.com> Progress! You managed to change the error message. File "./acc_test_script_generator.py", line 106, in loadData print u.encode('utf-8') AttributeError: Utterance instance has no attribute 'encode' I'm missing somethign really obvious here, but I don't know what it is... Diez B. Roggisch wrote: > gheissenberger at gmail.com schrieb: > > HELP! > > Guy who was here before me wrote a script to parse files in Python. > > > > Includes line: > > print u > > where u is a line from a file we are parsing. > > However, we have started recieving data from Brazil. If I open file to > > parse in VI, looks like: > > > > > audio="313-20070102144528.wav" grammarSet="G3" rawText="não" > > recValue="{data:CHOICE=NO;}" conf="970" rawText2="" conf2="0" > > transcribedText="não" parsableText="não"/ > > > > Clearly those "nã" are some non-Ascii characters, but how do I get > > print to understand that? > > > > I keep getting: > > "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in > > position 40: > > ordinal not in range(128)" > > > > Does the error happen at the > > print u > > line? If yes, what happens is that you try and print a unicode object. > Which means that it has to be converted (actually the right term is > encoded) to a byte-string. If you don't do that explicitely, it will be > done implicitly, using the default encoding - which is ascii. > > If you have non-ascii characters, you end up with the error you see. > > What to do? Use something like this: > > print u.encode('utf-8') > > instead. > > Diez From bthom at cs.hmc.edu Fri Jan 5 04:11:02 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Fri, 05 Jan 2007 01:11:02 -0800 Subject: checking one's type In-Reply-To: <7.0.1.0.0.20070105060049.05c1e270@yahoo.com.ar> References: <7.0.1.0.0.20070105060049.05c1e270@yahoo.com.ar> Message-ID: <2E261C28-2E4A-413D-91B0-34D04B160821@cs.hmc.edu> thanks :-) On Jan 5, 2007, at 1:05 AM, Gabriel Genellina wrote: > At Friday 5/1/2007 05:40, belinda thom wrote: > >> I've been using the following hack to determine if a type is >> acceptable and I suspect there is a better way to do it: > > This has been discussed today under the thread "Set type?", and a > few days ago as "type classobj not defined". > > > -- > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ Pregunt?. > Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni > imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http:// > www.yahoo.com.ar/respuestas > -- > http://mail.python.org/mailman/listinfo/python-list From http Thu Jan 25 07:35:13 2007 From: http (Paul Rubin) Date: 25 Jan 2007 04:35:13 -0800 Subject: My Tkinter Threading nightmare References: <1169693266.209082.323310@a75g2000cwd.googlegroups.com> <7x1wljajgg.fsf@ruckus.brouhaha.com> <7xac07wzh2.fsf@ruckus.brouhaha.com> <1169726320.703566.272120@k78g2000cwa.googlegroups.com> Message-ID: <7xejpjuvwe.fsf@ruckus.brouhaha.com> half.italian at gmail.com writes: > > try: > > func, args, kw = self.cmd_queue.get(block=False) > > except QueueEmpty: > > return > > func (*args, **kw) > > Thanks Paul. That has made more sense than all of my scrounging > combined, but I still need to mess around with the idea and code some. > How can I put something like the window delete into the command queue? > Isn't window.protocol() just binding the close window button to a > function? self.progressWindow.protocol('WM_DELETE_WINDOW', self.callback) becomes gui.cmd_queue.put(self.progressWindow.protocol, ('WM_DELETE_WINDOW', self.callback)) where gui is the Window object containing your gui. I think there are some recipes like this in ASPN, that give more detail about how to do this stuff. From webb.sprague at gmail.com Thu Jan 4 13:48:00 2007 From: webb.sprague at gmail.com (_) Date: 4 Jan 2007 10:48:00 -0800 Subject: Set type? Message-ID: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> How do you check to see if a variable is a set? I would like to use if type(var) is types.SetType: blah but that is not available in types module. I am using 2.4 From joncle at googlemail.com Fri Jan 5 07:29:14 2007 From: joncle at googlemail.com (Jon Clements) Date: 5 Jan 2007 04:29:14 -0800 Subject: Encoding / decoding strings In-Reply-To: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> Message-ID: <1168000154.045319.122840@s34g2000cwa.googlegroups.com> oliver at obeattie.com wrote: > Hey Everyone, > > Was just wondering if anyone here could help me. I want to encode (and > subsequently decode) email addresses to use in URLs. I believe that > this can be done using MD5. > > I can find documentation for encoding the strings, but not decoding > them. What should I do to encode =and= decode strings with MD5? > > Many Thanks in Advance, > Oliver Beattie Depends what you mean by "encode email addresses to use in URLs". MD5 is a cryptographic one-way hash function; it creates a 'finger print' of the input data: given this, it's impossible to reproduce the original input. Is this what you're looking for? >>> import urllib >>> urllib.quote('some.person at somedomain.com') 'some.persons%40somedomain.com' hth Jon. From asn_update at adobe.com Mon Jan 15 05:44:10 2007 From: asn_update at adobe.com (asn_update at adobe.com) Date: Mon, 15 Jan 2007 12:44:10 +0200 Subject: Mail System Error - Returned Mail Message-ID: The original message was received at Mon, 15 Jan 2007 12:44:10 +0200 from adobe.com [142.121.237.185] ----- The following addresses had permanent fatal errors ----- python-list at python.org ----- Transcript of session follows ----- ... while talking to 184.246.123.62: 554 ... Message is too large 554 ... Service unavailable From ian.inglis at gmail.com Thu Jan 18 09:12:17 2007 From: ian.inglis at gmail.com (Cruelemort) Date: 18 Jan 2007 06:12:17 -0800 Subject: Catching wx events Message-ID: <1169129536.879657.113130@v45g2000cwv.googlegroups.com> Hello all, I am new to this group (and new to Python) and was hoping someone would be able to help me with something, it is not so much a problem it is more of a general interest query about something i have a solution too but am not sure it is the correct one. I have a class that contains a string ID and a name, and a list containing a few objects of this type, i need to loop through this list and create a button for each object (with the name as the label) i have done this with the following code - for chan in self._channellist: channelbutton = wx.Button(self, id=-1, label=chan.getName()) channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged) My question is this - in the _channelChanged method, how do i know which button has been pressed when i enter the channel changed method, and so how do i retrieve the appropriate object depending on which button has been pressed? I have potentially solved this problem using the UserData property in a sizer, i have added all the buttons to a sizer for display purposes and so SizerItem objects have been created, i can then set the original object to the UserData object by putting the following line of code in the loop sizeritem = self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan) This way i can retrieve the item in the _channelChanged method with the following - def _channelChanged(self, event): eventobj = event.GetEventObject() chan = self.topsizer.GetItem(eventobj).GetUserData() This works fine but by looking at the API it would appear the UserData property is not really designed for this use ("userData - Allows an extra object to be attached to the sizer item, for use in derived classes when sizing information is more complex than the proportion and flag will allow for"). Another option would be to derive my own Button class and include the object in there. Any advice on the best way to solve this problem would be appreciated. Many thanks Ian From ptmcg at austin.rr.com Thu Jan 25 23:07:16 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Jan 2007 20:07:16 -0800 Subject: Pyparsing - Dealing with a Blank Value In-Reply-To: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> References: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> Message-ID: <1169784435.941039.269240@k78g2000cwa.googlegroups.com> On Jan 25, 7:13 pm, "Steve" wrote: > Hi All, > > I've picked up thePyParsingmodule and am trying to figure out how to > do a simple parsing of some HTML source code. My specific problem is > dealing with an element that is blank. > > > Any assistance would be greatly appreciated! > > Steve Just define a default value to be returned for MultiItem if the Optional expression is not found: MultiItem = Optional(OneOrMore(dataItem),default="") Define default to be whatever string you choose. -- Paul From steveo at syslang.net Tue Jan 9 12:56:46 2007 From: steveo at syslang.net (Steven W. Orr) Date: Tue, 9 Jan 2007 12:56:46 -0500 (EST) Subject: Question about compiling. Message-ID: I *just* read the tutorial so please be gentle. I created a file called fib.py which works very nicely thank you. When I run it it does what it's supposed to do but I do not get a resulting .pyc file. The tutorial says I shouldn't do anything special to create it. I have machines that have both 2.4.1 and 2.3.5. Does anyone have an idea what to do? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From gagsl-py at yahoo.com.ar Tue Jan 30 19:15:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 21:15:55 -0300 Subject: Why don't have an object() instance a __dict__ attribute by default? References: <004c01c744c6$c2cf5710$8600a8c0@ANNA> Message-ID: En Tue, 30 Jan 2007 20:31:26 -0300, L?tez? escribi?: > I use Python 2.5, Win32 MSI release. > > Setting attributes on an empty object does not work: > >>>> a=object() > >>>> a.x=1 > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'object' object has no attribute 'x' > > > However using an empty new style class works fine: > >>>> class C(object): pass > ... >>>> c=C() >>>> setattr(c, 'x', 1) >>>> > > The dir(c) function indicates, that the C instance has a __dict__ > attribute. > > Why don't have an object() instance a __dict__ attribute by default? Because it's not needed, and creating an empty dict has some cost. If you need a class with __dict__, just inherit from object as you already have noted. > This may need some explanation in the Python manual. Maybe. -- Gabriel Genellina From bbands at gmail.com Fri Jan 26 17:37:34 2007 From: bbands at gmail.com (BBands) Date: 26 Jan 2007 14:37:34 -0800 Subject: time series data and NumPy In-Reply-To: <2007012611184275249-bob@passcalnmtedu> References: <1169830757.220964.196540@m58g2000cwm.googlegroups.com> <51us3uF1mdcpsU1@mid.uni-berlin.de> <1169834042.396351.12660@h3g2000cwc.googlegroups.com> <2007012611184275249-bob@passcalnmtedu> Message-ID: <1169851054.812214.27610@v45g2000cwv.googlegroups.com> On Jan 26, 10:18 am, Bob Greschke wrote: > You're using the Python-MySQL module mysqldb, right? Actually I using MySQL with pyodbc as the mysqldb Windows binaries for Python 2.5 aren't out yet. :-( > You can select the data from the database and have > MySQL do the conversion with an SQL command. > > select to_days(), > from ; That works very nicely indeed. Thanks, jab From ptmcg at austin.rr.com Thu Jan 25 02:57:00 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Jan 2007 23:57:00 -0800 Subject: Simple Matrix class In-Reply-To: References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> <1169664540.120687.211350@s48g2000cws.googlegroups.com> <1169670271.547292.141110@l53g2000cwa.googlegroups.com> Message-ID: <1169711820.690536.181280@m58g2000cwm.googlegroups.com> On Jan 24, 3:18 pm, Robert Kern wrote: > Ill-conditioned matrices. You should grab a copy of _Matrix Computations_ by > Gene H. Golub and Charles F. Van Loan. > > For example, try the Hilbert matrix n=6. > > H_ij = 1 / (i + j - 1) > Sure enough, this gets ugly at n=6. Thanks for the reference to Matrix Computations; I'll try to track down a copy next time I'm at Half-Price Books. Meanwhile, it's back to the day job... -- Paul From gagsl-py at yahoo.com.ar Tue Jan 2 10:42:34 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Jan 2007 12:42:34 -0300 Subject: Python embedded interpreter: how to initialize the interpreter ? In-Reply-To: <1167573333.723607.199480@v33g2000cwv.googlegroups.com> References: <1167573333.723607.199480@v33g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070102124112.03f97be0@yahoo.com.ar> At Sunday 31/12/2006 10:55, ycollet at freesurf.fr wrote: >I've written a C embedded application. I want to open a python gui >application in my C program but when I do : > >PyRun_String( "import gui.py", file_input, pDictionary, pDictionary ); > >the interpreter emits an error: tkinter module not defined Does it work if you try it from the interpreter? -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tactics40 at gmail.com Mon Jan 22 19:10:51 2007 From: tactics40 at gmail.com (tac-tics) Date: 22 Jan 2007 16:10:51 -0800 Subject: arrow keys don't work In-Reply-To: References: <1169506381.452422.179070@11g2000cwr.googlegroups.com> Message-ID: <1169511051.114069.156600@a75g2000cwd.googlegroups.com> Robert Kern wrote: > tac-tics wrote: > > I've noticed that in Python 2.5, the interactive prompt does not > > support intelligent use of arrow keys like 2.4 did (up/down for > > previous/next statement, left/right for moving the cursor). What > > exactly is the reason for this and is there an easier fix than > > downgradinig to 2.4? Thanks. > > Your installation of 2.4 probably had the readline module installed while your > installation of 2.5 doesn't. What platform are you on? Actually, I should have posted this a while ago. I've noticed it on Ubuntu Linux, Mac OSX, and earlier today on Sun Solaris. What do I need to do to install / configure readline? From laurent.pointal at limsi.fr Mon Jan 29 07:43:04 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 29 Jan 2007 13:43:04 +0100 Subject: Yank Bastards KILLED THEIR OWN PEOPLE to stage 911 DRAMA In-Reply-To: References: <1169837804.481376.5790@q2g2000cwa.googlegroups.com> Message-ID: bryan rasmussen a ?crit : > See, if the python list mail server was written in Lisp Paul Graham > would already have been able to write up a spam filter to ban this > guy. > > Seriously though, shouldn't Thermate be banned by now. I read this from comp.lang.python... and its very hard to ban people (or better, ban out-of-subject posts) from non-moderated Usenet newsgroups. A+ Laurent. From steve at REMOVEME.cybersource.com.au Mon Jan 22 19:18:44 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 23 Jan 2007 11:18:44 +1100 Subject: How to use time.clock() function in python References: <1169503516.425217.218790@q2g2000cwa.googlegroups.com> <1169508778.101027.320760@11g2000cwr.googlegroups.com> Message-ID: On Mon, 22 Jan 2007 15:32:58 -0800, samuel.y.l.cheung wrote: > File "/usr/lib/python2.4/timeit.py", line 188, in repeat > t = self.timeit(number) > File "/usr/lib/python2.4/timeit.py", line 161, in timeit > timing = self.inner(it, self.timer) > File "", line 6, in inner > NameError: global name 'func1' is not defined > > I don't understand why i can't find 'func1', when I call the function > 'func1' directly, it works. > but why when I call it within 'timeit', it can't find it? Because the code in timeit is running in a different namespace. You have to import your function first. That's what the setup parameter is used for. Here's the hard way: t = timeit.Timer("func1()", """def func1(): #do something here return result """) Here's the easy way: t = timeit.Timer("func1()", "from __main__ import func1") -- Steven D'Aprano From kylotan at gmail.com Tue Jan 2 05:52:53 2007 From: kylotan at gmail.com (Ben Sizer) Date: 2 Jan 2007 02:52:53 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> Message-ID: <1167735173.884444.250750@k21g2000cwa.googlegroups.com> robert wrote: > Ben Sizer wrote: > > My opinion is that this is not as big a problem as some may feel that > > it is. Unlike Unix systems, the PATH variable is rarely used. > > It is a big problem. > > It is not less than the majority of Python users (at least those who do things on the command line) who deal with multiple Python versions. So you think most Python users have more than one version of Python installed? I disagree - but even if it is true, how come this isn't a big problem on Unix? Can you name a single distribution that doesn't install Python to the path? > This would create funny PATH variables - almost a "psychic behavior with history". It is quite trivial to see if Python is already on the path, and act differently based on that. > Windows is at all less a multi user system. I don't even know a case where two (Python) Programmers use _one_ box and then also want separate Python's - just know home mates (parasites) who occasionally share the web browser or so... So... that's another reason why there's rarely a problem in setting that PATH variable. > Linking also a default python.exe into the system32 upon a (non-default) checkbox mark in the installer should be simple, clear and do everything what 99.9% want - and most "compatible" to *nix. No, it doesn't : the /scripts directory is also important for many Python packages and that isn't addressed by shifting python.exe into system32. -- Ben Sizer From gherron at islandtraining.com Tue Jan 2 17:25:49 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 02 Jan 2007 14:25:49 -0800 Subject: list/dictionary as case statement ? In-Reply-To: References: Message-ID: <459ADBED.4080401@islandtraining.com> Stef Mientki wrote: > If I'm not mistaken, I read somewhere that you can use > function-names/references in lists and/or dictionaries, but now I can't > find it anymore. > > The idea is to build a simulator for some kind of micro controller (just > as a general practise, I expect it too be very slow ;-). > > opcodes ={ > 1: ('MOV', function1, ...), > 2: ('ADD', function2, ), > 3: ('MUL', class3.function3, ) > } > > def function1 > # do something complex > > > Is this possible ? > > thanks, > Stef Mientki > Yes. Functions are (so called) first class objects. You can refer to one by name, and pass that reference around in variables and other data structures. That said, your code above won't work as written because function1 is not in existence when you refer to it. Here's some working code which manipulates a reference to a function then calls it: >>> def fn(): ... print "Hello world!" ... >>> x = fn >>> y = [fn,fn] >>> z = {1:fn, 2:fn} >>> >>> x() Hello world! >>> y[0]() Hello world! >>> y[1]() Hello world! >>> z[1]() Hello world! >>> z[2]() Hello world! >>> Gary Herron From timr at probo.com Sun Jan 14 20:29:25 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 15 Jan 2007 01:29:25 GMT Subject: Maths error References: Message-ID: "Hendrik van Rooyen" wrote: >"Nick Maclaren" wrote: > >> What I don't know is how much precision this approximation loses when >> used in real applications, and I have never found anyone else who has >> much of a clue, either. >> >I would suspect that this is one of those questions which are simple >to ask, but horribly difficult to answer - I mean - if the hardware has >thrown it away, how do you study it - you need somehow two >different parallel engines doing the same stuff, and comparing the >results, or you have to write a big simulation, and then you bring >your simulation errors into the picture - There be Dragons... Actually, this is a very well studied part of computer science called "interval arithmetic". As you say, you do every computation twice, once to compute the minimum, once to compute the maximum. When you're done, you can be confident that the true answer lies within the interval. For people just getting into it, it can be shocking to realize just how wide the interval can become after some computations. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From felipe.lessa at gmail.com Wed Jan 10 06:11:58 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 10 Jan 2007 09:11:58 -0200 Subject: maximum number of threads In-Reply-To: <7.0.1.0.0.20070110064655.0508d0a0@yahoo.com.ar> References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> <7.0.1.0.0.20070110064655.0508d0a0@yahoo.com.ar> Message-ID: On 1/10/07, Gabriel Genellina wrote: > At Wednesday 10/1/2007 04:38, Paul Sijben wrote: > >Does anyone know what it going on here and how I can ensure that I have > >all the threads I need? > > Simply you can't, as you can't have 10000 open files at once. > Computer resources are not infinite. > Do you really need so many threads? Above a certain threshold, the > program total execution time may increase very quickly. Maybe Stackless could help the OP? http://www.stackless.com/ -- Felipe. From kosh at aesaeion.com Wed Jan 10 09:43:45 2007 From: kosh at aesaeion.com (William Heymann) Date: Wed, 10 Jan 2007 07:43:45 -0700 Subject: maximum number of threads In-Reply-To: References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: <200701100743.45547.kosh@aesaeion.com> On Wednesday 10 January 2007 7:11 am, Felipe Almeida Lessa wrote: > --- > $ python test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > Exception raised: can't start new thread > > Biggest number of threads: 382 > --- > > The test.py script is attached. So you know I tried this on ubuntu edgy 64bit edition on a dual 2218 opteron system with 8G of ram and I got Exception raised: can't start new thread Biggest number of threads: 32274 From sean at datafly.net Tue Jan 16 20:19:02 2007 From: sean at datafly.net (Sean Schertell) Date: Wed, 17 Jan 2007 10:19:02 +0900 Subject: Newbie: Capture traceback message to string? Message-ID: <8E19FBD5-47DC-4FE3-9E5C-B143664CC846@datafly.net> Hello! I'm new to Python and this is my first post to the list. I'm trying to simply capture exception text to a few strings which can be passed to a PSP page to display a pretty error message. The problem is that I just can't seem to figure out how to get the basic components of the traceback message into strings. Here's what I want to do: --------------------- try: bad_math = 1/0 except: info = sys.exc_info() main_error_str = # ??? full_traceback_str = # ??? tmpl = psp.PSP(req, filename='error.html') tmpl.run({'main_error_str': main_error_str, 'full_traceback_str':full_traceback_str}) return apache.OK --------------------- ...So then my PSP page receives the errors as variables containing strings. I've been googling and experimenting for more hours than I care to admit. A little help please? Thanks! Sean From jorge.vargas at gmail.com Mon Jan 8 10:51:27 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 8 Jan 2007 11:51:27 -0400 Subject: PDF rendering toolkit? In-Reply-To: <509gkmF1eufvtU1@mid.uni-berlin.de> References: <509gkmF1eufvtU1@mid.uni-berlin.de> Message-ID: <32822fe60701080751r94a65eaxa8fb3a4344f678ef@mail.gmail.com> On 1/6/07, Diez B. Roggisch wrote: > > I'm looking for a tool to take an actual .pdf file and display it in a > > window (I'm using wxwidgets at the moment) > > No idea if there is a one-shot-kills-them-all solution out there - but > if you have a way to go for windows, you might checkout PyQt and PyKDE > to embed a kpfd-view in a window of yours. > > I agree that it is less than desirable to switch toolkits - but if you > _have_ to... > yes indeed the problem with that is I want my code to be portable that is the reason I'm working on top of wx. > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From no-spam at no-spam-no-spam.invalid Mon Jan 8 11:23:52 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Mon, 08 Jan 2007 17:23:52 +0100 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: Duncan Booth wrote: > Laszlo Nagy wrote: > > > The 'parallel python' site seems very sparse on the details of how it is > implemented but it looks like all it is doing is spawning some subprocesses > and using some simple ipc to pass details of the calls and results. I can't > tell from reading it what it is supposed to add over any of the other > systems which do the same. > > Combined with the closed source 'no redistribution' license I can't really > see anyone using it. Thats true. IPC through sockets or (somewhat faster) shared memory - cPickle at least - is usually the maximum of such approaches. See http://groups.google.de/group/comp.lang.python/browse_frm/thread/f822ec289f30b26a For tasks really requiring threading one can consider IronPython. Most advanced technique I've see for CPython ist posh : http://poshmodule.sourceforge.net/ I'd say Py3K should just do the locking job for dicts / collections, obmalloc and refcount (or drop the refcount mechanism) and do the other minor things in order to enable free threading. Or at least enable careful sharing of Py-Objects between multiple separated Interpreter instances of one process. .NET and Java have shown that the speed costs for this technique are no so extreme. I guess less than 10%. And Python is a VHLL with less focus on speed anyway. Also see discussions in http://groups.google.de/group/comp.lang.python/browse_frm/thread/f822ec289f30b26a . Robert From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 17:26:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 23:26:05 +0100 Subject: [OT] (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <1168203678.193392.158600@i15g2000cwa.googlegroups.com> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> <1168048620.409190.85870@v33g2000cwv.googlegroups.com> <1168130960.670978.111850@s34g2000cwa.googlegroups.com> <45a12b07$0$300$426a74cc@news.free.fr> <1168203678.193392.158600@i15g2000cwa.googlegroups.com> Message-ID: <45a16d3d$0$317$426a74cc@news.free.fr> Martin Miller a ?crit : > Bruno Desthuilliers wrote: > >>Martin Miller a ?crit : >>(snip) >> >>>Oh, contrair. >> >>I guess you mean "au contraire" ?-) >> >>(snip) > > > FWIW "contrair" is how it's spelled in the Oxford English dictionary (I > actually did look it up before posting because it seemed like there > ought be an 'e' on the end). The dictionary also says it's chiefly > Scottish but the etymology indicates from the Old French "contraire". Not that 'old' !-) It's still a common French word. "au contraire" is French for "on the contrary", and "au" is prononced 'o' - hence my mistake. From S.Mientki-nospam at mailbox.kun.nl Thu Jan 11 13:36:54 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 11 Jan 2007 19:36:54 +0100 Subject: globals accros modules In-Reply-To: <45a66cea$0$289$426a34cc@news.free.fr> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> <45a66cea$0$289$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > stef a ?crit : >> >>> >>> Change a=1 to amodule.a=1 >>> If you find yourself doing tricks with the module globals, think >>> about redesigning your application. >>> >> Of course I completely agree with you. >> >> But ... >> if you're moving from MatLab to Python, >> and want to show your collegaes, >> with how little effort they can reuse all their existing MatLab >> routines in Python, >> then the global issue is a real pain !! >> >> You can explain your collegaes, that >> - the startindex of arrays changes from 1 to 0 >> - slices are upto, instead of including the final border >> - indention is th? key >> And tell them about all beautiful things in Python, >> but tell them that they are going to loose all their globals ??? > > It's a feature. Globals are definitively a BadThing(tm). > >> cheers, >> Stef Mientki >> From alexandre_irrthum at yahoo.com Mon Jan 29 15:47:13 2007 From: alexandre_irrthum at yahoo.com (alexandre_irrthum at yahoo.com) Date: 29 Jan 2007 12:47:13 -0800 Subject: Compiling extension with Visual C++ Toolkit Compiler - MSVCR80.dll Message-ID: <1170103633.189538.216620@v45g2000cwv.googlegroups.com> Hi there, I am trying to install a Python library with a C extension (the Polygon library) and I am having a bad time. My Python version is Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug 2 2006, 12:09:59) [MSC v.1310 32 bit (Intel)] on Windows XP Pro. I have dutifully followed the instructions here: http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit i.e., - Installed Microsoft Visual C++ Toolkit Compiler 2003 - Installed Microsoft Platform SDK for Windows Server 2003 R2 - Installed Microsoft .NET Framework SDK, version 1.1 - setup the path, include and lib environment variables with a .bat file, as described in the wiki document The library seems to build correctly (producing Polygon.py and cPolygon.pyd), but when I import it I get the following message from python.exe: "This application has failed to start because MSVCR80.dll was not found". I thought that this might be due to Python trying to link against the .dll from Microsoft Visual C++ Express 2005, also installed on my PC, instead of MSVCR71.dll. So I've removed MS Visual C ++ Express 2005, and any trace of it from my environment variables, but that doesn't seem to change anything. Any help would be greatly appreciated. Regards, alex From bdesth.quelquechose at free.quelquepart.fr Thu Jan 18 16:42:24 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 18 Jan 2007 22:42:24 +0100 Subject: Traversing the properties of a Class In-Reply-To: <1169152688.921153.26150@m58g2000cwm.googlegroups.com> References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> <1169152688.921153.26150@m58g2000cwm.googlegroups.com> Message-ID: <45afe338$0$318$426a74cc@news.free.fr> EdG a ?crit : (top-post corrected) > > Neil Cerutti wrote: > >>On 2007-01-18, EdG wrote: >> >>>For debugging purposes, I would like to traverse the class >>>listing out all the properties. >> >>This is the first thing that came to mind. >> >>def show_properties(cls): >> for attr in dir(cls): >> if isinstance(getattr(cls, attr), property): >> print attr >> > This works great. I have one more question. Now that I have the name > of the property, how do I get it's value? > > I want to print '%s = %s' % (attr,theattributesvalue) Then you need to have the instance... def list_properties(cls): return [ name for name in dir(cls) if isinstance(getattr(cls, name), property) ] def print_properties(obj): for name in list_properties(obj.__class__): print "%s : %s" % (name, str(getattr(obj, name))) From steve at REMOVE.THIS.cybersource.com.au Mon Jan 22 17:28:06 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 23 Jan 2007 09:28:06 +1100 Subject: How to use time.clock() function in python References: <1169503516.425217.218790@q2g2000cwa.googlegroups.com> Message-ID: On Mon, 22 Jan 2007 14:05:16 -0800, yinglcs at gmail.com wrote: > Hi, > > I am following this python example trying to time how long does an > operation takes, like this: > > My question is why the content of the file (dataFile) is just '0.0'? > I have tried "print >>dataFile, timeTaken" or "print >>dataFile,str( > timeTaken)", but gives me 0.0. > Please tell me what am I missing? > > > t1 = time.clock() > os.system(cmd) > > outputFile = str(i) + ".png" > > t2 = time.clock() > > timeTaken = t2 - t1 > allTimeTaken += timeTaken > print >>dataFile, timeTaken For the correct way to time operations, see the timeit module. For your specific problem, it is hard to tell what you are doing wrong when you don't tell us what "datafile" is. What's "outfile" for? It gets created *after* the command runs, but doesn't get used. -- Steven. From scott.daniels at acm.org Tue Jan 16 13:32:41 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 16 Jan 2007 10:32:41 -0800 Subject: A note on heapq module In-Reply-To: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> Message-ID: <45ad0f6c$1@nntp0.pdx.net> bearophileHUGS at lycos.com wrote: > In few minutes I have just written this quite raw class, .... I'd suggest some changes. It is nice to have Heaps with equal contents equal no matter what order the inserts have been done. Consider how you want Heap([1, 2, 3]) and Heap([3, 1, 2]) to behave. Similarly, it is nice to have str and repr produce canonical representations (I would skip the __str__ code, myself, though). Also, subclasses should get their identities tweaked as so: > class Heap(object): > ... > def sort(self, cmp=None, key=None): > self.h.sort(cmp=cmp, key=key) I'd remove this method. > ... > def __eq__(self, other): > return isinstance(other, Heap) and self.h == other.h return isinstance(other, self.__class__) and sorted( self.h) == sorted(other.h) > def __ne__(self, other): > return not isinstance(other, Heap) or self.h != other.h return not isinstance(other, self.__class__) and sorted( self.h) != sorted(other.h) > ... > def __str__(self): > return str(self.h) return str(sorted(self.h)) > def __repr__(self): > return "Heap(%s)" % self.h if self.h else "Heap()" return "%s(%s)" % (self.__class__.__name__, sorted(self.h)) And I'd add: def __lt__(self, other): raise TypeError('no ordering relation is defined for %s' % self.__class__.__name__) __gt__ = __le__ = __ge__ = __lt__ --Scott David Daniels scott.daniels at acm.org From Terry.McKenna at gmail.com Thu Jan 11 12:11:40 2007 From: Terry.McKenna at gmail.com (Tmack) Date: 11 Jan 2007 09:11:40 -0800 Subject: COM compatibility Message-ID: <1168535500.394266.10860@i39g2000hsf.googlegroups.com> I'm not a programmer! I work for a software company. We have a SDK that customers can use to customize the app. The requirement to use the SDK is: XYZ App has been designed in such a way that all the business objects used in the application are automatically exposed through a thin COM wrapper created automatically during the application build process. This means that using the XYZ App SDK is very efficient, and all the same underlying objects and properties that the application's programmers use to build the XYZ App user interface are also available to third-party programmers via the SDK. Does it sound like Python would allow me use the apps SDK? Thanks From felipe.lessa at gmail.com Wed Jan 3 14:48:24 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 3 Jan 2007 17:48:24 -0200 Subject: A python library to convert RTF into PDF ? In-Reply-To: <1167850322.373355.327020@s34g2000cwa.googlegroups.com> References: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> <5stnp25m2uffc4n5k7g9e68hk2l85u4fmm@4ax.com> <1167850322.373355.327020@s34g2000cwa.googlegroups.com> Message-ID: On 3 Jan 2007 10:52:02 -0800, leonel.gayard at gmail.com wrote: > I have tried to > convert them to tex using OpenOffice, but the result is ugly as hell. Why not use OO.org to convert DOC to PDF? It does so natively, IIRC. -- Felipe. From jstroud at mbi.ucla.edu Sat Jan 27 01:04:06 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 26 Jan 2007 22:04:06 -0800 Subject: strip question In-Reply-To: References: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Fri, 26 Jan 2007 21:33:47 -0800, eight02645999 wrote: > > >>hi >>can someone explain strip() for these : >>[code] >> >>>>>x='www.example.com' >>>>>x.strip('cmowz.') >> >>'example' >>[/code] >> >>when i did this: >>[code] >> >>>>>x = 'abcd,words.words' >>>>>x.strip(',.') >> >>'abcd,words.words' >>[/code] >> >>it does not strip off "," and "." .Why is this so? >>thanks > > > > Fascinating... > > It gets weirder: > > >>>>x.strip('s') > > 'abcd,words.word' > > Why strip only the final s, not the earlier one? > > >>>>x.strip('w') > > 'abcd,words.words' > >>>>x.strip('o') > > 'abcd,words.words' > >>>>x.strip('r') > > 'abcd,words.words' > > Strips nothing. > > >>>>x.strip('ba') > > 'cd,words.words' > > Strips correctly. > > >>>>x.strip('bwa') > > 'cd,words.words' > > Strips the a and b but not the w. > > >>>>x.strip('bwas') > > 'cd,words.word' > > ...and only one of the S's. > > >>>>y = "bwas" >>>>y.strip('bwas') > > '' > >>>>y = "bwasxyz" >>>>y.strip('bwas') > > 'xyz' > > And yet these work. > > > You know, I'm starting to think there may be a bug in the strip method... > either that or the documentation should say: > > strip(...) > S.strip([chars]) -> string or unicode > > Return a copy of the string S with leading and trailing > whitespace removed. > If chars is given and not None, remove none, some or all characters in > chars instead. If chars is unicode, S will be converted to unicode > before stripping > > > *wink* > > At the risk of appearing that I didn't notice your *wink*, the operative words in the docs would be "leading" and "trailing". But somehow I think you knew that. James From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 10:21:59 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 16:21:59 +0100 Subject: Bizarre floating-point output References: Message-ID: <50f5snF1fb5uqU2@mid.individual.net> Nick Maclaren wrote: > Ah! That explains it. I would call that reason intermediate > between rational and an artifact of the way the code has evolved! Which code has evolved? Those precision problems are inherent problems of the way floats are stored in memory. Regards, Bj?rn -- BOFH excuse #292: We ran out of dial tone and we're and waiting for the phone company to deliver another bottle. From g.tagliaretti at gmail.com Wed Jan 17 17:21:39 2007 From: g.tagliaretti at gmail.com (Gian Mario Tagliaretti) Date: Wed, 17 Jan 2007 23:21:39 +0100 Subject: Would a Dutch speaker please check this wiki page please? References: Message-ID: <45aea118$0$32708$4fafbaef@reader1.news.tin.it> skip at pobox.com wrote: > Got a note about a new page on the Python Wiki: > >>>>>> "Wade" == Wade McDaniel writes: > > http://wiki.python.org/moin/Selcuk_Altun > > I suspect it's junk since it doesn't seem to mention Python and the > website it says: Welcome on my site www.keriwar.nl, if you have any questions first read the F.A.Q. In one sentence there are two mistakes, so I think the guy that wrote it is not dutch and yes .. it's junk. cheers -- Gian Mario Tagliaretti From bborcic at gmail.com Wed Jan 24 09:32:56 2007 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 24 Jan 2007 15:32:56 +0100 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> Message-ID: Chris Mellon wrote: > > Using either win32 or wxPython you will be able to produce bitmaps > directly, without needing to create a visible window. > > > Some quick & dirty wxPython code > > def getTextBitmap(text, font, fgcolor, bgcolor): > dc = wx.MemoryDC() > dc.SetFont(font) > width, height= dc.GetTextExtent(text) > bmp = wx.EmptyBitmap(width, height) > dc.SelectObject(bmp) > dc.SetBackground(wx.Brush(bgcolor)) > dc.Clear() > dc.SetTextBackground(bgcolor) > dc.SetTextForeground(fgcolor) > dc.DrawText(text, 0, 0) > dc.SelectObject(wx.NullBitmap) > return bmp > > > Raw win32 code will look similar but will be much more verbose. Thx again for this base. Quickly testing this, it appears that the result is rendered half a pixel off in the x-direction. Does this make sense ? Is it possible to position text with subpixel accuracy ? Regards, Boris Borcic From klaus at seistrup.dk Sat Jan 6 15:58:45 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 6 Jan 2007 20:58:45 +0000 (UTC) Subject: nntplib downloads content with extra linebreaks References: <1168110213.436860@sj-nntpcache-1.cisco.com> <1168112276.194982@sj-nntpcache-1.cisco.com> <1168115885.739704@sj-nntpcache-1.cisco.com> Message-ID: Rweth wrote: > so afile contains a filename. > One single aline looks like so: > '' Beats me where those empty lines come from, it doesn't seem to happen in nntplib. Does the same thing happen if you pass .body() a filepointer? Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From larry.bates at websafe.com Tue Jan 16 18:48:18 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 16 Jan 2007 17:48:18 -0600 Subject: Making a simple script standalone In-Reply-To: <5d1084-5j7.ln1@whisper.very.softly> References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: <45AD6442.6050209@websafe.com> Rikishi 42 wrote: > Hi, > I'm new to this group. I've tried finding my answer in existing messages, > but no such luck. > > What I want to do is to compile/bundle/prepare/whatever_term a simple > Python script for deployment on a Windows machine. Installing Python > itself on that machine, is not an option. Ideally I would like to obtain > a single executable file, but a script+runtime is acceptable. > > There is nothing graphical, nothing fancy about the script. > The only imports are: os, stat, string and time. > > > Any suggestions on an - easy and clear - path to follow ? > > I use py2exe and inno installer. Works great. -Larry From vgvr620034 at gmail.com Tue Jan 30 04:37:20 2007 From: vgvr620034 at gmail.com (raghu) Date: 30 Jan 2007 01:37:20 -0800 Subject: Explanation about pickle module Message-ID: <1170149840.610362.319690@h3g2000cwc.googlegroups.com> can any one explain about pickle i read in the book but they have not provided any example for that so please explain with a simple example From medicalsounds at hotmail.com Thu Jan 25 11:45:37 2007 From: medicalsounds at hotmail.com (Jona) Date: 25 Jan 2007 08:45:37 -0800 Subject: Using Timing function problem..... In-Reply-To: References: <1169699160.119721.9750@v45g2000cwv.googlegroups.com> Message-ID: <1169743535.955451.167900@q2g2000cwa.googlegroups.com> Thanks so much! that did it! you can tell I'm new with python.. lol... thanks again.. Jonathan From limodou at gmail.com Fri Jan 26 03:14:17 2007 From: limodou at gmail.com (limodou) Date: Fri, 26 Jan 2007 16:14:17 +0800 Subject: Announcement -- ZestyParser In-Reply-To: <1168580486.921117.317630@v45g2000cwv.googlegroups.com> References: <1168407920.281020.147680@k58g2000hse.googlegroups.com> <1168580486.921117.317630@v45g2000cwv.googlegroups.com> Message-ID: <505f13c0701260014g516dbbd5vccba30de1ac86791@mail.gmail.com> On 11 Jan 2007 21:41:26 -0800, Adam Atlas wrote: > Thanks for the responses; you're right, and I have now posted the > examples online. I just released version 0.6.0, by the way, which has > several worthwhile improvements and much better documentation. It also > includes an example for parsing RDF Notation3, to demonstrate a parsing > task a bit more complex than the other examples. > > That's all posted at now. > I'm very interesting in this project, and I see there are many examples, but there are no input data files. So I don't know how to test them. Can you send me some testing data files or just add them into the tarball file, so others can easy test the examples. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From kleiner at hora-obscura.de Thu Jan 18 06:01:16 2007 From: kleiner at hora-obscura.de (Stefan Palme) Date: Thu, 18 Jan 2007 12:01:16 +0100 Subject: DOTALL not working as expected References: Message-ID: arghh. Thanks for removing my blindness :) -stefan- On Thu, 18 Jan 2007 10:38:35 +0000, Roberto Bonvallet wrote: > Stefan Palme wrote: >>> using the "re" module of Python (2.3 and 2.4), I tried the following: >>> >>> import re >>> print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL) >>> >> Just noticed, that it works when *compiling* the pattern: >> >> import re >> p = re.compile('X.*?Y', re.DOTALL) >> print re.sub(p, 'Z', 'Xab\ncdY') >> >> Still the question - my fault or a bug? > > Your fault. According to the documentation [1], the re.sub function takes > a count as a fourth argument, not the compilation flags. > > [1] http://docs.python.org/lib/node46.html > > Cheers, From http Tue Jan 23 11:32:11 2007 From: http (Paul Rubin) Date: 23 Jan 2007 08:32:11 -0800 Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> Message-ID: <7xbqkpbt6c.fsf@ruckus.brouhaha.com> "gangesmaster" writes: > so this is why [lambda: i for i in range(10)] will always return 9. > imho that's a bug, not a feature. Use [(lambda j: lambda: j)(i) for i in range(10)] or the Python idiom [(lambda i=i: i) for i in range(10)] From horpner at yahoo.com Tue Jan 23 11:21:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Jan 2007 16:21:39 GMT Subject: Are there sprintf in Python??? References: <1169496238.925052.311660@l53g2000cwa.googlegroups.com> Message-ID: On 2007-01-22, questions? wrote: > Are there any sprintf in Python? > I know you can print to files(or redefine sys.stout) and later open the > file content. > > Are there similar function to sprintf in C? No, but you can compose a similar function very easily. def sprintf(format, *objects): return format % tuple(objects) Since strings are immutable it's not convenient to provide a pass-out parameter as in C. If you want to check for errors you'll have to catch the exceptions, rather than inspect the return value as you can in C. -- Neil Cerutti Symphonies of the Romantic era were a lot longer in length. --Music Lit Essay -- Posted via a free Usenet account from http://www.teranews.com From skip at pobox.com Tue Jan 2 13:07:42 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 2 Jan 2007 12:07:42 -0600 Subject: python2.5 frameobject - how to upgrade? In-Reply-To: <459A936C.4090609@skynet.be> References: <459a6894$0$9322$ba620e4c@news.skynet.be> <459A936C.4090609@skynet.be> Message-ID: <17818.40814.10769.56066@montanaro.dyndns.org> Helmut> A personal question: Have you converted from Perl to Python, as Helmut> well? Never really needed to. Anybody hiring me for my Perl expertise would be in big trouble. ;-) Skip From weekender_ny at yahoo.com Sun Jan 21 23:03:54 2007 From: weekender_ny at yahoo.com (John) Date: 21 Jan 2007 20:03:54 -0800 Subject: html + javascript automations = [mechanize + ?? ] or something else? In-Reply-To: <1168965900.409623.53970@a75g2000cwd.googlegroups.com> References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> <1168965900.409623.53970@a75g2000cwd.googlegroups.com> Message-ID: <1169438634.022238.275740@51g2000cwl.googlegroups.com> I tried to install pamie (but I have mostly used python on cygwin on windows). In the section " What will you need to run PAMIE", it says I will need "Mark Hammonds Win32 All" which I can not find. Can anyone tell me how do I install PAMIE? Do I need python for windows that is different from cygwin's python? Thanks, --j ina wrote: > John wrote: > > I have to write a spyder for a webpage that uses html + javascript. I > > had it written using mechanize > > but the authors of the webpage now use a lot of javascript. Mechanize > > can no longer do the job. > > Does anyone know how I could automate my spyder to understand > > javascript? Is there a way > > to control a browser like firefox from python itself? How about IE? > > That way, we do not have > > to go thru something like mechanize? > > > > Thanks in advance for your help/comments, > > --j > > You want pamie, iec or ishybrowser. Pamie is probably the best choice > since it gets patches and updates on a regular basis. > > http://pamie.sourceforge.net/ From nanjundi at gmail.com Mon Jan 22 19:53:27 2007 From: nanjundi at gmail.com (Nanjundi) Date: 22 Jan 2007 16:53:27 -0800 Subject: Are there sprintf in Python??? References: <1169496238.925052.311660@l53g2000cwa.googlegroups.com> Message-ID: <1169513607.120734.33150@s48g2000cws.googlegroups.com> > Are there any sprintf in Python? Refer module StringIO - just like file input/output operations. cStringIO is another module (faster) Quick intro: from StringIO import StringIO s = StringIO() s.write('hello') s.seek(0) print s.read() -N From ejatsomewhere.com Thu Jan 4 15:49:22 2007 From: ejatsomewhere.com (Erik Johnson) Date: Thu, 4 Jan 2007 13:49:22 -0700 Subject: subclassing a module: misleading(?) error message Message-ID: <459d687a$1@nntp.zianet.com> I ran into a problem I didn't understand at first. I got part of it figured out. Let me first demonstrate the original problem: > cat Super.py class Super(object): def __init__(self): self._class = 'Super' def hello(self): print "%s says 'Hello'" % self._class > cat Sub.py import Super class Sub(Super): def __init__(self): self._class = 'Sub' > > python Python 2.3.4 (#1, Feb 7 2005, 15:50:45) [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Super import Super >>> from Sub import Sub Traceback (most recent call last): File "", line 1, in ? File "Sub.py", line 4, in ? class Sub(Super): TypeError: function takes at most 2 arguments (3 given) >>> My question is NOT "What's wrong here?" (The answer to that is that the import in Sub.py should be: from Super import Super i.e., I tried to use the module itself where I meant to subclass the class defined in that module). My questions are: Why does python complain about a function here? (it's a class definition statement, right?) Is there really a function being called here? If so: What function was called? What two arguments is it expecting? What three were given? Thanks, -ej From ggrp1.20.martineau at dfgh.net Sun Jan 7 16:16:10 2007 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 7 Jan 2007 13:16:10 -0800 Subject: Python cheatsheets References: Message-ID: <1168204570.358284.72530@11g2000cwr.googlegroups.com> gonzlobo wrote: > Curious if anyone has a python cheatsheet* published? I'm looking for > something that summarizes all commands/functions/attributes. Having > these printed on a 8" x 11" double-sided laminated paper is pretty > cool. > > * cheatsheet probably isn't the right word, but you get the idea. :) Richard Gruet publishes an excellent Quick Reference in multiple formats, available from . -Martin From steve at REMOVE.THIS.cybersource.com.au Mon Jan 1 00:50:36 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 01 Jan 2007 16:50:36 +1100 Subject: I want to see all the variables References: <45952426.1080800@websafe.com> <8yelh.90$Q4.82@newsfe02.lga> <459722fc$0$30313$9b4e6d93@newsspool1.arcor-online.net> <2v0hp2tbk8uq2pbqi6874b4tidbck2tpga@4ax.com> <7xbqljnww8.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 31 Dec 2006 21:23:03 -0800, Paul Rubin wrote: > Steven D'Aprano writes: >> > At the same time, you should ponder very >> > carefully the reasons why the original author deemed it important to >> > make those attributes private in the first place. >> >> In my experience, it is mostly because they come from >> bondage-and-domination languages where it is expected that >> everything is private except for a small, carefully chosen public >> API, rather than from languages like Python that encourages openness >> and a philosophy of "we're all adults here". > > Funny thing, some of those B&D languages were designed by people who > had plenty of experience with Lisp and were tired of being bitten by > its Python-like looseness. I never said they were wrong to do so. But those languages aren't Python. Python is designed for those who are tied of the constant restraint of B&D languages. >> I wonder how many double-underscore "private" attributes are used in >> the Python standard library? That should give you an idea of "best >> practice" use of private attributes in Python. > > If socket.py is an example of best practice use of private attributes, I > shudder to imagine what kind of cruft must lurk in legacy applications. socket.py doesn't have any double-underscore private attributes (at least not in Python 2.4). So what's your point? -- Steven. From wyldwolf at gmail.com Tue Jan 23 11:06:56 2007 From: wyldwolf at gmail.com (Kevin Kelley) Date: Tue, 23 Jan 2007 10:06:56 -0600 Subject: 2007 DST Changes Message-ID: <77895c1d0701230806m4d49503dre4d29845ebdb827b@mail.gmail.com> Is python affected by the 2007 DST changes in the US? Other than making sure the OS is patched correctly (Win 2K and Solaris 8) is there anything else that needs to be done from a Python point of view? Thanks, Kevin Kelley -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Mon Jan 15 21:50:56 2007 From: nagle at animats.com (John Nagle) Date: Tue, 16 Jan 2007 02:50:56 GMT Subject: Does class patching actually work Message-ID: In M2Crypto/m2urllib there is this: import string, sys, urllib from urllib import * def open_https(self, url, data=None, ssl_context=None): ... # Minor brain surgery. URLopener.open_https = open_https The intent of this is to replace method open_https of class URLopener with a local, patched version. Does that actually work? When I've tried to do that in other code, it seems to have no effect. In fact, I can write URLopener.open_https = None and nothing changes. John Nagle From not at set.se Tue Jan 23 17:01:36 2007 From: not at set.se (Daniel Jonsson) Date: Tue, 23 Jan 2007 23:01:36 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? Message-ID: So, I've reached the point where my building pipeline tools actually needs to be used by other people in my company. By this reason I actually need to think about the usability, and I've come to the conclusion that I need a GUI. So, which of the two packages should I learn, and which one is easier to pick up? Thanks in advance! Daniel From kylotan at gmail.com Fri Jan 12 05:07:25 2007 From: kylotan at gmail.com (Ben Sizer) Date: 12 Jan 2007 02:07:25 -0800 Subject: Is there a good example on instantiating, calling, using, an API from Python on Windows? In-Reply-To: <1168563132.224441.212130@51g2000cwl.googlegroups.com> References: <1168541166.457806.133320@p59g2000hsd.googlegroups.com> <45A6CA45.3000300@websafe.com> <1168563132.224441.212130@51g2000cwl.googlegroups.com> Message-ID: <1168596445.398267.81330@38g2000cwa.googlegroups.com> kj7ny wrote: > To be more exact, I am trying to use Python to talk to a Livelink > system (http://www.opentext.com/) through their LAPI interface (.dll's, > I think). I'll see if I can generate a more intelligent answer to your > question, but for now, I'm far enough in the dark that this is as good > as I can get. API is a vague term referring to the interface to an application, which could take one of many forms. The form it takes dictates the method you need to use here. If indeed it is via DLLs, then the ctypes module may help. Otherwise, you need to find out precisely what form the API takes. -- Ben Sizer From timr at probo.com Fri Jan 5 02:17:55 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 05 Jan 2007 07:17:55 GMT Subject: cache line length of a machine References: <1167953016.952907.279260@i15g2000cwa.googlegroups.com> Message-ID: <7burp2dgedmpf7utp4c5hi58dncc44kdqj@4ax.com> "John" wrote: > >How do I find out the cache line length of a machine in python? How would that piece of information be valuable in Python? There isn't anything you can do to take advantage of it in Python. You can look up the L2 and L3 cache size and speed using WMI (assuming you are using Windows). For more detailed, you will have to call into a C routine, and maybe even resort to looking up the cpuid info. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bj_666 at gmx.net Wed Jan 24 16:23:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 24 Jan 2007 22:23:25 +0100 Subject: raise UnicodeError, "label too long" References: <1169672223.231030.262610@l53g2000cwa.googlegroups.com> Message-ID: In <1169672223.231030.262610 at l53g2000cwa.googlegroups.com>, Flavio wrote: > Hi I am havin a problem with urllib2.urlopen. > > I get this error when I try to pass a unicode to it. > > raise UnicodeError, "label too long" > > is this problem avoidable? no browser or programs such as wget seem to > have a problem with these strings. What exactly are you doing? How does a (unicode?) string look like that triggers this exception? Ciao, Marc 'BlackJack' Rintsch From NikitaTheSpider at gmail.com Sat Jan 20 15:41:18 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sat, 20 Jan 2007 15:41:18 -0500 Subject: spidering script References: <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d@fdn.com> Message-ID: In article <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d at fdn.com>, "David Waizer" wrote: > Hello.. > > I'm looking for a script (perl, python, sh...)or program (such as wget) > that will help me get a list of ALL the links on a website. > > For example ./magicscript.pl www.yahoo.com and outputs it to a file, it > would be kind of like a spidering software.. David, In addition to others' suggestions about Beautiful Soup, you might also want to look at the HTMLData module: http://oregonstate.edu/~barnesc/htmldata/ -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From mail at microcorp.co.za Sun Jan 14 00:18:11 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 14 Jan 2007 07:18:11 +0200 Subject: Maths error References: Message-ID: <002901c7379b$634567e0$03000080@hendrik> "Dennis Lee Bieber" wrote: > {My 8th grade teacher was a bit worried at seeing me with a slipstick > ; and my HighSchool Trig/Geometry teacher only required 3 significant > digits for answers -- even though half the class had calculators by > then} LOL - I haven't seen the word "slipstick" for yonks... I recall an SF character known as "Slipstick Libby", who was supposed to be a Genius - but I forget the setting and the author. It is something that has become quietly extinct, and we did not even notice. We should start a movement for reviving them - on grounds of their "greenness" - they use no batteries... Fat chance. - Hendrik From hg at nospam.org Wed Jan 24 01:47:26 2007 From: hg at nospam.org (hg) Date: Wed, 24 Jan 2007 07:47:26 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? References: <45b72b0d$0$5107$ba4acef3@news.orange.fr> Message-ID: Laurent Rahuel wrote: > Hi, > > I known this can be impossible but what about an "HTML" GUI ? > > Daniel Jonsson wrote: > >> So, I've reached the point where my building pipeline tools actually >> needs to be used by other people in my company. By this reason I >> actually need to think about the usability, and I've come to the >> conclusion that I need a GUI. So, which of the two packages should I >> learn, and which one is easier to pick up? >> Thanks in advance! >> >> Daniel I think it has been proposed. I have customers that require that but usually find two major issues with the concept: 1) Unless very knowledgeable in Ajax, it is quite difficult to reach the same level of functionnality from a browser 2) accessing local devices generally requires browser plugins (XPCOM for mozilla and ActiveX for IE) .... which are a pain to code and are considered a security breach. hg From codecraig at gmail.com Wed Jan 24 09:12:14 2007 From: codecraig at gmail.com (abcd) Date: 24 Jan 2007 06:12:14 -0800 Subject: Thoughts on using isinstance In-Reply-To: References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> Message-ID: <1169647934.219682.144390@j27g2000cwj.googlegroups.com> > The "Python way" is to validate by performing the operations you need to > perform and catching any exceptions that result. In the case of your > example, you seem to be saying that you'd rather raise your own > exception (which, by the way, should really be a subclass of Exception, > but we will overlook that) that relying on the interpreter to raise a > ValueError or a TypeError. Is there really any advantage to this? You > increase your code size and add *something* to execution time with > little real purpose. > > People coming to Python after C++ or some similar language that allows > or requires parameter type declarations often don't feel comfortable > taking this direction to start with, but it works well for most of us. > > regards > Steve So instead of validating input I should just try and use the input as if it was correct, and let python throw the errors? From vpolukcht at gmail.com Tue Jan 16 09:22:42 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 16 Jan 2007 06:22:42 -0800 Subject: Regular expressions question In-Reply-To: References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> Message-ID: <1168957361.204348.30080@s34g2000cwa.googlegroups.com> Actually, i'm trying to get the values of first field (Global) , fourth (200, 4), and fifth (100%) and sixth (100%). Everything except fourth is simple. On Jan 16, 2:59 pm, Duncan Booth wrote: > "Victor Polukcht" wrote: > > I have 2 strings: > > > "Global etsi3 *200 ok 30 100% 100% > > Outgoing" > > and > > "Global etsi3 * 4 ok 30 100% 100% > > Outgoing" > > > The difference is "*200" instead of "* 4". Is there ability to write a > > regular expression that will match both of that strings?Yes, ".*" would match both of the strings, but not in a useful way. You'll > have to consider which strings you *don't* want to match as well as which > ones you do and whether you want to extract any information from the > strings or find the ones which match. > > But first take a step back and look at the problem as a whole. You didn't > say what you are trying to do, and often people will jump at regular > expressions as the solution when there may be better ways of doing what > they want without writing a regular expression. > > What do you really want to do? From justin.mailinglists at gmail.com Thu Jan 11 04:59:20 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 11 Jan 2007 01:59:20 -0800 Subject: os.popen() not executing command on windows xp In-Reply-To: <1168508553.151827.261420@k58g2000hse.googlegroups.com> References: <1168508553.151827.261420@k58g2000hse.googlegroups.com> Message-ID: <1168509560.119819.78470@o58g2000hsb.googlegroups.com> > import os > a = os.popen('"c:\Program Files\Grisoft\AVG Free\avgscan.exe" > "c:\program files\temp1\test1.txt"') > print a.read() > use raw strings e.g., instead of '"c:...\avgscan...' use r'"c:...\avgscan...' http://www.ferg.org/projects/python_gotchas.html#contents_item_2 From Roland.Puntaier at br-automation.com Wed Jan 10 11:10:05 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Wed, 10 Jan 2007 17:10:05 +0100 Subject: SubProcess _make_inheritable Message-ID: SubProcess.py needs to be patched - at least in 2.4 - to work from windows GUIs: def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" if handle==None: handle=-1 return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS) From cliff at develix.com Wed Jan 24 18:38:29 2007 From: cliff at develix.com (Cliff Wells) Date: Wed, 24 Jan 2007 15:38:29 -0800 Subject: ANN: Dejavu 1.5.0RC1 In-Reply-To: <435DF58A933BA74397B42CDEB8145A8608C50C4F@ex9.hostedexchange.local> References: <435DF58A933BA74397B42CDEB8145A8608C50C4F@ex9.hostedexchange.local> Message-ID: <1169681909.3499.29.camel@portable-evil> On Wed, 2007-01-24 at 14:57 -0800, Robert Brewer wrote: > 1. Expressions: pure Python lambda querying. This is perhaps the most > appealing feature of Dejavu. Actually I just went and looked and personally I find the documentation the most appealing feature. Regards, Cliff From jan.dries at dcube-resource.be Wed Jan 3 16:02:13 2007 From: jan.dries at dcube-resource.be (Jan Dries) Date: Wed, 03 Jan 2007 22:02:13 +0100 Subject: Unsubscribing from the list In-Reply-To: <880dece00701031247l3d2354a3le318340653969de8@mail.gmail.com> References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> <880dece00701031247l3d2354a3le318340653969de8@mail.gmail.com> Message-ID: <459C19D5.2040706@dcube-resource.be> Dotan Cohen wrote: > On 03/01/07, Robert Kern wrote: >> He misunderstood you (as I nearly did, too). The way you phrased "decided that >> there was no futher interest on the page for me" is somewhat ambiguous: it can >> seem like it refers to the second time, not the first. >> > > Ah. Sorry. I'm getting better at confusing people :) > > if ($you=="got_offended") { > $dotan="sorry"; > } Except that on this list, you might offend people just by using vulgar language like that. Better rephrase it to: if you == "got_offended": dotan = "sorry" Regards, Jan From tjreedy at udel.edu Wed Jan 31 14:47:30 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 Jan 2007 14:47:30 -0500 Subject: how to "free" an object/var ? References: Message-ID: "John Nagle" wrote in message news:AAXvh.1465$zH1.1114 at newssvr29.news.prodigy.net... | If your data structure has no backlinks, it will go away | as soon as the last reference to it disappears. | In Python, garbage collection is mostly a backup to | the reference counting system. These both are true of the CPython implementation (current and known future, at least) but not of other implementations and not of the language itself. The same comment applies to some other posts in this thread. GC, if any, is implementation defined. tjr From ptmcg at austin.rr._bogus_.com Mon Jan 8 02:20:38 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 8 Jan 2007 01:20:38 -0600 Subject: regex question References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> Message-ID: <45a1f0c6$0$18929$4c368faf@roadrunner.com> "proctor" <12cc104 at gmail.com> wrote in message news:<1168232001.377605.236270 at 11g2000cwr.googlegroups.com>... > hello, > > i hope this is the correct place... > > i have an issue with some regex code i wonder if you have any insight: > > ================ There's nothing actually *wrong* wth your regex. The problem is your misunderstanding of raw string notation. In building up your regex, do not start the string with "r'" and end it with a "'". def makeRE(w): print w + " length = " + str(len(w)) # reString = "r'" + w[:1] reString = w[:1] w = w[1:] if len(w) > 0: for c in (w): reString += "|" + c # reString += "'" print "reString = " + reString return reString Or even better: def makeRE(w): print w + " length = " + str(len(w)) reString = "|".join(list(w)) return reString Raw string notation is intended to be used when the string literal is in your Python code itself, for example, this is a typical use for raw strings: ipAddrRe = r'\d{1,3}(\.\d{1,3}){3}' If I didn't have raw string notation to use, I'd have to double up all the backslashes, as: ipAddrRe = '\\d{1,3}(\\.\\d{1,3}){3}' But no matter which way I create the string, it does not actually start with "r'" and end with "'", those are just notations for literals that are part of your Python source. Does this give you a better idea of what is happening? -- Paul From smusnmrNOSPAM at yahoo.com Mon Jan 15 06:00:33 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Mon, 15 Jan 2007 12:00:33 +0100 Subject: Problem with findinf wx modules solved References: Message-ID: I included the "...\wxDemos" path in PYTHONPATH. Everthing fine now! "siggi" schrieb im Newsbeitrag news:eo5hpp$2tmo$1 at zam602.zam.kfa-juelich.de... > "Tim Roberts" wrote: >>> >>>when I do >>>sys.path in IDLE (winXP), i get a horrendously long list of >>>paths, paths I may have used during a lot of trials and errors. How can I >>>clean up sys.path? I mean, trim it of unnecessary paths? >> >> What do mean by "used during a lot of trials and errors"? sys.path is >> recreated from scratch every time Python starts. It doesn't accumulate >> over time, other than from new packages that you install. >> -- >> Tim Roberts, timr at probo.com >> Providenza & Boekelheide, Inc. > > > Sorry Tim, my statement was not correct, due to my inexperience with > Python. > And sorry, too, for my somewhat lengthy reply: > After having had inspected my current sys.path... > > ['C:\\Documents and Settings\\User\\My Documents\\My Python files', > 'C:\\Documents and Settings\\User\\My Documents\\Python25\\Lib\\idlelib', > 'C:\\Documents and Settings\\User\\My Documents\\Python25\\python25.zip', > 'C:\\Documents and Settings\\User\\My Documents\\Python25\\DLLs', > 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib', > 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\plat-win', > 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\lib-tk', > 'C:\\Documents and Settings\\User\\My Documents\\Python25', 'C:\\Documents > and Settings\\User\\My Documents\\Python25\\lib\\site-packages', > 'C:\\Documents and Settings\\User\\My > Documents\\Python25\\lib\\site-packages\\PIL', 'C:\\Documents and > Settings\\User\\My Documents\\Python25\\lib\\site-packages\\win32', > 'C:\\Documents and Settings\\User\\My > Documents\\Python25\\lib\\site-packages\\win32\\lib', 'C:\\Documents and > Settings\\User\\My Documents\\Python25\\lib\\site-packages\\Pythonwin', > 'C:\\Documents and Settings\\User\\My > Documents\\Python25\\lib\\site-packages\\wx-2.8-msw-ansi'] > > or in plain DOS: > > C:\Documents and Settings\User\My Documents\My Python files > C:\Documents and Settings\User\My Documents\Python25\Lib\idlelib > C:\Documents and Settings\User\My Documents\Python25\python25.zip > C:\Documents and Settings\User\My Documents\Python25\DLLs > C:\Documents and Settings\User\My Documents\Python25\lib > C:\Documents and Settings\User\My Documents\Python25\lib\plat-win > C:\Documents and Settings\User\My Documents\Python25\lib\lib-tk > C:\Documents and Settings\User\My Documents\Python25 > C:\Documents and Settings\User\My Documents\Python25\lib\site-packages > C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\PIL > C:\Documents and Settings\User\My > Documents\Python25\lib\site-packages\win32 > C:\Documents and Settings\User\My > Documents\Python25\lib\site-packages\win32\lib > C:\Documents and Settings\User\My > Documents\Python25\lib\site-packages\Pythonwin > C:\Documents and Settings\User\My > Documents\Python25\lib\site-packages\wx-2.8-msw-ansi > > ...it just looked horrible to me at first sight! > > If I interpret your explanation correctly, all these paths are necessary, > and not relics of previous installations and deinstallations. > > What puzzles me, though, is, that e.g., when I run the wxPython > application > "AnalogClock.py" with IDLE or in the command line , this works only in the > directory "...\My Python files\wxDemos\" . This directory contains all > files > and folders from the original "\wx-2.8-msw-ansi\demos\"). > > When I copy AnalogClock.py to ...\My Python Files\ , nothing happens > after > running it with IDLE or in the command line. > Appending 'C:\Documents and Settings\User\My Documents\My Python > files\wxDemos ' to the sys.path does not help either. > > Thinking that I am clever, I changed my sys.path with sclicing and > concatenation such that my sys.path starts with > > 'C:\Documents and Settings\User\My Documents\My Python files', > 'C:\Documents > and Settings\User\My Documents\My Python files\wxDemos'. Now \wxDemos\ is > being searched very early. > > ... no way! After running AnalogClock.py again, this error message > appears: > > ------------------------------------------ > Traceback (most recent call last): > File "C:\Documents and Settings\My Documents\My Python > files\wxAnalogClock.py", line 14, in > import wx > ImportError: No module named wx. > ------------------------------------------ > > Very strange! Because all this wx stuff IS IN the directory 'C:\Documents > and Settings\User\My Documents\My Python files\wxDemos'. And > AnalogClock.py > does work when residing in that directory. > > Can you help me again? > > Thanks, > > siggi > > P.S. On another PC where the python program is in c:\programs\python25\, > same as above! > > > > > > From donn at u.washington.edu Tue Jan 9 17:53:37 2007 From: donn at u.washington.edu (Donn Cave) Date: Tue, 09 Jan 2007 14:53:37 -0800 Subject: Non-blocking pipes during subprocess handling References: <22q5q25jn7dfti18rv1tshj7os5a0gm27r@4ax.com> Message-ID: In article <22q5q25jn7dfti18rv1tshj7os5a0gm27r at 4ax.com>, Tom Plunket wrote: > I'm using subprocess to launch, well, sub-processes, but now I'm > stumbling due to blocking I/O. > > Is there a way for me to know that there's data on a pipe, and possibly > how much data is there so I can get it? Currently I'm doing this: > > process = subprocess.Popen( > args, > bufsize=1, > universal_newlines=True, > stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > > def ProcessOutput(instream, outstream): > text = instream.readline() > if len(text) > 0: > print >>outstream, text, > return True > else: > return False I think it would be fair to say that your problem is not due to blocking I/O, so much as buffered I/O. Since you don't appear to need to read one line at a time, you can detect and read data from the file descriptor without any buffering. Don't mix with buffered I/O, as this will throw the select off. From memory - better check, since it has been a while since I wrote anything real like this (or for that matter much of anything in Python) -- import select def ProcessOutput(instream, outstream): fdr = [instream.fileno()] (r, w, e) = select.select(fdr, [], [], 0.0) for fd in r: text = os.read(fd, 4096) outstream.write(text) Donn Cave, donn at u.washington.edu From durumdara at gmail.com Wed Jan 3 07:30:22 2007 From: durumdara at gmail.com (durumdara) Date: Wed, 03 Jan 2007 13:30:22 +0100 Subject: [Half-off] How to get textboxes (text blocks) from ps/pdf files? Message-ID: <459BA1DE.7040205@gmail.com> Hi! I need to get textboxes/textblocks from pdf files. I can convert them into ps. Is anyone knows about method, trick, routine to I can get the textboxes from ps or pdf? (Pythonic, COM, or command line solutions needed.) I need to redraw them into my application, and user can reorder them, and next I concat. every text to process it. I need these infos: x, y, w, h, text Example: page1 textbox1{x:100,y:100;w:600;h:27;text:"TextBox1 /xfc /xfa"} textbox2{x:100,y:180;w:600;h:27;text:"TextBox2"} page2 textbox1{x:100,y:100;w:600;h:27;text:"TextBox1"} textbox2{x:100,y:180;w:600;h:27;text:"TextBox2"} ... Any solution? Thanks for it! dd ps1: I tried every pdf2text and pdf2html application. All failed in the test. Only one provide good informations, the pdftohtml, because it is makes divs with abs. position and size and the texts. But this program is not handle the iso-8859-2 chars, so I lost them. ps2: The program must run under Windows XP. So the solution is os specific. From grahn+nntp at snipabacken.dyndns.org Mon Jan 22 15:46:23 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 22 Jan 2007 20:46:23 GMT Subject: Is any python like linux shell? References: <1169398326.510530.180860@51g2000cwl.googlegroups.com> Message-ID: On Sun, 21 Jan 2007 22:10:17 -0800, James Stroud wrote: > Frank Potter wrote: >> I learned some python in windows. >> And now I've turned to linux. >> I read a book and it teaches how to write shell script with bash, >> but I don't feel like the grammar of bash. ... > My strongest advice would be to let go of the idea of "shell scripting" > altogether and begin to write programs built from libraries to solve > your problems. Shell scripting is "building from libraries". In this case, other executables are the libraries. > The mere act of beginning to write a shell script (in, > say, bash) will tie you to that "language", In what way is shell scripting different from Python scripting here? > even when you realize your > task was much more complex than you had originally imagined. It has > happened to me time and time again. Opinions differ, of course. Me, I don't hesitate to write Bourne shell scripts when that seems like the straightforward idea. Then it's my responsibility to move to something else -- usually Python -- if the problem grows out of its language. (And I have to admit, I don't let it grow very complex before I make that choice, because I don't known Bourne shell that well.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From bearophileHUGS at lycos.com Wed Jan 3 17:46:20 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 Jan 2007 14:46:20 -0800 Subject: static object In-Reply-To: <459c306c$0$314$426a74cc@news.free.fr> References: <459c306c$0$314$426a74cc@news.free.fr> Message-ID: <1167864379.679648.267340@42g2000cwt.googlegroups.com> That looks like some kind of singleton. Why don't you use a module instead of a class? Another solution is to define your data as class attributes. Bye, bearophile From manstey at csu.edu.au Sun Jan 28 23:24:23 2007 From: manstey at csu.edu.au (manstey) Date: 28 Jan 2007 20:24:23 -0800 Subject: sending a class as an argument Message-ID: <1170044663.163303.131930@v45g2000cwv.googlegroups.com> Hi, Our class has its attributes set as classes, as in MyClass.Phone.Value='34562346' MyClass.Phone.Private=True Inside the MyClass definition we have a function like this: def MyFunc(self,clsProperty): if clsProperty.Private: print 'Private property' else: print ClsProperty.Value In our code, we then call >>> MyClass.MyFunc(MyClass.Phone) We want to be able in our code instead simply to call: >>> MyClass.MyFunc(Phone) or MyClass.MyFunc('Phone') But we can't get it to work. If we rewrite the function as follows: def MyFunc(self,attr): if self.attr.Private: print 'Private' else: print self.attr.Value we get an error. Is there a better way to do this? Thanks From joshua at eeinternet.com Tue Jan 23 17:17:12 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 23 Jan 2007 13:17:12 -0900 Subject: My python programs need a GUI, wxPython or PyQt4? References: Message-ID: <45b67cc1$0$24377$88260bb3@free.teranews.com> Daniel Jonsson wrote: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! Wow...are you *trying* to start a flamewar? :) Anyway, here are a few points to think about. This is by no means exhaustive, and I'm sure others will add to (and/or correct) what I say. I'm most familiar with Qt, so my comments will be directed that way. Qt4 *is* GPL, but you can only use it for free if the software you're writing is GPL. So, if there is no issue with you making your source code public, there is no problem using Qt. wxWindows is essentially LGPL, so might be easier to use, depending on how closely you need to hold your source code. wxWindows uses Gtk widgets on *nix. In *my opinion* the Qt widgets look better, but that's just me. >From what I've seen of the PyQt4 API, it's very clean and easy to use. You can design your forms using the standard QtDesigner and compile them to Python by using py-uic. You can also load .ui files at run time if you want. I have no idea of the form design facilities in wxWindows, others can add their input there. It's very easy to create forms with QtDesigner. And also easy to make sure they still nicely laid out and proportionate by using layouts and spacers. Anyway, those are the thoughts off the top of my head, I'll chime in again if I think of more. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From mart_in_medina at ya___.es Wed Jan 10 10:20:54 2007 From: mart_in_medina at ya___.es (martin griffith) Date: Wed, 10 Jan 2007 16:20:54 +0100 Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> <1p9d74-5i71.ln1@stratos.fenelon.com> Message-ID: On Tue, 9 Jan 2007 20:16:01 +0000, in comp.arch.embedded Pete Fenelon wrote: >In comp.arch.embedded octabox at gmail.com wrote: >> Hello all, >> >> I represent Octabox, an Internet Start-up developing a wide-scale > >Hello. F*ck off, spammer. > > >pete a bit more subtle http://www.tagzin.com/main.aspx?cat=v&q=history martin From steven.bethard at gmail.com Sun Jan 28 01:49:02 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 27 Jan 2007 23:49:02 -0700 Subject: distutils, sdist and tests In-Reply-To: References: Message-ID: Robert Kern wrote: > Steven Bethard wrote: >> How do I get distutils to include my testing module in just the "sdist" >> distribution? > > Use a MANIFEST. Thanks again to Robert Kern for all the help. For the record, in the end all I did was add a MANIFEST.in file with the single line: include test_argparse.py and "test_argparse.py" got included in the source distribution and left out of the binary distributions. It's a pity there's no way to specify something this simple in the setup.py file, but since I'm not offering to maintain distutils, I guess I don't really have a right to complain. ;-) STeVe From kj7ny at nakore.com Thu Jan 11 19:52:12 2007 From: kj7ny at nakore.com (kj7ny) Date: 11 Jan 2007 16:52:12 -0800 Subject: Is there a good example on instantiating, calling, using, an API from Python on Windows? In-Reply-To: <45A6CA45.3000300@websafe.com> References: <1168541166.457806.133320@p59g2000hsd.googlegroups.com> <45A6CA45.3000300@websafe.com> Message-ID: <1168563132.224441.212130@51g2000cwl.googlegroups.com> To be more exact, I am trying to use Python to talk to a Livelink system (http://www.opentext.com/) through their LAPI interface (.dll's, I think). I'll see if I can generate a more intelligent answer to your question, but for now, I'm far enough in the dark that this is as good as I can get. Thanks, From jdillworth at gmail.com Wed Jan 3 11:49:12 2007 From: jdillworth at gmail.com (Jeremy Dillworth) Date: 3 Jan 2007 08:49:12 -0800 Subject: Synchronization methodology In-Reply-To: References: Message-ID: <1167842950.012349.207780@s34g2000cwa.googlegroups.com> Hi Chris, Have you looked at the mutex module? Jeremy From gandalf at designaproduct.biz Tue Jan 9 04:39:59 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 09 Jan 2007 10:39:59 +0100 Subject: How to write temporary data to file? In-Reply-To: <45A31767.9030404@gmx.net> References: <45A31767.9030404@gmx.net> Message-ID: <45A362EF.1080006@designaproduct.biz> Thomas Ploch ?rta: > Hi folks, > > I have a data structure that looks like this: > > d = { > 'url1': { > 'emails': ['a', 'b', 'c',...], > 'matches': ['d', 'e', 'f',...] > }, > 'url2': {... > } > > This dictionary will get _very_ big, so I want to write it somehow to a > file after it has grown to a certain size. > > How would I achieve that? > How about dbm/gdbm? Since urls are strings, you can store this dict in a database instance and actually use it from your program as it were a dict? Laszlo From nogradi at gmail.com Sat Jan 13 09:18:58 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 13 Jan 2007 15:18:58 +0100 Subject: sqlobject 0.8.0b1 and python 2.5 Message-ID: <5f56302b0701130618u4f47296fv73426a32064e81cd@mail.gmail.com> Hi list, I get loads of DeprecationWarnings while using sqlobject 0.8.0b1 with python 2.5. Does this mean that the sqlobject project is not very up to date? Or should I just ignore them and happily use it? In general, what's the status of sqlobject, will it be dropped altogether after sqlobject2 is out? Anyone's experience with this version of sqlobject would be very helpful. Since I'm starting to use sqlobject right now, if there is a similar ORM tool that is comparable but up to date and actively developed, that would be an option too. (Things like SQLAlchemy are waaaay to complicated and complex for my needs. :)) Thanks, Daniel From tim.one at comcast.net Mon Jan 8 14:09:02 2007 From: tim.one at comcast.net (Tim Peters) Date: Mon, 08 Jan 2007 13:09:02 -0600 Subject: Q: About a programming problem with Python! References: <1168270884.957998.251150@51g2000cwl.googlegroups.com> Message-ID: [followups set to comp.lang.python] [Danny] > I am just getting into OOP using Python and > because of the floating point of large integer (L) > square roots all the decimal expansions are truncated. > This has created a problem because I need these > decimal expansions in my algorithm other wise > it adds more sub iterations slowing down > greatly to the programs performance. > > Is there any way of retrieving these truncated decimal > expansions up to a certain (n) with Python? You want comp.lang.python for this, not sci.math. Be sure to give a concrete example, giving a specific input and showing exactly as possible what you /want/ to achieve. There are so many possible ambiguities in what you wrote here that few people will take time to guess at what you might have intended to ask. > Java and I believe c++ do not have this problem > but I am not about to learn any of these because > I like Python. Programming language has little to nothing to do with this, it's the data type you're using. In Java, C++, and Python, if you're using the native double-precision floating-point type, you're limited to (on most machines) at most 53 bits of precision. If you need more than that, you need to use a different data type. For example, in recent versions of Python you could use the `decimal` module, and set its precision to virtually anything you like; e.g., under Python 2.5, >>> import decimal >>> t = decimal.Decimal(2) >>> decimal.getcontext().prec # show the default precision 28 >>> print t.sqrt() # sqrt(2) rounded to 28 significant digits 1.414213562373095048801688724 >>> decimal.getcontext().prec = 56 # double the precision >>> print t.sqrt() # sqrt(2) to rounded to 56 significant digits 1.4142135623730950488016887242096980785696718753769480732 From bignose+hates-spam at benfinney.id.au Mon Jan 15 16:54:09 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 Jan 2007 08:54:09 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <874pqs7y7y.fsf@benfinney.id.au> dickinsm at gmail.com writes: > Suppose you're writing a class "Rational" for rational numbers. The > __init__ function of such a class has two quite different roles to > play. That should be your first clue to question whether you're actually needing separate functions, rather than trying to force one function to do many different things. > First, it's supposed to allow users of the class to create Rational > instances; in this role, __init__ is quite a complex beast. The __init__ function isn't the "constructor" you find in other languages. Its only purpose is to initialise an already-created instance, not make a new one. > It needs to allow arguments of various types---a pair of integers, a > single integer, another Rational instance, and perhaps floats, Decimal > instances, and suitably formatted strings. It has to validate the > input and/or make sure that suitable exceptions are raised on invalid > input. And when initializing from a pair of integers---a numerator > and denominator---it makes sense to normalize: divide both the > numerator and denominator by their greatest common divisor and make > sure that the denominator is positive. All of this points to having a separate constructor function for each of the inputs you want to handle. > But __init__ also plays another role: it's going to be used by the > other Rational arithmetic methods, like __add__ and __mul__, to > return new Rational instances. No, it won't; those methods won't "use" the __init__ method. They will use a constructor, and __init__ is not a constructor (though it does get *called by* the construction process). > For this use, there's essentially no need for any of the above > complications: it's easy and natural to arrange that the input to > __init__ is always a valid, normalized pair of integers. Therefore, make your __init__ handle just the default, natural case you identify. class Rational(object): def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator > So the question is: (how) do people reconcile these two quite > different needs in one function? By avoiding the tendency to crowd a single function with disparate functionality. Every function should do one narrowly-defined task and no more. @classmethod def from_string(input): (n, d) = parse_elements_of_string_input(input) return Rational(n, d) @classmethod def from_int(input): return Rational(input, 1) @classmethod def from_rational(input): (n, d) = (input.numerator, input.denominator) return Rational(n, d) def __add__(self, other): result = perform_addition(self, other) return result def __sub__(self, other): result = perform_subtraction(self, other) return result Put whatever you need to for 'parse_elements_of_string_input', 'perform_addition', 'perform_subtraction', etc; either the calculation itself, if simple, or a call to a function that can contain the complexity. Use Python's exception system to avoid error-checking all over the place; if there's a problem with the subtraction, for instance, let the exception propagate up to the code that gave bad input. The alternate constructors are decorated as '@classmethod' since they won't be called as instance methods, but rather: foo = Rational.from_string("355/113") bar = Rational.from_int(17) baz = Rational.from_rational(foo) -- \ "If you can't beat them, arrange to have them beaten." -- | `\ George Carlin | _o__) | Ben Finney From martin at v.loewis.de Thu Jan 4 03:36:09 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Jan 2007 09:36:09 +0100 Subject: Cannot build 2.5 on FC6 x86 In-Reply-To: <503a8vF1d8dn2U1@mid.individual.net> References: <502e72F1eh7ngU1@mid.individual.net> <459c0ac1$0$28366$9b622d9e@news.freenet.de> <503a8vF1d8dn2U1@mid.individual.net> Message-ID: <459CBC79.8040901@v.loewis.de> Paul Watson schrieb: > Martin v. L?wis wrote: >> Paul Watson schrieb: >>> ./configure >>> make >>> make test >>> >>> The result appears to hang after the test_tkl... line. I had to kill >>> the 'make test' process which terminated it. Any suggestions? The only suggestion then is that you (or somebody else) would need to debug the interpreter to find out what is happening - this specific behaviour is not supposed to happen. Regards, Martin From fuzzyman at gmail.com Sun Jan 7 14:33:55 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Jan 2007 11:33:55 -0800 Subject: Capturing stderr and stdout of a subprocess as a single stream Message-ID: <1168198435.629380.136080@42g2000cwt.googlegroups.com> Hello all, Before I ask the question a couple of notes : * This question is for implementing a script inside the Wing IDE. For some reason using the subprocess module doesn't work so I need a solution that doesn't use this module. * The platform is Windows and I'm happy with a Windoze only solution. :-) I would like to execute subprocesses asynchronously and capture stdout / stderr as a single stream. If I use "os.popen3(executable)" it gives me separate pipes for stdout and stderr, but reads from them are blocking. The output on stdout and stderr may be interleaved and I would like to display them *as* they arrive. That means I can't just read from them and output the results. The only solution I can think of is to read from both a character at a time on two separate threads, putting the data into a queue. A separate thread could pull characters off the queue and display them. (I don't need to differentiate between stdout and stderr when I display.) Can anyone think of a better solution ? My current code works, but *doesn't* capture stderr : from threading import Thread pipe = os.popen(executable) def DisplayOutput(): while True: output = pipe.read(1) if not output: break display(output) Thread(target=DisplayOutput).start() All the best, Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From pierre at saiph.com Mon Jan 8 11:14:43 2007 From: pierre at saiph.com (Imbaud Pierre) Date: Mon, 08 Jan 2007 17:14:43 +0100 Subject: closed issue In-Reply-To: <4594130c$0$318$426a74cc@news.free.fr> References: <4594130c$0$318$426a74cc@news.free.fr> Message-ID: <45a26d04$0$317$426a74cc@news.free.fr> I submitted a bug, to sourceforge. Was answered (pretty fast) the file I dealt with was the buggy part. I then submitted a bug to the file author, who agreed, and fixed. End of the story. All I could complain about, with the xml.dom library, is how obscure the exception context was: I did violate SOME xml rule, ideally the exception should show the rule, and the faulty piece of data. But I know this has a cost, both runtime cost and developper-s time cost. Imbaud Pierre a ?crit : > I am using the standard xml library to create another library able to > read, and maybe write, > xmp files. > Then an xml library bug popped out: > xml.dom.minidom was unable to parse an xml file that came from an > example provided by an official organism.(http://www.iptc.org/IPTC4XMP) > The parsed file was somewhat hairy, but I have been able to reproduce > the bug with a simplified > version, that goes: > > > > xmlns:iX='http://ns.adobe.com/iX/1.0/'> > > xmlns:xmpPLUS='XMP Photographic Licensing Universal System (xmpPLUS, > http://ns.adobe.com/xap/1.0/PLUS/)'> > False > False > > > > > > > The offending part is the one that goes: xmpPLUS='....' > it triggers an exception: ValueError: too many values to unpack, > in _parse_ns_name. Some debugging showed an obvious mistake > in the scanning of the name argument, that goes beyond the closing > " ' ". > > Im aware I dont give here enough matter to allow full understanding > of the bug. But thats not the place for this, and thats not my point. > > Now my points are: > - how do I spot the version of a given library? There is a __version__ > attribute of the module, is that it? > - How do I access to a given library buglist? Maybe this one is known, > about to be fixed, it would then be useless to report it. > - How do I report bugs, on a standard lib? > - I tried to copy the lib somewhere, put it BEFORE the official lib in > "the path" (that is:sys.path), the stack shown by the traceback > still shows the original files being used. Is there a special > mechanism bypassing the sys.path search, for standard libs? (I may > be wrong on this, it seems hard to believe...) > > - does someone know a good tool to validate an xml file? > > > btw, my code: > > from nxml.dom import minidom > ... > class whatever: > def __init__(self, inStream): > xmldoc = minidom.parse(inStream) > > > > Thanks for any help... From weekender_ny at yahoo.com Sat Jan 13 23:49:53 2007 From: weekender_ny at yahoo.com (John) Date: 13 Jan 2007 20:49:53 -0800 Subject: Threaded for loop In-Reply-To: <7xr6ty8ugv.fsf@ruckus.brouhaha.com> References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> <7xr6ty8ugv.fsf@ruckus.brouhaha.com> Message-ID: <1168750192.222440.89450@a75g2000cwd.googlegroups.com> Damn! That is bad news. So even if caclulate is independent for (i,j) and is computable on separate CPUs (parts of it are CPU bound, parts are IO bound) python cant take advantage of this? Surprised, --j Paul Rubin wrote: > "John" writes: > > I want to do something like this: > > > > for i = 1 in range(0,N): > > for j = 1 in range(0,N): > > D[i][j] = calculate(i,j) > > > > I would like to now do this using a fixed number of threads, say 10 > > threads. What is the easiest way to do the "parfor" in python? > > It won't help in terms of actual parallelism. Python only lets one > thread run at a time, even on a multi-cpu computer. From rkmr.em at gmail.com Fri Jan 12 15:30:25 2007 From: rkmr.em at gmail.com (mark) Date: Fri, 12 Jan 2007 12:30:25 -0800 Subject: dynamic argument name for functions In-Reply-To: <1168633680.3382.96.camel@dot.uniqsys.com> References: <8c7f10c60701121222p2187225fn3e0559388a83a16e@mail.gmail.com> <1168633680.3382.96.camel@dot.uniqsys.com> Message-ID: On 1/12/07, Carsten Haese wrote: > > On Fri, 2007-01-12 at 20:22 +0000, Simon Brunning wrote: > > On 1/12/07, mark wrote: > > > I want to pass a value to an argument of a function. The argument name > is > > > dynamic and is stored in a > > > variable. How do I call the function using with arg_name and value as > the > > > parameters. > > > thanks > > > arg_name = 'arg1' > > > arg_value = 'i am passing a value to argument 1' > > > function(???????) > > > > Untested: > > > > function(**{arg_name: arg_value}) > > My version is superior: I tested it before replying. ;) both work like charm! ;-)! thanks mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Wed Jan 3 01:21:46 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 3 Jan 2007 08:21:46 +0200 Subject: list/dictionary as case statement ? References: Message-ID: <015101c72f00$8c43af60$03000080@hendrik> "Stef Mientki" wrote: > > If I'm not mistaken, I read somewhere that you can use > function-names/references in lists and/or dictionaries, but now I can't > find it anymore. > > The idea is to build a simulator for some kind of micro controller (just > as a general practise, I expect it too be very slow ;-). > > opcodes ={ > 1: ('MOV', function1, ...), > 2: ('ADD', function2, ), > 3: ('MUL', class3.function3, ) > } > > def function1 > # do something complex > > > Is this possible ? the short answer is : "Yes" a slightly longer answer depends on what you want to do If you want to write a simple assembler, your dict will look something like: Mnemonics_to_Opcodes = {"MOV": [Functionnameforopcodeandtwooperands,movopcode], "NOP":[Functionnameforopcodeonly,nopopcode], "SETB":[Functionnameforopcodeandoneoperand,setbopcode], "JMP":[Functionnameforopcodeandoneoperand,jmpopcode], ... } if you want to write a simulator only that "executes" the hex or binary, then your dict needs to be something like this: Opcodes = {movopcode:[MovFunction,movinstructionlen], nopopcod:[NopFunction,nopinstructionlen], setbopcode:[SetbFunction,setbinstructionlen], jmpopcode:[JmpFunction,jmpinstructionlen], ... } and then you write an "instruction fetcher" based on the Program Counter that uses the length data in the dict and calls the various functions with the operands as fetched from memory. The easiest is to make the PC a global... It works well - and it is surprisingly fast too... And its easy if the opcodes are all say one byte, else you need an opcode length field too, and fancier parsing. This is not the hassle with this kind of thing - the hassle comes in trying to simulate the behaviour of the I/O of a real system... hth - Hendrik From robert.kern at gmail.com Fri Jan 19 01:57:58 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 19 Jan 2007 00:57:58 -0600 Subject: Why this script can work? In-Reply-To: References: Message-ID: Jm lists wrote: > Please help with this script: > > class ShortInputException(Exception): > '''A user-defined exception class.''' > def __init__(self,length,atleast): > Exception.__init__(self) > self.length=length > self.atleast=atleast > > try: > s=raw_input('Enter something --> ') > if len(s)<3: > raise ShortInputException(len(s),3) > # Other work can continue as usual here > except EOFError: > print '\nWhy did you do an EOF on me?' > except ShortInputException,x: > print 'ShortInputException: The input was of length %d, was > expecting at least %d' %(x.length,x.atleast) > else: > print 'No exception was raised.' > > > My questions are: > > 1) ShortInputException,x: what's the 'x'? where is it coming? It's the actual ShortInputException instance that was raised. Try printing x.length and x.atleast, for example. > 2) The 'if' and 'else' are not in the same indent scope,why this can work? This else: clause goes with the try: and except: clauses, not the if: clause. It is executed if no exception was raised. http://docs.python.org/ref/try.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From heikki at osafoundation.org Fri Jan 19 14:18:30 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 19 Jan 2007 11:18:30 -0800 Subject: More M2Crypto issues In-Reply-To: References: Message-ID: John Nagle wrote: > I've been running M2Crypto successfully using Python 2.4 on Windows 2000, > and now I'm trying to get it to work on Python 2.3.4 on Linux. > > Attempting to initialize a context results in > > Traceback (most recent call last): [...] > map()[long(self.ctx)] = self > ValueError: invalid literal for long(): _480e1008_p_SSL_CTX This is almost certainly because of SWIG that is too old. The minimum required is SWIG 1.3.24. If you cannot upgrade SWIG, the alternative would be to play around with these values to fit your version of SWIG. I'm adding this to the FAQ. -- Heikki Toivonen From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 15 13:45:57 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 15 Jan 2007 19:45:57 +0100 Subject: Looking for Job References: <1168881431.411312.98530@51g2000cwl.googlegroups.com> Message-ID: <5120f5F1hccevU2@mid.individual.net> fhk6431 at gmail.com wrote: > Any one looking for job.. I need someone good at phyton Sorry, you'll only sporadically find people competent with plants here. Regards, Bj?rn -- BOFH excuse #83: Support staff hung over, send aspirin and come back LATER. From paul at boddie.org.uk Mon Jan 8 13:49:48 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 8 Jan 2007 10:49:48 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <%Isoh.22447$X97.12337@newsfe18.lga> Message-ID: <1168282188.449637.94280@42g2000cwt.googlegroups.com> Chris Mellon wrote: > Private data in the C++ and Java OO worlds is so taught so much and > emphasized so often that people have started thinking of it as being > desirable for its own sake. But the primary motivation for it grew out > of the need to maintain compatible interfaces. This is generally true, yes. [...] > Python doesn't have these problems, so the only use for private > information is to warn your clients away from access to certain names. > There's no need for compiler enforcement of that, as a convention is > just as effective. You'll have to be more clear, here. If you're writing a subclass of some other class then any usage of private attributes in the superclass potentially provides the benefit of a free choice in attribute names in the subclass. If you wanted to warn people away from certain names, it would be the public attributes that would require the warning, noting that "your clients" in this context includes people extending classes as well as those merely instantiating and using them. > The remaining arguments are generally outgrowths of "but my code is > SECRET", which just isn't true in general, even less true of Python, > and not really a healthy attitude anyway. I don't care about secret attributes, and the namespace privacy aspect doesn't bother me enough to use private attributes anyway, especially since I'm the author of most of the superclasses I'm extending. But either providing namespace privacy or convenient tools to mitigate namespace sharing seems fairly important to me, at least. Paul From Eugene.Antimirov at portaone.com Wed Jan 31 09:39:13 2007 From: Eugene.Antimirov at portaone.com (Eugene Antimirov) Date: Wed, 31 Jan 2007 16:39:13 +0200 Subject: another newbie question: why should you use "*args" ? In-Reply-To: References: Message-ID: <45C0AA11.40407@portaone.com> stef wrote: > # method 2 > def chunk_plot(self, list): > for i in range ( len(list) ): > .... do something And one note more. Just to be more pythonic you shouldn't use form range(len(blabla)). Instead use: for i in list: ....blabla... -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer support at portaone.com From perica.zivkovic at gmail.com Fri Jan 12 17:09:41 2007 From: perica.zivkovic at gmail.com (perica.zivkovic at gmail.com) Date: 12 Jan 2007 14:09:41 -0800 Subject: Portable Python - free portable development environment ! In-Reply-To: References: <1168533423.224355.221390@k58g2000hse.googlegroups.com> Message-ID: <1168639781.763133.319580@s34g2000cwa.googlegroups.com> Right now there is not a big difference with Movable Python. - Smaller size but less libraries in default package - Portable Python comes with django - Uses SciTE not SPE but this is first release and I have big plans ;) grtz Perica Steve Holden wrote: > perica.zivkovic at gmail.com wrote: > > Hi there, > > > > I would like to announce the *first* beta release of the Portable > > Python 1.0 beta. From today Portable Python website is also online and > > you can find it on the location www.PortablePython.com. > > > > About: > > Portable Python is a Python programming language preconfigured to run > > directly from a portable device (USB stick, iPod etc.), enabling you to > > have, at any time, portable programming environment. Just download and > > extract to your portable device and in 10 minutes you are ready to > > create your next Python application. No registry modifications, > > installations, totally portable. > > > > Where to find it: > > http://www.portablepython.com > > > > regards, > > > > Perica Zivkovic > > > > P.S. did I mentioned that it is free? :-) > > > And what, besides is freeness, differentiates it from Movable Python? > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com From nmm1 at cus.cam.ac.uk Thu Jan 18 15:14:03 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 18 Jan 2007 20:14:03 GMT Subject: How to find out if another process is using a file References: Message-ID: In article , Donn Cave writes: |> In article , |> "Gabriel Genellina" wrote: |> > "Tom Wright" escribi? en el mensaje |> > news:eoo6vd$33u$1 at gemini.csx.cam.ac.uk... |> > |> > > I'm writing a program which reads a series of data files as they are |> > > dumped |> > > into a directory by another process. At the moment, it gets sporadic bugs |> > > when it tries to read files which are only partially written. |> > > |> > > I'm looking for a function which will tell me if a file is opened in |> > > write-mode by another process - if it is, my program will ignore it for |> > > now |> > > and come back to it later. This needs to work on linux and windows. Mac |> > > OS would be a bonus too. An os-independent solution would be good, but I |> > > could write os-specific options and have it pick the appropriate one. |> > |> > Use os.open with the O_EXCL flag; will fail if the other process has the |> > file still open (and will fail if another process is reading the file, too, |> > not just if someone is writing). |> |> O_EXCL fails if the file exists at all - whether closed or open. Yes. In theory. In practice, it usually works on normal files, provided that all opens are local. Under some circumstances, it will even work for NFS mounted files, as far as I recall. MVS (now zOS) and other mainframe systems had what the poster wants, but modern systems don't. I shall not recommend that the poster asks IBM for a copy of zOS, for reasons that will be well-known to anyone who used MVS (which are NOT the ones claimed by the Unix brigade, which are mostly bogus) :-) Under Linux, you can do something with fuser, and I am pretty certain that modern Macintoshes (i.e. BSD) will have an equivalent. It can't be made reliable (unlike under MVS), but might reduce the number of problems. Regards, Nick Maclaren. From cvanarsdall at mvista.com Fri Jan 26 19:07:20 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 26 Jan 2007 16:07:20 -0800 Subject: Off-Topic Posts In-Reply-To: <8FF0B818-AD0B-4743-8D95-A84A7955F532@datafly.net> References: <1169821615.198847.237790@m58g2000cwm.googlegroups.com> <1169852010.083168.81900@h3g2000cwc.googlegroups.com> <1169852537.508485.13260@v33g2000cwv.googlegroups.com> <8FF0B818-AD0B-4743-8D95-A84A7955F532@datafly.net> Message-ID: <45BA97B8.5000702@mvista.com> Yea, that guy sucks. Is there a list mod who can just ban this guy? Sean Schertell wrote: > Hey Genius -- I'm probably further to the left and even more > vehemently opposed to the Bush/Cheney regime than you are. But could > you *please* take your unwelcome ranting elsewhere? You're not > winning any converts here. And you're alienating your ideological > allies to boot. Give it a rest, m'kay? > > Sean > > P.S. Printing letters in all-caps and using extra exclamation points > doesn't necessarily make your argument any more compelling. > > > > > On Jan 27, 2007, at 8:02 AM, thermate at india.com wrote: > > >> What did Dick Faced Cheney told Honorable Senator Patrick Leahy ? >> "Fuck >> yourself". >> So much for politeness and vulgarity at the top level. >> >> Proof: >> http://www.capitolhillblue.com/news2/2007/01/the_madness_of.html >> >> On Jan 26, 2:53 pm, therm... at india.com wrote: >> >>> Yeah, listen to wise counsel of klein. As a member of conquered races >>> and still under occupation, namely Jewish, French, German, Japanese, >>> Korean ... dont mess in the crimes of the anglo-saxon yanks. You >>> should >>> remember the beating you got from the Anglo-Saxon Yanks and just keep >>> quiet ... As for the lunatics off their meds, its also true that 911 >>> was a grand optical illusion and thus within the charter of this >>> group >>> to study ... After all, one of its proponent is the former head of >>> Star >>> Wars, Dr Bob Bowman from MIT and Caltech ... Do you have a degree >>> from >>> those prestigious institutes or did you manage to get any of your >>> kids >>> into one of them ??? As for vulgarity, its the mark of patriotism ... >>> the constitutional amendments guarantee it and Herbert Walker Bush >>> was >>> a strongly suspected pedophile ... there is a video called conspiracy >>> of silence, watch it on video.google.com and download with before the >>> fascist bureau of incompetence bastards (running around like crazy >>> rats >>> to confiscate pentagon videos on that day in destruction of evidence) >>> try to sabotage the google servers ... they are part of the crime and >>> complicit in it. If they were competent, we would see one consistent >>> theory coming out from that bureau to explain all significant >>> events on >>> that day. Now dont forget the SHITTY job done by FEMA and NIST. There >>> are gaping holes in their work. >>> >>> Hey Kinch, if you are jewish, did you forget that England was the >>> first >>> country to expel the Jews. >>> >>> If you forget your status as conquered races, then you are in >>> delusion, >>> not anyone else. >>> >>> The final balance of power provided against the anglos will be by >>> Slavs. Hurray to Vladimir Putin, and Mikhail Khodorkovsky in a >>> Siberian >>> jail. >>> >>> On Jan 26, 1:13 pm, Richard J Kinch wrote: >>> >>> >>>> alex writes: >>>> >>>>> I have only just joined this group, but have noticed a >>>>> significant rise >>>>> in off-topic posts that really detract from what is otherwise an >>>>> excellent place to learn and talk about optics.This has nothing >>>>> to do with sci.optics. Recent days have seen this stuff >>>>> >>>> being broadcast mechanically into all sorts of groups. >>>> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > :::: DataFly.Net :::: > Complete Web Services > http://www.datafly.net > > -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From ernst.karner at gmail.com Mon Jan 15 05:24:50 2007 From: ernst.karner at gmail.com (diego) Date: 15 Jan 2007 02:24:50 -0800 Subject: Problem with win32pipe.popen2 Message-ID: <1168856689.749595.74440@q2g2000cwa.googlegroups.com> I'm trying to understand how popen2 works. Found in this group, that popen2.popen2 can cause trouble so i chose win32pipe.popen2. have a look a the listing of 2 files: ekmain.py: ************** import win32pipe (stdin1, stdout1) = win32pipe.popen2("test1.py") stdin1.write("1\n") print stdout1.readlines() # This will print the result. ************** test1.py: ************** a=raw_input("a=") print "***a=",a print "finished!" ************** i do not understand, why ekmain.py produces only following output: ['a='] why is the stdin1.write("1\n") command ignored? i tried to find an answer in this group by searching through existing article, but i had no success. tanks for you help! ernst p.s.: i working with python 2.3 on win2000. From http Thu Jan 25 15:00:56 2007 From: http (Paul Rubin) Date: 25 Jan 2007 12:00:56 -0800 Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> <1169754601.992058.205640@q2g2000cwa.googlegroups.com> Message-ID: <7xsldy7u6f.fsf@ruckus.brouhaha.com> "Paddy" writes: > No, you should think of the service that needs to be up. You seem to be > talking about how it can't be fixed rather than looking for ways to > keep things going. But you're proposing cargo cult programming. There is no reason whatsoever to expect that restarting the server now and then will help the problem in the slightest. Nick used the fancy term Poisson process but it just means that the probability of failure at any moment is independent of what's happened in the past, like the spontaneous radioactive decay of an atom. It's not like a mechanical system where some part gradually gets worn out and eventually breaks, so you can prevent the failure by replacing the part every so often. > A little learning is fine but "it can't theoretically be fixed" is > no solution. The best you can do is identify the unfixable situations precisely and work around them. Precision is important. The next best thing is have several servers running simultaneously, with failure detection and automatic failover. If a server is failing at random every few months, trying to prevent that by restarting it every so often is just shooting in the dark. Think of your server stopping now and then because there's a power failure, where you get power failures every few months on the average. Shutting down your server once a month, unplugging it, and plugging it back in will do nothing to prevent those outages. You need to either identify and fix whatever is causing the power outages, or install a backup generator. From tmaroff at yahoo.com Thu Jan 11 09:45:28 2007 From: tmaroff at yahoo.com (Tristan) Date: 11 Jan 2007 06:45:28 -0800 Subject: IDLE Python and Environment Variables In-Reply-To: References: <1168482248.828858.161320@i39g2000hsf.googlegroups.com> Message-ID: <1168526728.313917.309340@o58g2000hsb.googlegroups.com> Thanks Gabriel. > What kind of environment variables? Those used by Python itself, like > PYTHONPATH? Or your own variables, like FOO_LOCATION=C:\My\Projects\Lib\Foo I need to add to PYTHONPATH and other enviroment variables asked, for example, by DJANGO or other python products. > It appears that your variables are some kind of configuration - in > this case it has more sense to put such configuration in another > place, like a config file, and forget about environment variables. > You can use the usual .ini Windows format and read it with > ConfigParser. You can pass your script the name of the ini file to > read - this would be the equivalent of using different .bat files to > call the same script. > This way it doesn't matter whether you invoke your application using > python command line, or inside IDLE, or inside another environment. I considered to use it, thanks!! Incidentally (beg your pardon if it sounds to ignorance), can I define Environment variables in a config file and then apply to my python program? Thanks!!! From nmm1 at cus.cam.ac.uk Fri Jan 26 04:05:00 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 26 Jan 2007 09:05:00 GMT Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> <116975460 Message-ID: In article , skip at pobox.com writes: |> |> What makes you think Paddy indicated he wouldn't try to solve the problem? |> Here's what he wrote: |> |> What I'm proposing is that if, for example, a process stops running |> three times in a year at roughly three to four months intervals , and it |> should have stayed up; then restart the server sooner, at aa time of |> your choosing, whilst taking other measures to investicate the error. |> |> I see nothing wrong with trying to minimize the chances of a problem rearing |> its ugly head while at the same time trying to investigate its cause (and |> presumably solve it). No, nor do I, but look more closely. His quote makes it quite clear that he has got it firmly in his mind that this is a degradation problem, and so regular restarting will improve the reliability. Well, it could also be one where failure becomes LESS likely the longer the server stays up (i.e. the "settling down" problem). No problem is as hard to find as one where you are firmly convinced that it is somewhere other than where it is. Regards, Nick Maclaren. From bdesth.quelquechose at free.quelquepart.fr Mon Jan 29 16:26:28 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Jan 2007 22:26:28 +0100 Subject: List Behavior when inserting new items In-Reply-To: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> Message-ID: <45be5fa3$0$1529$426a34cc@news.free.fr> Drew a ?crit : > I'm looking to add an element to list of items, however I'd like to > add it at a specific index greater than the current size: > > list = [1,2,3] NB: better to avoid using builtins types and functions names as identifiers. > list.insert(10,4) > > What I'd like to see is something like: > > [1,2,3,,,,,,4] Hint : the Python representation of nothing is a singleton object named None. > However I see: > > [1,2,3,4] Yeps. I thought it would have raised an IndexError. But I seldom use list.insert() to append to a list - there's list.append() (and/or list.extend()) for this. > Is there any way to produce this kind of behavior easily? Hints: >>> [None] * 5 [None, None, None, None, None] >>> [1, 2, 3, None] + [10] [1, 2, 3, None, 10] HTH From smusnmrNOSPAM at yahoo.com Fri Jan 5 13:51:11 2007 From: smusnmrNOSPAM at yahoo.com (Siggi) Date: Fri, 5 Jan 2007 19:51:11 +0100 Subject: where is Microsoft Speech Object Library 5.1 option inPythonWin 2.5? References: Message-ID: Gabriel Genellina wrote: > After you download and install version 5.1, it should appear on the list. It should, but it does not! Shutting down and starting the WinXP Home system anew did not help. The SDK 5.1 installation went smoothly, however. What can I do to find out what is wrong? siggi "Gabriel Genellina" schrieb im Newsbeitrag news:mailman.2330.1168015570.32031.python-list at python.org... > At Friday 5/1/2007 11:24, siggi wrote: > >>However, in my Python 2.5/PythonWin 2.5 installation I find as only option >>"Microsoft Speech Object Library 5.0" to select. > > This list shows all the COM objects currently registered in Windows, does > not depend on Pythonwin. > >>Unfortunately, 5.1 is the lowest SDK version I found on >>http://www.microsoft.com/downloads/details.aspx?FamilyId=5E86EC97-40A7-453F-B0EE-6583171B4530&displaylang=en#QuickInfoContainer > > After you download and install version 5.1, it should appear on the list. > > > -- > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ Pregunt?. Respond?. > Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en > Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From alain.walter at thalesgroup.com Wed Jan 24 06:03:59 2007 From: alain.walter at thalesgroup.com (awalter1) Date: 24 Jan 2007 03:03:59 -0800 Subject: use of a GChildWatch source Message-ID: <1169636639.256213.146060@k78g2000cwa.googlegroups.com> Hello I am using python, pyGTK and GTK+ on HPUX (unix) In this context, the pygtk documentation about gobject.spawn_async says : ... you must use a GChildWatch source to be notified about the death of the child process ... Does someone know where to find details about GChildWatch ? I didn't retrieve any thing on the net. In addition, does someone be aware about some limitations concerning subprocesses creation in a python/GTK application Thanks a lot From fredrik at pythonware.com Thu Jan 25 05:11:54 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 Jan 2007 11:11:54 +0100 Subject: Fast Imaging for Webserver References: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> Message-ID: "Prateek" wrote: > Hi. I'm creating a web-application using CherryPy 2.2.1. My application > needs to process images (JPG/PNG files) to > > 1) create thumbnails (resize them) > 2) overlay them on a custom background (a simple frame) > 3) Overlay 'badges' (small 16x16 images) on top of the final thumbnail > > I am using PIL 1.1.5 which I have custom compiled on my development > machine (MacBook Pro 2.33Ghz Core Duo).. > I am using im.thumbnail for step 1 and im.paste for steps 2 and 3. > > The problem is that this thing is just way too slow. > For ab -n 1000 -C session_id=2f55ae2dfefa896f67a80f73045aadfa4b4269f1 > http://localhost:8080/imaging/icon/def/128/255 (where def is the name > of the image - default in this case - 128 is the size in pixels and 255 > is the background color), I am getting: > > Document Path: /imaging/icon/def/128/255 > Document Length: 14417 bytes > > Concurrency Level: 1 > Time taken for tests: 18.664 seconds > Complete requests: 1000 > Failed requests: 0 > Broken pipe errors: 0 > Total transferred: 14680000 bytes > HTML transferred: 14417000 bytes > Requests per second: 53.58 [#/sec] (mean) > Time per request: 18.66 [ms] (mean) > Time per request: 18.66 [ms] (mean, across all concurrent > requests) > Transfer rate: 786.54 [Kbytes/sec] received > > FYI: This request returns a PNG image (image/png) and not html > > My understanding is that the problem is either with the CherryPy setup > (which is likely because even in other cases, i don't get much more > than 65 requests per second) or PIL itself (even though I'm caching the > background images and source images) without knowing more about what kind of source images you're using, the amount of data they represent etc, it's not entirely obvious to me that 50+ images per second on a single server is that bad, really. unless the source images are rather tiny, that's plenty of pixels per second to crunch. are you really receiving more than 4500000 source images per day per server? From jstroud at mbi.ucla.edu Mon Jan 22 00:59:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 21 Jan 2007 21:59:08 -0800 Subject: Help with 'popen' In-Reply-To: <1169436640.161806.111510@38g2000cwa.googlegroups.com> References: <1169436640.161806.111510@38g2000cwa.googlegroups.com> Message-ID: stephen_b wrote: > Can someone let me know why this won't work? Thanks. > > >>>>from os import popen >>>>popen('export asdfasdf=hello').read() > > '' > >>>>popen('echo $asdfasdf').read() > > '\n' > > Thanks. > > Stephen > Python starts a new shell for each command, so your environment variable is lost. You probably want this, which makes the variable "permanent". py> import os py> os.environ['asdfasdf'] = 'hello' py> os.popen('echo $asdfasdf').read() 'hello\n' James From sturlamolden at yahoo.no Sun Jan 21 13:42:01 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 21 Jan 2007 10:42:01 -0800 Subject: A solution to the MSVCRT vs MSVCR71 problem? In-Reply-To: References: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> Message-ID: <1169404921.709667.192280@38g2000cwa.googlegroups.com> Gabriel Genellina wrote: > This would only work, if runtime dll's were compatibles between them, > and they are not. It is standard C, defined by ANSI and ISO. From roland.hedberg at adm.umu.se Wed Jan 3 03:29:01 2007 From: roland.hedberg at adm.umu.se (Roland Hedberg) Date: Wed, 03 Jan 2007 09:29:01 +0100 Subject: import order or cross import Message-ID: <459B694D.4060904@adm.umu.se> Hi! I'm having a bit of a problem with import. I'm writing a marshalling system that based on a specification will create one or more files containing mostly class definitions. If there are more than one file created (and there are reasons for creating more than one file in some instances) then they will import each other since there may be or is interdependencies in between them. And this is where the going gets tough. Let's assume I have the following files: ------------- ONE.py -------------------- import TWO class Car: def __init__(self): self.color = None def set_color(self,v): if isinstance(v,TWO.Black) or isinstance(v,TWO.White): self.color = v class BaseColor: def __init__(self): pass def __str__(self): return self.color if __name__ == "__main__": car = Car() color = TWO.Black() car.set_color(color) print car.color -------------- TWO.py ------------------- import ONE class Black(ONE.BaseColor): color = "Black" def __init__(self): ONE.BaseColor.__init__(self) class White(ONE.BaseColor): color = "White" def __init__(self): ONE.BaseColor.__init__(self) ----------------------------------------- Now, running ONE.py causes no problem it will print "Black", but running TWO.py I get: AttributeError: 'module' object has no attribute 'BaseColor' So, how can this be solved if it can be ? To join ONE.py and TWO.py into one file could be a solution if there where no other conditions (non-language based) that prevented it. -- Roland From http Mon Jan 29 09:06:21 2007 From: http (Paul Rubin) Date: 29 Jan 2007 06:06:21 -0800 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170064302.264009.12650@p10g2000cwp.googlegroups.com> Message-ID: <7xveiqapwi.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > from random import choice Security note: if you're trying to generate real passwords this way, you're better off using os.urandom instead of the random module to generate the random numbers. The random module's results are supposed to be statistically uncorrelated (good for stuff like games and simulations) but they don't try to resist guessing by malicious attackers. os.urandom results are supposed to be unguessable. From bj_666 at gmx.net Wed Jan 24 11:49:22 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 24 Jan 2007 17:49:22 +0100 Subject: Thoughts on using isinstance References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> Message-ID: In <1169656371.689791.216360 at v33g2000cwv.googlegroups.com>, abcd wrote: > Well my example function was simply taking a string and printing, but > most of my cases would be expecting a list, dictionary or some other > custom object. Still propose not to validate the type of data being > passed in? Yes because usually you don't expect a list or dictionary but some object that *acts* like a list or dictionary. Or you even expect just some aspects of the type's behavior. For example that it is something you can iterate over. Ciao, Marc 'BlackJack' Rintsch From S.Mientki-nospam at mailbox.kun.nl Sun Jan 28 10:58:01 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 28 Jan 2007 16:58:01 +0100 Subject: howto redirect and extend help content ? Message-ID: <1fc1a$45bcc7f4$d443bb3a$8806@news.speedlinq.nl> I'm making special versions of existing functions, and now I want the help-text of the newly created function to exists of 1. an extra line from my new function 2. all the help text from the old function # the old function def triang(M,sym=1): """The M-point triangular window. <== old help text """ .... # the new function def chunked_triang(M): """ Chunked version of "triang" <== the extra line """ >>> help(chunked_triang) # should give something like chunked_triang(M) <== the new definition Chunked version of "triang" <== the extra line The M-point triangular window. <== old help text Is that possible ? thanks, Stef Mientki From bearophileHUGS at lycos.com Fri Jan 19 16:30:55 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 Jan 2007 13:30:55 -0800 Subject: Py 2.5 on Language Shootout Message-ID: <1169242255.023147.310570@38g2000cwa.googlegroups.com> The The Computer Language Shootout has just published results for Python 2.5 and Psyco 1.5.2. Comparing the old (Python 2.4) Gentoo Pentium 4 results (now not visible anymore) with the new results, I have seen that all the tests with Python 2.5 are faster than the ones with Python 2.4 (some results can't be compared because N is changed): Gentoo Pentium 4, Python 2.4.3 measurements: Program & Logs CPU Time Memory KB GZip N binary-trees 99.26 15,816 402 16 chameneos Timout 5.000.000 cheap-concurrency 23,13 5.252 160 15.000 fannkuch 66,38 2.200 395 10 fasta 81,62 9.884 861 2.500.000 k-nucleotide 15,52 15.580 459 250.000 mandelbrot 363,86 2.412 472 3.000 n-body Timout 20.000.000 nsieve 9,79 34.416 269 9 nsieve-bits 164,72 42.412 320 11 partial-sums 38,64 2.300 410 2.500.000 pidigits 9,22 2.388 391 2.500 recursive 701,64 14.360 344 11 regex-dna 6,21 24.160 326 500.000 reverse-complement 2,7 46.032 272 2.500.000 spectral-norm 696,76 2.456 266 2.500 startup 6,38 29 200 sum-file 8,08 2.364 61 8.000 Regarding Psyco, two tests only are worse (the sourcecode, CPU and SO are the same): Old (Python 2.4.3, older Psyco): nsieve 4.22 22,680 211 9 reverse-complement 1.66 49,336 330 2,500,000 New (Python 2.5, Psyco 1.5.2): nsieve 4.26 22,904 211 9 reverse-complement 1.75 52,056 330 2,500,000 Bye, bearophile From ldo at geek-central.gen.new_zealand Fri Jan 5 01:48:44 2007 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 05 Jan 2007 19:48:44 +1300 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: In message , Piet van Oostrum wrote: > The scenario is as follows: Suppose the script starts with the line: > #!/usr/bin/python > > (using #!/usr/bin/env python would be disastrous because the user could > supply his own `python interpreter' in his PATH.) > > Now a malicious user can make a link to this file in his own directory, > e.g. to /Users/eve/myscript1. Because permissions are part of the file > (inode), not of the file name, this one is also suid. > > Now she execs /Users/eve/myscript1. The kernel, when honoring suid > scripts, would startup python with effective uid root with the command > line: /usr/bin/env /Users/eve/myscript1 No it wouldn't. This security hole was fixed years ago. From carsten at uniqsys.com Sat Jan 27 03:34:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 27 Jan 2007 03:34:15 -0500 Subject: python+ncurses: I can't display accents In-Reply-To: <45bb02bf$0$26684$426a34cc@news.free.fr> References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> <12rl5mq4nnqoea0@corp.supernews.com> <45bafda7$0$2417$426a74cc@news.free.fr> <45bb02bf$0$26684$426a34cc@news.free.fr> Message-ID: <20070127081443.M5483@uniqsys.com> On 27 Jan 2007 07:43:59 GMT, Fabrice DELENTE wrote > Incidentally, I noticed something about the environment: in my > script, I use the LINES and COLUMNS environment vars that are set in > my shell: > > columns=int(os.environ.get("COLUMNS")) > lines=int(os.environ.get("LINES")) > > In the shell, I get > > $ echo $LINES $COLUMNS > 89 199 > > but python doesn't get these values. I have to start the script with > > $ LINES=$LINES COLUMNS=$COLUMNS ./sort_entries.py > > How come? There is a distinction between shell variables and environment variables. In all likelihood, LINES and COLUMNS are shell variables, not environment variables. Try "export LINES COLUMNS" to set them as environment variables. HTH, Carsten. From gagsl-py at yahoo.com.ar Tue Jan 16 12:32:33 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 14:32:33 -0300 Subject: Check a windows service References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> Message-ID: "awel" escribi? en el mensaje news:1168966952.965088.17740 at l53g2000cwa.googlegroups.com... > I'm new in python and I would like to know if it's possible to check if > a specific windows service is present and if it's possible how can I > do? Yes, using the wmi module, but you'll have to search the Microsoft documentation on how to enumerate services and their properties: http://msdn2.microsoft.com/en-us/library/aa384642.aspx The code might look like this, but the names may be wrong: import wmi import pythoncom pythoncom.CoInitialize() w = wmi.WMI() for s in w.Win32_Services(): print s -- Gabriel Genellina From deets at nospam.web.de Wed Jan 3 20:52:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Jan 2007 02:52:07 +0100 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: References: <1167839629.435980.311750@k21g2000cwa.googlegroups.com> Message-ID: <5034u9F1dg9r9U1@mid.uni-berlin.de> > > I think that it *is* possible to do it, but a whole lot of work had to > be done to achieve this. It is all about how many rules (like how to > convert this block of unreadable code of language X into a readable > python block) you are willing to find/program (and these are a lot). It > is a almost gigantic task to make this work proper, but it definitely > *is* possible. It is definitely _not_ possible. There are so many design decisions that are differing based on what a language offers - e.g. generators, garbage collection, precise control over memory layout and so on. Projects like jython or ironpython show that to some degree at least binary compatibility is feasible - but beyond that, machine generated cod will always be that, and by no means idiomatic. Diez From mail at microcorp.co.za Sat Jan 27 04:30:19 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 27 Jan 2007 11:30:19 +0200 Subject: The reliability of python threads References: <45B90118.5010408@mvista.com><01b001c7411d$17e52a20$03000080@hendrik> <45BA39D3.7020400@mvista.com> Message-ID: <014501c741fa$64dbbbe0$03000080@hendrik> "Carl J. Van Arsdall" wrote: > Hendrik van Rooyen wrote: > > "Carl J. Van Arsdall" wrote: 8< --------------------------------------------------- > > > Yea, I do some of that too. I use that with conditional print > statements to stderr when i'm doing my validation against my test > cases. But I could definitely do more of them. The thing will be When I read this - I thought - probably your stuff is working perfectly - on your test cases - you could try to send it some random data and to see what happens - seeing as you have a test server, throw the kitchen sink at it. Possibly "random" here means something that "looks like" data but that is malformed in some way. Kind of try to "trick" the system to get it to break reliably. I'm sorry I can't be more specific - it sounds so weak, and you probably already have test cases that "must fail" but I don't know how to put it any better... - Hendrik From bytter at gmail.com Tue Jan 30 20:11:05 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Wed, 31 Jan 2007 01:11:05 +0000 Subject: Synchronous shutil.copyfile() In-Reply-To: References: Message-ID: <4e8efcf50701301711m1fb5a0ffi5b3080eed1517214@mail.gmail.com> Well.. Thx for the answers. The only way I had to make it work was to use a time.sleep(10) after the shutil.copyfile(). Since this is a night-run script, I can waste 10 seconds, but it still knocks me out "why" it happens... Cheers! Hugo Ferreira On 30 Jan 2007 18:06:15 +0000 (GMT), Matthew Woodcraft < mattheww at chiark.greenend.org.uk> wrote: > > Hugo Ferreira wrote: > > I have a problem. I'm using calling shutil.copyfile() followed by > > open(). The thing is that most of the times open() is called before > > the actual file is copied. I don't have this problem when doing a > > step-by-step debug, since I give enough time for the OS to copy the > > file, but at run-time, it throws an exception. > > > > Is there anyway to force a sync copy of the file (make python wait for > > the completion)? > > shutil.copyfile() closes both files before it returns, so I suspect > this is an OS-level bug. > > The most likely culprits are buggy network filesystems and buggy > on-access virus scanners. > > -M- > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Wed Jan 17 10:03:59 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 17 Jan 2007 07:03:59 -0800 Subject: Distributed computation of jobs (was: Parallel Python) References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: <1169046239.405261.81740@m58g2000cwm.googlegroups.com> A.T.Hofkamp skrev: > > Let me add a few cents to the discussion with this announcement: [Notes about exec_proxy, batchlib and rthread] I've added entries for these modules, along with py.execnet, to the parallel processing solutions page on the python.org Wiki: http://wiki.python.org/moin/ParallelProcessing Thanks for describing your work to us! Paul From jstroud at mbi.ucla.edu Fri Jan 19 23:48:39 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 19 Jan 2007 20:48:39 -0800 Subject: regexp qns In-Reply-To: <1169268024.164643.71320@l53g2000cwa.googlegroups.com> References: <1169268024.164643.71320@l53g2000cwa.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > hi > suppose i have a string like > > test1?test2t-test3*test4*test5$test6#test7*test8 > > how can i construct the regexp to get test3*test4*test5 and > test7*test8, ie, i want to match * and the words before and after? > thanks > py> import re py> s = 'test1?test2t-test3*test4*test5$test6#test7*test8' py> r = re.compile(r'(test\d(?:\*test\d)+)') py> r.findall(s) ['test3*test4*test5', 'test7*test8'] James From rzantow at gmail.com Sun Jan 7 17:21:27 2007 From: rzantow at gmail.com (rzed) Date: Sun, 07 Jan 2007 17:21:27 -0500 Subject: where is python on linux? References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> <45a157a0$0$289$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote in news:45a157a0$0$289$426a74cc at news.free.fr: > Frank Potter a ?crit : >> I installed fedora core 6 and it has python installed. >> But the question is, where is the executable python file? >> I can't find it so I come here for help. > > man which > > mmmmmmm... sloppy joes .... -- rzed "A sandwich is a sandwich, but a Manwich is a meal." From redawgts at gmail.com Wed Jan 24 20:33:13 2007 From: redawgts at gmail.com (redawgts) Date: 24 Jan 2007 17:33:13 -0800 Subject: Python Windows Editors In-Reply-To: References: Message-ID: <1169688793.302541.243200@s48g2000cws.googlegroups.com> Yes, pywin32 installs PythonWin. On Jan 24, 4:07 pm, "W. Watson" wrote: > W. Watson wrote: > > I downloaded python-2.5.msi and installed it. I believe its editor is > > [corrected]IDLE. I understand there's a Win editor called pythonwin. I believe it's > > in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this > > exe file has just the editor or all of Python. Comments? If not how do I > > get the PythonWin editor by itself? > > > BTW, one of the features I did not like of IDE is the limited file Print > > command. It puts everything in 16pt type, and gives no choice over what > > pages should be printed. Maybe there's an option?I don't see any responses that address regarding > pywin32-210.win32-py2.5.exe, so it looks like I'll have to undbundle it and > see for myself. From gagsl-py at yahoo.com.ar Sat Jan 13 21:26:21 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Jan 2007 23:26:21 -0300 Subject: Boilerplate in rich comparison methods References: <7x8xg71j3t.fsf@ruckus.brouhaha.com> Message-ID: "Steven D'Aprano" escribi? en el mensaje news:pan.2007.01.13.19.09.09.242271 at REMOVE.THIS.cybersource.com.au... > On Fri, 12 Jan 2007 23:28:06 -0800, Paul Rubin wrote: > >> If it's that uniform I think you can just use __cmp__: > > Good point -- I had somehow picked up the mistaken idea that __cmp__ was > depreciated in favour of rich comparisons. If you inherit from a base class that implements rich comparisons, you have to override all those methods, else your __cmp__ won't be called at all. Sometimes it may be enough to implement __cmp__ and make all others call it. -- Gabriel Genellina From nick at craig-wood.com Fri Jan 5 05:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 05 Jan 2007 04:30:04 -0600 Subject: code optimization (calc PI) / New Algorithme for PI References: Message-ID: Michael M. wrote: > Yes, this "gmpy" sounds good for calc things like that. > But not available on my machine. > ImportError: No module named gmpy Sorry, I should have said - you'll need to download that from http://gmpy.sourceforge.net/ > Anyway, thanks for posting. This gmpy module can be very intersting. > But right now, the focus was, if it's possible to translate a strange C > code into Python. And it is. Sure ;-) > > Maybe, someone can also translate a very simple algorithm for calc a > range of PI in Python. (Available Code for C.) > http://crd.lbl.gov/~dhbailey/ Here are some more pi calculation methods. You'll need the FixedPoint class in my last posting, or you cah use gmpy mpf~s also. _1 = FixedPoint(1) # or _1 = gmpy.mpf(1, bits) # or (for testing) _1 = 1.0 _3 = _1 * 3 def arctan(x): """ Calculate arctan(x) arctan(x) = x - x**3/3 + x**5/5 - ... (-1 <= x <= 1) """ total = x power = x divisor = 1 old_delta = None while 1: power *= x power *= x power = -power divisor += 2 old_total = total total += power / divisor delta = abs(total - old_total) if old_delta is not None and delta >= old_delta: break old_delta = delta return total def pi_machin(): return 4*(4*arctan(_1/5) - arctan(_1/239)) def pi_ferguson(): return 4*(3*arctan(_1/4) + arctan(_1/20) + arctan(_1/1985)) def pi_hutton(): return 4*(2*arctan(_1/3) + arctan(_1/7)) def pi_gauss(): return 4*(12*arctan(_1/18) + 8*arctan(_1/57) - 5*arctan(_1/239)) def pi_euler(): return 4*(5*arctan(_1/7) + 2*arctan(_3/79)) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dickinsm at gmail.com Sun Jan 14 18:32:35 2007 From: dickinsm at gmail.com (dickinsm at gmail.com) Date: 14 Jan 2007 15:32:35 -0800 Subject: Conflicting needs for __init__ method Message-ID: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Here's an example of a problem that I've recently come up against for the umpteenth time. It's not difficult to solve, but my previous solutions have never seemed quite right, so I'm writing to ask whether others have encountered this problem, and if so what solutions they've come up with. Suppose you're writing a class "Rational" for rational numbers. The __init__ function of such a class has two quite different roles to play. First, it's supposed to allow users of the class to create Rational instances; in this role, __init__ is quite a complex beast. It needs to allow arguments of various types---a pair of integers, a single integer, another Rational instance, and perhaps floats, Decimal instances, and suitably formatted strings. It has to validate the input and/or make sure that suitable exceptions are raised on invalid input. And when initializing from a pair of integers---a numerator and denominator---it makes sense to normalize: divide both the numerator and denominator by their greatest common divisor and make sure that the denominator is positive. But __init__ also plays another role: it's going to be used by the other Rational arithmetic methods, like __add__ and __mul__, to return new Rational instances. For this use, there's essentially no need for any of the above complications: it's easy and natural to arrange that the input to __init__ is always a valid, normalized pair of integers. (You could include the normalization in __init__, but that's wasteful when gcd computations are relatively expensive and some operations, like negation or raising to a positive integer power, aren't going to require it.) So for this use __init__ can be as simple as: def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator So the question is: (how) do people reconcile these two quite different needs in one function? I have two possible solutions, but neither seems particularly satisfactory, and I wonder whether I'm missing an obvious third way. The first solution is to add an optional keyword argument "internal = False" to the __init__ routine, and have all internal uses specify "internal = True"; then the __init__ function can do the all the complicated stuff when internal is False, and just the quick initialization otherwise. But this seems rather messy. The other solution is to ask the users of the class not to use Rational() to instantiate, but to use some other function (createRational(), say) instead. Then __init__ is just the simple method above, and createRational does all the complicated stuff to figure out what the numerator and denominator should be and eventually calls Rational(numerator, denomiator) to create the instance. But asking users not to call Rational() seems unnatural. Perhaps with some metaclass magic one can ensure that "external" calls to Rational() actually go through createRational() instead? Of course, none of this really has anything to do with rational numbers. There must be many examples of classes for which internal calls to __init__, from other methods of the same class, require minimal argument processing, while external calls require heavier and possibly computationally expensive processing. What's the usual way to solve this sort of problem? Mark From sndive at gmail.com Fri Jan 26 15:50:47 2007 From: sndive at gmail.com (sndive at gmail.com) Date: 26 Jan 2007 12:50:47 -0800 Subject: Calling python function from C and import questions Message-ID: <1169844647.673719.25810@j27g2000cwj.googlegroups.com> Is there a better way to make a call from C than PyRun_SimpleString("import foo_in_python\nfoo_in_python.bar(whatever)\n"); ? I already imported the foo_in_python using PyImport_ImportModule and wonder why do I need to keep importing it every time I'm calling a python function in that module. I stepped thru PyImport_ImportModule and it seems rather expensive. I assume the module will end up in cache after PyImport_ImportModule so that subsequent PyRun_SimpleString("import foo_in_python\n... is cheaper but I still have to wonder if I what I'm doing is the right thing or there is a much simpler way of doing this. Does anyone know why does the import tries to load .py files before .pyc? Thank you. From stefan.behnel-n05pAM at web.de Mon Jan 8 10:15:00 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 08 Jan 2007 16:15:00 +0100 Subject: lxml namespaces problem In-Reply-To: <1168212638.493983.202560@11g2000cwr.googlegroups.com> References: <1168212638.493983.202560@11g2000cwr.googlegroups.com> Message-ID: <45a25ff6$0$30319$9b4e6d93@newsspool1.arcor-online.net> Maxim Sloyko wrote: > I have a little problem with XML namespaces. > In my application I have two XML processors, that process the same > document, one after the other. The first one looks for nodes in 'ns1' > namespace, and substitutes them, according to some algorithm. After > this processor is finished, it is guaranteed that there are no more > 'ns1' nodes left in the tree. however 'ns1' namespace dclaration is > still > there, in the root node (well, I put it there manually). Now, when > this namespace is no longer needed, I want to get rid of it, because > it confuses some other processors (namely, my browser) > > So, the question is, how do I do that? > del tree.getroot().nsmap['ns1'] > does not seem to do the trick :( Please ask this kind of questions on the lxml mailing list. You might also want to consider searching the mail archive first. First of all, lxml produces perfectly well-formed XML here. There is no reason a document should not contain any unused namespace declarations. It's the browser that's broken if it handles the namespace incorrectly. Then: the thing is that lxml can't know that you removed all occurrences of the respective namespace, so it can't just remove the declaration by itself. lxml 1.2 will likely be able to handle these things a little (!) more beautifully, but it's not there yet. One way to get around this might be to reimplement the namespace replacement in XSLT. You might also want to try to copy the elements to a newly created document that does not have the original namespace declaration. Note, however, that this is not guaranteed to work and might break depending on the lxml version. Stefan From howard at eegsoftware.com Mon Jan 22 16:19:21 2007 From: howard at eegsoftware.com (Howard Lightstone) Date: Mon, 22 Jan 2007 21:19:21 GMT Subject: Building extensions with vc8 Message-ID: Has there been any progress on being able to build extensions with MSVC8 (aka Visual Studio 2005)? Since the "free" compiler from Microsoft is now VC8, I *assume* this will be the new method..... 2.5 itself rebuilds using PCbuild8, as do tkinter (but using Tcl 8.4.14 and Tk 8.4.14) however none of the distutils-generated extensions will build. From wangshuhao at sina.com Wed Jan 24 03:14:48 2007 From: wangshuhao at sina.com (Wang Shuhao) Date: Wed, 24 Jan 2007 16:14:48 +0800 Subject: sys.path issue in cygwin Message-ID: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> I successfully built and installed Python 2.2.3 in cygwin. But there is something wrong in the sys.path. I use following statments for a test. >>> import sys >>> print sys.path ['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', 'C/lib/python2.2/lib-tk' , '\\Python24/lib/python2.2/lib-dynload'] >>> To keep the question simple, I've set PATH= in cygwin.bat to avoid python initialze sys.path from Windows' PATH environment. Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is installed in /usr/local/lib/python2.2.3. The result of the issue is that when you run a program python can't find the module. So what I really want to know is where these path came from and how to fix it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grahn+nntp at snipabacken.dyndns.org Mon Jan 22 09:55:29 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 22 Jan 2007 14:55:29 GMT Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> <45af8f52$0$339$e4fe514c@news.xs4all.nl> Message-ID: On Thu, 18 Jan 2007 14:15:44 -0300, Gabriel Genellina wrote: ... > I'll try to explain better: the cgi *protocol* (I'm not talking about the > cgi *module*) requires a *new* python process to be created on *each* > request. Try to measure the time it takes to launch Python, that is, the > time from when you type `python ENTER` on your shell and the interpreter > prompt appears. On my Mac Mini with all of Python on local disk: tuva:~> time python time python < /dev/null 0.028u 0.004s 0:00.02 100.0% 0+0k 0+0io 0pf+0w tuva:~> I.e. about 200--300ms. I assume startup time >> shutdown time. If Python was at the other end of a NFS file system, much worse figures. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From paul.sijben at xs4all.nl Wed Jan 10 09:43:23 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 15:43:23 +0100 Subject: maximum number of threads In-Reply-To: References: Message-ID: <45A4FB8B.60508@xs4all.nl> All thanks for all the input! This was very informative. Looks like I indeed need stackless as my code benefits from being concurrently designed. Paul Jean-Paul Calderone wrote: > On Wed, 10 Jan 2007 12:11:59 -0200, Felipe Almeida Lessa > wrote: >> On 1/10/07, Laurent Pointal wrote: >>> This is a system configurable limit (up to a maximum). >>> >>> See ulimit man pages. >>> >>> test >>> >>> ulimit -a >>> >>> to see what are the current limits, and try with >>> >>> ulimit -u 2000 >>> >>> to modify the maximum number of user process (AFAIK each thread use a >>> process entry on Linux) >> >> I don't think it's only this. > > Indeed you are correct. The actual limit you are hitting is the size > of your address space. Each thread is allocated 8MB of stack. 382 > threads consumes about 3GB of address space. Even though most of this > memory isn't actually allocated, the address space is still used up. So, > when you try to create the 383rd thread, the kernel can't find anyplace > to put its stack. So you can't create it. > > Try reducing your stack size or reducing the number of threads you create. > There's really actually almost no good reason to have this many threads, > even though it's possible. > > exarkun at charm:~$ python Desktop/test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > Exception raised: can't start new thread > Biggest number of threads: 382 > exarkun at charm:~$ ulimit -Ss 4096 > exarkun at charm:~$ python Desktop/test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > 400 > 450 > 500 > 550 > 600 > 650 > 700 > 750 > Exception raised: can't start new thread > Biggest number of threads: 764 > exarkun at charm:~$ > Jean-Paul From deets at nospam.web.de Tue Jan 30 03:10:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 Jan 2007 09:10:57 +0100 Subject: Python 2.5 Tkinter not configured In-Reply-To: References: Message-ID: <528ctaF1nig7eU1@mid.uni-berlin.de> Jim schrieb: > I compiled Python 2.5 from python.org and I get an error message when I try > to import the Tkinter module. Python reports that there is no such module. > It says my Python isn't configured for Tkinter. How do I configure it? I'm > using GCC 4.1.1 to compile the tarball. Thanks for any help with this. You need to have tcl/tk together with it's development-headers installed. Python _should_ figure out where things are, and then be configured to include tkinter. Diez From duncan.booth at invalid.invalid Fri Jan 12 10:13:54 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jan 2007 15:13:54 GMT Subject: Command line arguments on Vista References: <1168613362.406648.304720@11g2000cwr.googlegroups.com> Message-ID: jmike at alum.mit.edu wrote: > But on Windows Vista, when I run that command, I get > > there are 1 args > arg: printargs.py > > What's up with that? It sounds like the registry entry for running Python files is messed up. Can you go to a command line and see what the command 'ftype Python.File' displays? (Assuming that command lines and ftype still work on Vista) The output should be: Python.File="C:\Python25\python.exe" "%1" %* but if it only says: Python.File="C:\Python25\python.exe" "%1" then you would get the behaviour you observed (on any version of Windows, not just Vista). From agriff at tin.it Sun Jan 7 14:40:57 2007 From: agriff at tin.it (Andrea Griffini) Date: Sun, 07 Jan 2007 20:40:57 +0100 Subject: Why less emphasis on private data? In-Reply-To: <45a12cb0$0$300$426a74cc@news.free.fr> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <45a0b4e3$0$19089$4fafbaef@reader4.news.tin.it> <45a12cb0$0$300$426a74cc@news.free.fr> Message-ID: <45a14b57$0$4248$4fafbaef@reader1.news.tin.it> Bruno Desthuilliers wrote: >> ... and on >> the opposite I didn't expect that fighting with object >> leaking in complex python applications was that difficult >> (I've heard of zope applications that just gave up and >> resorted to the "reboot every now and then" solution). >> > Zope is a special case here, since it relies on an object database... Just to clarify my post... I found by being punched myself in the nose what does it mean to have a complex python application that suffers from object leaking; it's not something I only read about zope programs. But why zope applications would be a special case ? Andrea From bthom at cs.hmc.edu Tue Jan 9 02:38:44 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Mon, 08 Jan 2007 23:38:44 -0800 Subject: private variables In-Reply-To: <45A331FE.90509@gmx.net> References: <74E534EE-D260-409D-8E91-0182BB897B94@cs.hmc.edu> <45A331FE.90509@gmx.net> Message-ID: I knew it was a beehive, but I had hoped someone would know which version they were released, so I can put the proper statement into my tutorial (e.g. In version , Python provided some support for private variables...). I've been avoiding getting stung b/c I see both sides and have no preference for one vs. the other. --b On Jan 8, 2007, at 10:11 PM, Thomas Ploch wrote: > belinda thom schrieb: >> Hello, >> >> In what version of python were private variables added? >> >> Thanks, >> >> --b >> > > With this question you stepped into a bee hive. :-) > > Read the 'Why less emphasis on private data?' thread. > > But I can't tell you, when this so called 'private variables' were > added. > > Thomas > -- > http://mail.python.org/mailman/listinfo/python-list From mail at microcorp.co.za Wed Jan 10 05:14:08 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 10 Jan 2007 12:14:08 +0200 Subject: Is there a way to protect a piece of critical code? Message-ID: <000b01c734a0$2f635840$03000080@hendrik> Hi, I would like to do the following as one atomic operation: 1) Append an item to a list 2) Set a Boolean indicator It would be almost like getting and holding the GIL, to prevent a thread swap out between the two operations. - sort of the inverted function than for which the GIL seems to be used, which looks like "let go", get control back via return from blocking I/O, and then "re - acquire" Is this "reversed" usage possible? Is there some way to prevent thread swapping? The question arises in the context of a multi threaded environment where the list is used as a single producer, single consumer queue - I can solve my problem in various ways, of which this is one, and I am curious as to if it is possible to prevent a thread swap from inside the thread. - Hendrik From bdesth.quelquechose at free.quelquepart.fr Thu Jan 4 05:57:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Jan 2007 11:57:48 +0100 Subject: static object In-Reply-To: References: <459c306c$0$314$426a74cc@news.free.fr> Message-ID: <459cd784$0$284$426a34cc@news.free.fr> Ben Finney a ?crit : (snip) > The "Singleton" pattern does what you say here. Implementing a proper > Singleton in Python is complicated and hard to understand. Really ? Using __new__ and a class attribute, it doesn't seem so complicated - nor difficult to understand... From s99999999s2003 at yahoo.com Mon Jan 22 22:03:01 2007 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 22 Jan 2007 19:03:01 -0800 Subject: match nested parenthesis Message-ID: <1169521381.814119.27020@11g2000cwr.googlegroups.com> hi i wish to find an reg exp for matching nested parenthesis of varying level like string = "somewords1(words(somewords2)-(some(some)words3)somestuff)somestuff" and be able to evaluate the pair starting from the inner most(the deepest level) , ie (some) up till the outer most. What is a good reg exp to do this? or is simple string manipulations enough? thanks From bearophileHUGS at lycos.com Thu Jan 11 07:38:49 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Jan 2007 04:38:49 -0800 Subject: Type casting a base class to a derived one? In-Reply-To: References: Message-ID: <1168519129.413970.80840@p59g2000hsd.googlegroups.com> Frederic Rentsch: > If I derive a class from another one because I need a few extra > features, is there a way to promote the base class to the derived one > without having to make copies of all attributes? > > class Derived (Base): > def __init__ (self, base_object): > # ( copy all attributes ) > ... > > This looks expensive. No need to copy attributes: class Base(object): def __init__ (self, x): self.x = x class Derived(Base): def __init__ (self, x, y): Base.__init__(self, x) self.y = y d = Derived(1, 2) print d.x, d.y Bye, bearophile From rdiaz02 at gmail.com Sat Jan 20 10:59:45 2007 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Sat, 20 Jan 2007 16:59:45 +0100 Subject: Py 2.5 on Language Shootout In-Reply-To: <45B23400.2010906@gmx.de> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> <45B23400.2010906@gmx.de> Message-ID: <624934630701200759k4f4aa6fr803595fa4ada28d3@mail.gmail.com> On 1/20/07, Carl Friedrich Bolz wrote: > pgarrone at acay.com.au wrote: > >>> Looking over the benchmarks, one gains the impression that Python is a > >>> slow language. > >> What does that even mean - a slow language? > >> > > > > The alioth benchmarks provide a set of numbers by which > > languages may be compared. > > Wrong. The benchmarks provide a set of numbers by which > _implementations_ of languages can be compared. After all, it is > possible that someone implements a magic-pixie-dust-interpreter that > executes Python programs several orders of magnitude fastes than > CPython. Or you could say that C is slow because if you use CINT, a C > interpreter ( http://root.cern.ch/root/Cint.html ) to execute it, it is > slow. Yeah, but this is hair-splitting. Except for Jython, IronPython, and Stackless, I think when we say "Python is slow/fast" we think CPython (otherwise, we qualify the implementation). For that matter it is often said "the GIL ..."; oh, but wait, Stackless ... With other languages (e.g., Common Lisp) the separation between the language and the implementation is key because, to begin with, there is something external from, and independent of, any particular implementation. That is not the case with Python. And the example of CINT is hair-splitting to the nth power.To begin with, I do not think CINT implements the full standard C. But even if it were, when people think of C they rarely think of CINT. I think readers understood the previous poster. Best, R. > > Cheers, > > Carl Friedrich Bolz > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From removethis.kartic.krishnamurthy at gmail.com Mon Jan 29 13:58:09 2007 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 29 Jan 2007 18:58:09 GMT Subject: Sourcing Python Developers In-Reply-To: <45BE4348.9020500@gmail.com> References: <45BE4348.9020500@gmail.com> Message-ID: <45BE43C1.1000805@gmail.com> Current requirements in US only. Kartic sayeth, on 01/29/2007 01:56 PM: > Hello, > > My company has quite a few opening involving python expertise. We are > always looking for python resources (and find it difficult filling these > positions, might I add). Is there any place to find developers' resumes > (like finding jobs from http://python.org/community/jobs/)? If any one > knows of a resume repository (other than Monster, Dice, > Costs-an-arm-and-leg job site) please share. > > In any case, we have immediate requirements for a Pythonista with C++, > MySQL, XML, Debian expertise. Please email resume to: > python-resumes(at)temporaryforwarding.com > > Thank you, > --Kartic From dudds at netspace.net.au Tue Jan 23 08:01:24 2007 From: dudds at netspace.net.au (dudds) Date: 23 Jan 2007 05:01:24 -0800 Subject: PythonCard installation Message-ID: <1169557284.833325.305590@k78g2000cwa.googlegroups.com> Anyone had any joy with this using FC6?? When I try to run code editor I get the error "Traceback (most recent call last): File "/usr/lib/python2.4/PythonCard-0.8.2/tools/codeEditor/codeEditor.py", line 13, in ? from PythonCard import about, configuration, dialog, log, menu, model, resource, util ImportError: No module named PythonCard" From theller at ctypes.org Fri Jan 26 09:10:05 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 26 Jan 2007 15:10:05 +0100 Subject: how to unistall a Python package? In-Reply-To: References: <000601c74094$4d514e20$1400a8c0@mytomato> Message-ID: <45BA0BBD.1030105@ctypes.org> Colin J. Williams schrieb: > With Windows, a few packages, eg. PythonWin, also modify the registry. > numpy, the elaboration of numarray/numeric, and PythonWin have > RemoveXXX.exe in C:\Python25. > > I don't know whether this is the standard approach. There doesn't seem > to be a reference to Removal in the distutils document. Packages that are create with distutils bdist_wininst command can be removed using the control panel->add/Software/ Add Remove programs. This calls RemoveXXX.exe (which is undocumented on purpose). Thomas From rocky at panix.com Thu Jan 25 19:09:35 2007 From: rocky at panix.com (R. Bernstein) Date: 25 Jan 2007 19:09:35 -0500 Subject: Possible bug in Python 2.5? (Was Re: pdb in python2.5) References: <1169717486.230356.79730@l53g2000cwa.googlegroups.com> <1169760673.197226.206540@a75g2000cwd.googlegroups.com> Message-ID: "Rotem" writes: > Hi, > > I noticed that pydb.pm() also fails in python2.5 when invoked on that > same example (seems like also trying to access a nonexistent > attribute/variable). > > Is this known to you as well/was it fixed? Doesn't do that for me for Python 2.5 on both pydb 1.20 (last released version) and the current CVS. See below. If you think the problem is not on your end and want to file a bug report, please do. But note * comp.lang.python is not the place to file bug reports * more detail is needed that what's been given so far $ cat /tmp/t1.py from __future__ import with_statement import threading def f(): l = threading.Lock() with l: print "hello" raise Exception("error") print "world" try: f() except: import pydb pydb.pm() $ python /tmp/t1.py hello (/tmp/t1.py:9): f (Pydb) where -> 0 f() called from file '/tmp/t1.py' at line 9 ## 1 () called from file '/tmp/t1.py' at line 15 (Pydb) show version pydb version 1.20. (Pydb) quit $ python /tmp/t1.py hello (/tmp/t1.py:15): (Pydb) where ## 0 f() called from file '/tmp/t1.py' at line 8 -> 1 () called from file '/tmp/t1.py' at line 15 (Pydb) show version pydb version 1.21cvs. (Pydb) quit $ From cliff at develix.com Wed Jan 24 14:49:20 2007 From: cliff at develix.com (Cliff Wells) Date: Wed, 24 Jan 2007 11:49:20 -0800 Subject: Type casting a base class to a derived one? In-Reply-To: <1169667478.4910.52.camel@portable-evil> References: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> <1169664145.4910.22.camel@portable-evil> <4866bea60701241057t13776d34ya516c2c24e7119bb@mail.gmail.com> <1169667478.4910.52.camel@portable-evil> Message-ID: <1169668160.4910.57.camel@portable-evil> On Wed, 2007-01-24 at 11:37 -0800, Cliff Wells wrote: > > class Person: # assume this is something from the ORM > name = "Kenny" > > class PersonRow ( Person ): > pass > > def flatten_person ( p ): > return "omg, you've killed %p" % p.name > > def flatten_personrow ( p ): > return "%s" % p.name > > register_flattener ( PersonRow, flatten_personrow ) > register_flattener ( Person, flatten_person ) > > > Now, assuming a list of Person records were passed in as 'persons', then > in the template the template author could simply use: > > div [ > # show the first person > persons [ 0 ], > > # show a table of all persons > table [ > [ PersonRow ( p ) for p in persons ] > ] > ] > I should add that the reason I don't want to just say, call flatten_personrecord() directly from the template (which would be a reasonable solution in this example) is because I have a longer-term goal that would require an object at that point. What I expect I'll end up doing is using a factory function that returns the desired object at that point, but it will require a bit more explanation at the template level than I'd like: table [ [ render_as ( PersonRow, p ) for p in persons ] ] or something similar. Regards, Cliff From tpawley at gmail.com Mon Jan 15 03:52:33 2007 From: tpawley at gmail.com (Torabisu) Date: 15 Jan 2007 00:52:33 -0800 Subject: Python web app. (advice sought) In-Reply-To: <45aae51b.0@entanet> References: <45aae51b.0@entanet> Message-ID: <1168851153.618515.261800@a75g2000cwd.googlegroups.com> Duncan Smith wrote: > Hello, > I find myself in the, for me, unusual (and at the moment unique) > position of having to write a web application. I have quite a lot of > existing Python code that will form part of the business logic. This > relies on 3rd party libraries (such as numpy) which would make porting > to e.g. IronPython difficult (I would imagine). I was thinking LAMP > (the P standing for Python, of course), particularly as I was originally > encouraged to go for open source solutions. > > The application will provide some basic statistical analyses of data > contained in database tables and associated plots (R / matplotlib / > graphviz). There will also be some heavier duty Monte Carlo simulation > and graphical modelling / MCMC. The user(s) will need to be able to set > model parameters; maybe even tinker with model structure, so it will be > very interactive (AJAX?). > > I've had a look at Django, Turbogears and Plone, and at the moment I am > torn between Turbogears and Plone. I get the impression that Turbogears > will require me to write more non-Python code, but maybe Plone is more > than I need (steeper learning curve?). Maybe Turbogears will lead to a > more loosely coupled app. than Plone? > > The disconcerting thing is that others on the project (who won't be > developing) have started to talk about a LAMP back end with an IIS front > end, .NET, and the benefits of sharepoint. The emphasis is supposed to > be on rapid development, and these technologies are supposed to help. > But I have no real familiarity with them at all; just Python, C and SQL > to any realistic level of competence. > > Any advice would be greatly appreciated. I have to do much of the > statistical work too, so I need to make good choices (and hopefully be > able to justify them so nobody else on the project makes inappropriate > choices for me). e.g. I don't mind learning Javascript if it doesn't > take too long. The physical server will initially be a multiprocessor > machine with several GB of RAM. But we also have a cluster (I have no > details, I only started the project a week ago). So any advice > regarding parallelisation would also be appreciated (or, in fact, any > useful advice / pointers at all). Thanks. > > Duncan I was in a similar boat a while back, needing to make a decision on what to use for our web development. I had worked with Plone previously and found that for our needs it wasn't going to work. Our web development was quite specific and didn't fit ideally into the standard content management realm. I also looked at Django and TurboGears, installing and working with each. I eventually went with Django, and I've really enjoyed working with it. Was a personal choice and I'm sure our development would have been as successful if I'd chosen TurboGears. If you want the strength of persistent layers, MVC, templating etc etc but want to stay away from the heavier frameworks, another possibility is http://webpy.org/. Very simple to implement, lightweight yet still fairly full of features. From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 16:42:11 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 22:42:11 +0100 Subject: Why less emphasis on private data? In-Reply-To: <9dboh.11767$ZT3.426@newssvr19.news.prodigy.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <9dboh.11767$ZT3.426@newssvr19.news.prodigy.com> Message-ID: <45a162f3$0$3501$426a74cc@news.free.fr> John Nagle a ?crit : > sturlamolden wrote: > >> time.swift at gmail.com wrote: >> >>> Coming from a C++ / C# background, the lack of emphasis on private data >>> seems weird to me. I've often found wrapping private data useful to >>> prevent bugs and enforce error checking.. >>> >>> It appears to me (perhaps wrongly) that Python prefers to leave class >>> data public. What is the logic behind that choice? >> >> >> >> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that >> if an object's 'internal' variables or states cannot be kept private, >> programmers get an irresistible temptation to mess with them in >> malicious ways. > > > If you're not clear on encapsulation issues, encapsulation != data hiding > you probably haven't > done extensive maintenance programming on code written by others. I did. > Finding out who can mess with a variable when debugging the code of > others is not fun. # before class Toto(object): def __init__(self, x): self._x = x # after class Toto(object): def __init__(self, x): self._x = x @apply def _x(): def fget(self): return self._real_x def fset(self, value): import pdb; pdb.set_trace() self._real_x = value return property(**locals) This is of course a braindead implementation - a better one would use either the inspect module of the sys._getframe() hack to retrieve useful debug infos (left as an excercice to the reader...) > Because Python doesn't have explicit declarations, scope of > variables is > a touchy issue. ??? > If you write "x = 1" within a function, that will > create a local "x" if "x" doesn't exist, or alter a global "x" if "x" was > previously created in the global context. Err... May I suggest you to read these two pages: http://docs.python.org/ref/assignment.html http://docs.python.org/ref/global.html#l2h-563 > But at least global variables > are local to the namespace; we don't have clashes across files. So > it's not too bad. JavaScript has the convention that newly created > variables are global by default. Unless preceded by the 'var' keyword... > Big mistake. Mmm... which one ? > The underscore thing makes sense. Single underscore > variables are "protected" in the C++ sense, and double underscore > variables are "private", not visible from inherited classes. > It's hard to misuse such variables by accident. I'd be tempted > to prohibit access to underscore variables other than via "self._x" > forms, so they'd be inaccessable outside the object. # foo.py class Foo(object): def __init__(self, x): self._x = x def __repr__(self): return "" % self._x # bar.py def bar(self): self.y = self._x # baaz.py from foo import Foo from bar import bar Foo.bar = bar f = Foo([42]) f.bar() f.y.append('gotcha') print f > It's undesirable > from a maintenance standpoint to have an unenforced convention If it's a convention, it doesn't have to be inforced. If it's inforced, it's not a convention anymore. While we're at it, I've found it very valuable to be able to mess with implementation when doing maintenance on somewhat large (and somewhat messy) Python systems... > like > a lead underscore. The maintenance programmer can't trust its meaning. > > As Python grows up, and larger systems are written in it, these > issues become more important. If you go that way, then you'll also want to introduce declarative static typing and remove all possibility to dynamically modify classes or add/replace attributes and/or methods on a per-instance basis. If you want Java, you know where to find it. From garyjefferson123 at yahoo.com Thu Jan 25 16:28:07 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 25 Jan 2007 13:28:07 -0800 Subject: selective logger disable/enable In-Reply-To: <1169708086.661248.142390@j27g2000cwj.googlegroups.com> References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> <1169349399.938121.238430@38g2000cwa.googlegroups.com> <1169395276.181654.160810@a75g2000cwd.googlegroups.com> <1169437763.213781.163660@38g2000cwa.googlegroups.com> <1169442596.209314.162410@s34g2000cwa.googlegroups.com> <1169531341.221067.205500@11g2000cwr.googlegroups.com> <1169546484.370874.253890@a75g2000cwd.googlegroups.com> <1169708086.661248.142390@j27g2000cwj.googlegroups.com> Message-ID: <1169760487.039284.193410@a75g2000cwd.googlegroups.com> Gary Jefferson wrote: > So maybe I don't have all this figured out quite as well as I thought. > What I really want to do is set an environment variable, MYDEBUG, which > contains a list of wildcarded logger names, such as "a.*.c a.d" (which > becomes ['a.*.c', 'a.d'], and then selectively crank the loglevel up to > DEBUG for those that match. > > In order to do that, I think I need something kind of like filters, but > for logger name... I'm not seeing how to do this, even after playing > with variations of test15, 18, and 21. > > What I do have working at the moment is passing a list of non-wildcard > logger names, i.e., doing the wildcard expansion manually such as > "['a.b.c', 'a.c.c', 'a.f.c', 'a.d']. Is there anyway to automate this > dynamically? > > BTW, I do understand that 'a.d' is essentially equivalent to 'a.d.*', > but I'm dealing with a hierarchy that doesn't always tidy up like that. > For example, I have top.network.server.http, top.network.server.smtp, > top.network.client.http, and top.network.client.smtp. Obviously, if I > only want server or client DEBUG msgs, this is easy. And sometimes > that's exactly what I want. Other times, I want only smtp DEBUG msgs, > and the hierarchy won't help me get that (unless I break it for just > getting client or server msgs), etc. So I would really like to figure > out how to do 'a.*.c'. > > Any ideas? > > Thanks again, > Gary Okay, I think I'm back on track again: I can do regex comparisons against the name field of the LogRecord instance handed to me by filter(). Gary From antonyliu2002 at yahoo.com Fri Jan 5 11:27:32 2007 From: antonyliu2002 at yahoo.com (antonyliu2002 at yahoo.com) Date: 5 Jan 2007 08:27:32 -0800 Subject: Undefined symbol __pure_virtual when importing MySQLdb References: <1167977378.425615.220350@51g2000cwl.googlegroups.com> <1167980159.711978.309970@i15g2000cwa.googlegroups.com> Message-ID: <1168014452.463696.102340@51g2000cwl.googlegroups.com> antonyliu2002 at yahoo.com wrote: > Fredrik Lundh wrote: > > antonyliu2002 at yahoo.com wrote: > > > > > I have googled hard, and did see someone asking the same question, but > > > haven't found a good solution to this problem. Could anyone give me a > > > hint? Thanks a lot! > > > > googling for "undefined symbol: __pure_virtual" brings up hundreds of > > posts on this topic, and the answer is *always* to make sure that you're > > linking with a version of the C++ libraries that matches your compiler. > > > > > > Hi, thanks. I followed the strategy provided at the following url > > http://www.mail-archive.com/dbi-users at perl.org/msg27851.html > > by adding "-lmygcc" to the end of the librarys to link. I added it to > the end of this line in the mysql_config script like so: > > libs=" $ldflags -L$pkglibdir -lmysqlclient -lz -lcrypt -lnsl -lm > -lmygcc " > > And then I recompiled the MySQL-python-1.2.1 package, but the same > problem remains. I tried using -lgcc as some people suggested in some forum, but it does not resolve the problem. It looks like many people are having this problem, but no solution has been offered so far. Anybody has a clue? Thanks. From S.Mientki-nospam at mailbox.kun.nl Thu Jan 11 13:42:53 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 11 Jan 2007 19:42:53 +0100 Subject: globals accros modules In-Reply-To: <45a66cea$0$289$426a34cc@news.free.fr> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> <45a66cea$0$289$426a34cc@news.free.fr> Message-ID: <3137a$45a6851a$d443bb3a$24085@news.speedlinq.nl> Bruno Desthuilliers wrote: > stef a ?crit : >> >>> >>> Change a=1 to amodule.a=1 >>> If you find yourself doing tricks with the module globals, think >>> about redesigning your application. >>> >> Of course I completely agree with you. >> >> But ... >> if you're moving from MatLab to Python, >> and want to show your collegaes, >> with how little effort they can reuse all their existing MatLab >> routines in Python, >> then the global issue is a real pain !! >> >> You can explain your collegaes, that >> - the startindex of arrays changes from 1 to 0 >> - slices are upto, instead of including the final border >> - indention is th? key >> And tell them about all beautiful things in Python, >> but tell them that they are going to loose all their globals ??? > > It's a feature. Globals are definitively a BadThing(tm). yes, I know, but my audience will accept that only in the long term. But maybe this idea works: global var1 global var2 import Ugly_MatLab_Globals def some_function(): import Ugly_MatLab_Globals (btw who owns the BadThing tm ;-) cheers, Stef Mientki From ramashish.lists at gmail.com Sun Jan 21 15:49:17 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 21 Jan 2007 12:49:17 -0800 Subject: Accessing class variables in staticmethods. Message-ID: <1169412557.737589.105120@a75g2000cwd.googlegroups.com> Hi, I want to access a static variable in a staticmethod. The variable can be redefined by derived classes and that should be reflected in base's staticmethod. Consider this trivial example- class Base: staticvar = 'Base' @staticmethod def printname(): # this doesn't work # print staticvar # this does work but derived classes wouldn't behave as I want print Base.staticvar class Derived(Base): staticvar = 'Derived' Base.printname() # should print 'Base' Derived.printname() # should print 'Derived' Any idea on how to go about this? Also from a staticmethod how can I find out other attributes of the class (not objects)? Do static methods get some classinfo via some implicit argument(s)? Thanks in advance, Ram From dotancohen at gmail.com Tue Jan 2 09:05:34 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 2 Jan 2007 16:05:34 +0200 Subject: Unsubscribing from the list Message-ID: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> I need to unsubscribe from this list. I've mailed users-unsubscribe at python.org but that did not unsubscribe me. I've also gone to the list homepage and entered my user information, but that just sent me a message that someone had tried to resubscribe this username. What must one do to unsubscribe from python-list? Thanks. Dotan Cohen http://what-is-what.com/what_is/internet.html http://lyricslist.com/lyrics/artist_albums/356/moore_mandy.php From hg at nospam.org Tue Jan 16 14:07:58 2007 From: hg at nospam.org (hg) Date: Tue, 16 Jan 2007 20:07:58 +0100 Subject: Queue and signals References: Message-ID: <_xfrh.57411$kn7.45469@newsfe23.lga> skip at pobox.com wrote: > > >> Is it legal to use Queue.put in a signal handle and Queue.get in > >> the main process (no thread) > > hg> PS: and if not is there a way to share data between a "main" and > its hg> signal in a safe way (write in signal and read in main) > > The Queue module was designed to work in multithreaded contexts. I doubt > it > will work as expected in a nonthreaded application. Given that your > application isn't multithreaded I suspect you can just modify an object > that > both your signal handler and the rest of the application reference. In > particular, there's no reason your signal handler can't be a method of an > instance: > > import signal > import time > > class MyClass: > def __init__(self): > self.alarm_rang = False > signal.signal(signal.SIGALRM, self.ring_alarm) > signal.alarm(2) > > def ring_alarm(self, sig, frame): > self.alarm_rang = True > > obj = MyClass() > print obj.alarm_rang > time.sleep(4.0) > print obj.alarm_rang > > Skip Hi, Well, so far it seems to work ... The signal handler gets "called" by another application which in turn will stuff info in my sys.stdin, I need then to "raw_input" the info and put it in some type of data structure in a safe way so my main loop can then reader/pop it. ref: (ps: I'm trying to setup a Python high level interface for my kids to learn the language / be interested) http://realtimebattle.sourceforge.net/ Regards, hg From Garrick.Peterson at zootweb.com Mon Jan 29 11:22:36 2007 From: Garrick.Peterson at zootweb.com (Garrick.Peterson at zootweb.com) Date: Mon, 29 Jan 2007 09:22:36 -0700 Subject: stop script w/o exiting interpreter In-Reply-To: Message-ID: > I want, and the script will stop executing at that line and will > return to the interactive interpreter, as I wish. May I recommend wrapping your main program in a function definition? Such as: main(): # Bulk of your code (use a macro to indent it faster) if __name__ == "__main__": main() Then you should be able to throw in a "return" at any point and get a clean break, without affecting the flow of your program. This should make it easier to debug as well, offering a clean entry point from the python interactive session, and letting you return a specific value you wish to check. Garrick M. Peterson Quality Assurance Analyst Zoot Enterprises, Inc. garrick.peterson at NO.zootweb.com Copyright ? 2007 Zoot Enterprises, Inc. and its affiliates. All rights reserved. This email, including any attachments, is confidential and may not be redistributed without permission. If you are not an intended recipient, you have received this message in error; please notify us immediately by replying to this message and deleting it from your computer. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sschwarzer at sschwarzer.net Wed Jan 3 14:02:35 2007 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 03 Jan 2007 20:02:35 +0100 Subject: code optimization (calc PI) In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> Message-ID: <459BFDCB.4000503@sschwarzer.net> On 2007-01-03 16:50, mm wrote: > More general, maybe there is a speed optimazation docu out there. At least Alex Martellis "Python in a Nutshell" has a section on optimization. I presented this at the last EuroPython conference: http://sschwarzer.com/download/optimization_europython2006.pdf Stefan -- Dr.-Ing. Stefan Schwarzer SSchwarzer.com - Softwareentwicklung f?r Technik und Wissenschaft http://sschwarzer.com From bg_ie at yahoo.com Fri Jan 19 12:34:59 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 19 Jan 2007 09:34:59 -0800 Subject: Why do I have to call del explicitly for com objects? In-Reply-To: References: <1169210578.544593.310100@v45g2000cwv.googlegroups.com> Message-ID: <1169228099.386082.129590@38g2000cwa.googlegroups.com> Gabriel Genellina skrev: > escribi? en el mensaje > news:1169210578.544593.310100 at v45g2000cwv.googlegroups.com... > > > I'm creating objects in my python script belonging to a COM object > > which I dispatch using win32com.client.DispatchEx. Hence, dllhost.dll > > is the concerned process. The problem is that the objects destructor > > within the com object is not called if the object lives past a certain > > number of seconds. For example, this function will not call the > > destructor concerned with obj unless the sleep is commented out. > > > > def fnction: > > obj = comobj.createACertainObject() > > obj.doStuff() > > sleep(10) > > obj.doMoreStuff() > > #del obj > > I don't understand the case. > del does not invoke a destructor, just decrements the object's reference > count. When the rc reaches zero, the object is a candidate for GC. That is, > "some time in the future", the GC would destroy it (unless it's part of a > circular reference chain...) > So, *inside* your function, there is a reference held by the local variable > obj. It is decremented automatically when you exit the function (and obj > gets out of scope) or if you explicitely use del. > You can use sys.getrefcount() to see how many references an object has. (The > output is +1 because getrefcount() has a temporary reference to the object > too). > > py> x="Hello World" > py> sys.getrefcount(x) > 2 > > See how many references your obj have. After calling doStuff or doMoreStuff, > you can have more references if those functions store `self` somewhere, or > pass it to another method that does so. > > > It seems to me that the GC forgets about obj after a certain amount of > > time. I can force the destructor to be called using del obj at the end > > of my function, but why do I have to call this explicitly? > If del obj works at the end, exiting the function should work too. Both ways > you decrement the rc. There is something *more* in here. > > -- > Gabriel Genellina Thanks for the reply. I tried using a longer sleep before the del but the destructor wasn't called this time. I guess del is not the issue here what so ever. As far as I can see, the garbage collector forgets about my object after a certain period of time. The fix i'm using now is to use Destruct functions in my CoM object which I call explicitly. def fnction: obj = comobj.createACertainObject() obj.doStuff() sleep(10) obj.doMoreStuff() obj.Destruct() I'd still love to know what the issue is here. Thanks, Barry. From write2unique at optonline.net Fri Jan 5 06:20:42 2007 From: write2unique at optonline.net (Unique Merchandise Outlet) Date: Fri, 05 Jan 2007 06:20:42 -0500 Subject: !MAKE MONEY USING PAYPAL- IT WORKS! Message-ID: Hello, I wonder if you can help me out..I received an extrememly obnoxious e-mail from someone who told me this is a SCAM and, not a LEGAL way to make money, and that Paypal, even has a policy against it. Every forum you read this in, where people are posting this same opportunity, I have NOT seen anything about this being an issue. Do you know anything about it. Would love the help of some HONEST people that know about this. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From jweida at gmail.com Thu Jan 25 00:03:05 2007 From: jweida at gmail.com (Jerry) Date: 24 Jan 2007 21:03:05 -0800 Subject: How can i do this in Python? In-Reply-To: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> References: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> Message-ID: <1169701385.113924.50270@l53g2000cwa.googlegroups.com> Well, the python interpreter has no equivalent to -n or -a in the perl interpreter. You'd have to implement it using an actual while loop and because of the indention sensitivity in Python, I don't believe you can do it on the command line. (I may be very wrong here, but I've not gotten it to work). -- Jerry On Jan 24, 10:25 pm, "NoName" wrote: > perl -ane "print join(qq(\t), at F[0,1,20,21,2,10,12,14,11,4,5,6]).qq(\n)" > file.txt > > -a autosplit mode with -n or -p (splits $_ into @F) > -n assume "while (<>) { ... }" loop around program From martin at v.loewis.de Wed Jan 17 15:28:24 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 17 Jan 2007 21:28:24 +0100 Subject: XLM prolgoue In-Reply-To: <1169054322.500863.313660@11g2000cwr.googlegroups.com> References: <1169054322.500863.313660@11g2000cwr.googlegroups.com> Message-ID: <45AE86E8.9020207@v.loewis.de> fscked schrieb: > How do I go about creating the XML prologue like I want it to be? print " % (version, encoding) Regards, Martin From __peter__ at web.de Thu Jan 25 03:38:41 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Jan 2007 09:38:41 +0100 Subject: logging module and doctest References: <1169703145.393435.166020@m58g2000cwm.googlegroups.com> Message-ID: Gary Jefferson wrote: > I've written a logging.filter and would like to use doctest on it > (using a StreamHandler for stdout), but this doesn't seem possible. > Output from the logger seems to disappear (running the doctest strings > through the interpreter as-is yields expected results). I assume this > is because doctest does something with logging. It redirects stdout to a StringIO subclass to capture the output. > Is there any way to make these work together? Using the StreamHandler with something like class WrapStdOut(object): def __getattr__(self, name): return getattr(sys.stdout, name) instead of sys.stdout directly should work. Peter From oyekomova at hotmail.com Tue Jan 9 21:28:58 2007 From: oyekomova at hotmail.com (oyekomova) Date: 9 Jan 2007 18:28:58 -0800 Subject: Read CSV file into an array Message-ID: <1168396138.395017.299530@o58g2000hsb.googlegroups.com> I would like to know how to read a CSV file with a header ( n columns of float data) into an array without the header row. From gregtech at wp.pl Tue Jan 16 16:49:40 2007 From: gregtech at wp.pl (Grzegorz Smith) Date: Tue, 16 Jan 2007 22:49:40 +0100 Subject: Python and Soap protocol Message-ID: <164s123s8zosf$.gx6o8cywx5af.dlg@40tude.net> Hi folks I must write webb application that will comunicate with delphi desktop application by SOAP protocol. Can you recommend any Python Soap Libary? I founded: SOAPpy and Zolera SOAP Infrastructure (ZSI). Any tip which is better to use? Thanks for any help Gregor From gagsl-py at yahoo.com.ar Thu Jan 11 17:47:02 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 19:47:02 -0300 Subject: globals accros modules In-Reply-To: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> Message-ID: <7.0.1.0.0.20070111192224.057daae0@yahoo.com.ar> At Thursday 11/1/2007 11:55, stef wrote: >Of course I completely agree with you. > >But ... >if you're moving from MatLab to Python, >and want to show your collegaes, >with how little effort they can reuse all their existing MatLab routines >in Python, >then the global issue is a real pain !! > >You can explain your collegaes, that >- the startindex of arrays changes from 1 to 0 >- slices are upto, instead of including the final border >- indention is th? key >And tell them about all beautiful things in Python, >but tell them that they are going to loose all their globals ??? Yes -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From greg at cosc.canterbury.ac.nz Sun Jan 28 01:58:15 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 28 Jan 2007 19:58:15 +1300 Subject: subclassing pyrex extension types in python In-Reply-To: <1169178838.303291.291740@s34g2000cwa.googlegroups.com> References: <1169178838.303291.291740@s34g2000cwa.googlegroups.com> Message-ID: <45BC4987.3000807@cosc.canterbury.ac.nz> Nitin wrote: > I am trying to subclass an extension type in Python and add attributes > to the new class but I keep getting errors. > > cdef class Spam: > > cdef int amount > > def __new__(self): > self.amount = 0 > > I get an error "TypeError: 'name2' is an > invalid keyword argument for this function" Arguments to the constructor of a class are passed to its __new__ method as well as its __init__ method, so if you want to subclass it in Python, you need to allow for that by defining it as def __new__(self, *args, **kwds): ... Without that, your Python subclass would have to define its own __new__ method which accepts the extra args and strips them out, e.g. class MySpam(Spam): def __new__(cls, name1=None, name2=None): return Spam.__new__(cls) -- Greg From duncan.booth at invalid.invalid Wed Jan 24 13:29:35 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jan 2007 18:29:35 GMT Subject: Thoughts on using isinstance References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> <1169659264.605545.211000@s48g2000cws.googlegroups.com> Message-ID: Gabriel Genellina wrote: > In > the example above, you can validate that fileobject has a write > attribute: getattr(fileobject, "write"). But I'd only do that if I > have a good reason (perhaps if the file is used after some lengthy > calculation,and I want to be sure that I will be able to store the > result) Or even just: write = fileobject.write data = ... lengthy calculation here ... write(data) There is no point using getattr when you know the name of the attribute in advance. From http Mon Jan 29 15:44:15 2007 From: http (Paul Rubin) Date: 29 Jan 2007 12:44:15 -0800 Subject: Sourcing Python Developers References: <45BE4348.9020500@gmail.com> Message-ID: <7xirepimw0.fsf@ruckus.brouhaha.com> Kartic writes: > In any case, we have immediate requirements for a Pythonista with C++, > MySQL, XML, Debian expertise. Please email resume to: Generally it's ok to post here to the newsgroup with Python jobs. But you should describe the specific openings you're trying to fill, and their locations. From skip at pobox.com Sun Jan 7 15:11:37 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 7 Jan 2007 14:11:37 -0600 Subject: strange for loop construct In-Reply-To: <1168200211.928423.319260@38g2000cwa.googlegroups.com> References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> <12ptf5bl21f2teb@corp.supernews.com> <1168193206.598957.257700@38g2000cwa.googlegroups.com> <1168200211.928423.319260@38g2000cwa.googlegroups.com> Message-ID: <17825.21497.148898.986938@montanaro.dyndns.org> Gabriel> Where do you find the "What's new" for previous releases? I Gabriel> have to read them online. >> >> Google for >> > what's new site:python.org Sorry, I took "I have to read them online" to mean that you needed to read them online because (perhaps) you don't have a source distribution on your computer. My 2.5 source (Subversion sandbox) has 2.0 through 2.5 What's New source in Doc/whatsnew. Skip From bthom at cs.hmc.edu Fri Jan 5 00:59:13 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Thu, 04 Jan 2007 21:59:13 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167974907.497878.61070@i15g2000cwa.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1167974907.497878.61070@i15g2000cwa.googlegroups.com> Message-ID: On Jan 4, 2007, at 9:28 PM, Carl Banks wrote: > jeremito wrote: >> I am writing a class that is intended to be subclassed. What is the >> proper way to indicate that a sub class must override a method? > > You can't (easily). > > If your subclass doesn't override a method, then you'll get a big fat > AttributeError when someone tries to call it. But this doesn't stop > someone from defining a subclass that fails to override the method. > Only when it's called will the error show up. You can, as others have > noted, define a method that raises NotImplementedError. But this > still > doesn't stop someone from defining a subclass that fails to override > the method. The error still only occurs when the method is called. > > There are some advantages to using NotImplementedError: > > 1. It documents the fact that a method needs to be overridden > 2. It lets tools such as pylint know that this is an abstract method > 3. It results in a more informative error message > > But, in the end, if someone wants to define a class that defiantly > refuses to declare a method, you can't stop them. This is the con of a dynamic language... From tpawley at gmail.com Fri Jan 12 07:50:40 2007 From: tpawley at gmail.com (Torabisu) Date: 12 Jan 2007 04:50:40 -0800 Subject: Tools Designing large/complicated applications In-Reply-To: References: Message-ID: <1168606240.143950.299770@38g2000cwa.googlegroups.com> Carl J. Van Arsdall wrote: > For those of you that work on larger applications but still code in > python... do your development teams use any tools to facilitate the > design? (i'm not asking about editors here, i'm really asking about > software design tools) Are these the same tools you would use to help > engineer software in another language? > > Is there anyone here who is forced to use a tool to design python > software that completely hates it? Why do you hate it? > > Thanks! > > -carl > > > -- > > Carl J. Van Arsdall > cvanarsdall at mvista.com > Build and Release > MontaVista Software Our software architects use Enterprise Architect. Its probably one of the cheaper modeling and UML design applications, but loaded with features. They do all the use cases, analysis and design with it, then give us the necessary flow / activity diagrams and information that we then use to construct our python applications. It does have a python interface (and obviously c, c#, java, php etc etc) allowing python code to be imported for class design etc etc. I've played with a few open source UML based tools, but unfortunately its not one of my strengths, I leave that up to the guys that know it well. From bdesth.quelquechose at free.quelquepart.fr Wed Jan 24 16:46:20 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Jan 2007 22:46:20 +0100 Subject: Static variables In-Reply-To: References: Message-ID: <45b7ccf3$0$22783$426a74cc@news.free.fr> Florian Lindner a ?crit : > Hello, > does python have static variables? I mean function-local variables that keep > their state between invocations of the function. Not directly. But there are ways to have similar behaviour: 1/ the mutable default argument hack: def fun(arg, _hidden_state=[0]): _hidden_state[0] += arg return _hidden_static[0] * 2 2/ using OO: class Fun(object): def __init__(self, static=0): self._state = static def __call__(self, arg): self._state += arg return self._state * 2 fun = Fun() HTH From manstey at csu.edu.au Wed Jan 31 18:09:29 2007 From: manstey at csu.edu.au (manstey) Date: 31 Jan 2007 15:09:29 -0800 Subject: parent-child object design question In-Reply-To: References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> Message-ID: <1170284969.902118.155570@l53g2000cwa.googlegroups.com> Thanks for your input. Here is my next version, which works very well, but for one problem I explain below: class CacheProperty(object): def __init__(self, insCacheClass, name): self.Name = name self._bind_to_parent(insCacheClass) self.__parent = insCacheClass self.__pyValue = self.__parent.get(name) def _bind_to_parent(self, parent): setattr(parent, self.Name, self) def get(self): return self.__pyValue def set(self, val): self.__parent.set(self.Name, val) self.__pyValue = val # Set in wrapper's copy Value = property(get, set) def __repr__(self): return str(self.Value) def __str__(self): return str(self.Value) class CacheClass(object): def __init__(self, obj): self.__data = obj def getOref(self): return self.__data def __repr__(self): return 'self.__data' def __str__(self): return str(self.__data) def __getattr__(self, attr): return getattr(self.__data, attr) Our code works fine as follows (oref is in-memory version of Cache oo- dbase class, and is an old-style class that comes with set and get and run_obj_method methods): >>> insCacheClass = CacheClass(oref) >>> insCacheProperty = CacheProperty(insOref,'Chapter') >>> print insOref.Chapter.Value 5 >>> print insOref.Chapter.Name 'Chapter' >>> insOref.Chapter.Value=67 >>> print insOref.Chapter 67 However, the problem is now that I can also write: >>> insOref.Chapter=67 but we want to disallow this, as insOref.Chapter must remain = insProperty We add various other instances of CacheProperty to the insOref as well, btw. So any idea how to prohibit this, and can the class code above be improved? Does it matter that each instance of CacheProperty contains self.__parent? Does it actually "contain" the parent (I realise this is not 'parent' in usual python lingo - what would be a better term?), or is self.__parent simply point to it somehow? I don't understand this part of python at all! Thanks, you are being a great help in our development. From smusnmrNOSPAM at yahoo.com Tue Jan 9 03:01:36 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Tue, 9 Jan 2007 09:01:36 +0100 Subject: help: code formatter? References: Message-ID: Thomas wrote: > Tools\scripts\reindent.py in your Python distribution. Thank you Thomas! What a bucket full of toolsin \tools! I didn't know that. siggi "Thomas Heller" schrieb im Newsbeitrag news:mailman.2417.1168270685.32031.python-list at python.org... > siggi schrieb: >> Hi all, >> >> as a newbie I have problems with formatting code of downloaded programs, >> because IDLE's reformatting capabilities are limited . Incorrect >> indentation, mixing of TAB with BLANKs or eol are often very nasty to >> correct. >> Is there a simple code formatter that first removes all indentations and >> then refomats correctly? >> >> Please help! > > > Tools\scripts\reindent.py in your Python distribution. > > Thomas From eurleif at ecritters.biz Mon Jan 15 11:28:06 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 15 Jan 2007 11:28:06 -0500 Subject: __getattr__ equivalent for a module In-Reply-To: References: Message-ID: <45abab5e$0$15166$4d3efbfe@news.sover.net> Maksim Kasimov wrote: > so my question is: how to tune up a module get default attribute if we > try to get access to not actually exists attribute of a module? You could wrap it in an object, but that's a bit of a hack. import sys class Foo(object): def __init__(self, wrapped): self.wrapped = wrapped def __getattr__(self, name): try: return getattr(self.wrapped, name) except AttributeError: return 'default' sys.modules[__name__] = Foo(sys.modules[__name__]) From michael at mustun.ch Wed Jan 3 10:36:18 2007 From: michael at mustun.ch (mm) Date: Wed, 03 Jan 2007 16:36:18 +0100 Subject: C/C++, Perl, etc. to Python converter Message-ID: Is there a Perl to Python converter? Or in general: a XY to Python converter? Is see, that Python is much better then Perl anyway. But for beginners, they whant to konw how is this done with Python etc. Sure, there are some docus out there in the internet. But a converter? From oliver at obeattie.com Fri Jan 5 10:15:44 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 5 Jan 2007 07:15:44 -0800 Subject: Encoding / decoding strings In-Reply-To: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> Message-ID: <1168010144.000928.131920@42g2000cwt.googlegroups.com> Basically, I want to encode an email address so that it looks something like 8d2e23c0a835598510c88a758c6b215a - this way the user does not know the email address they are looking at. They are public-facing views and they are to get info about other users, therefore anonymity is important. Any suggestions? From robert.kern at gmail.com Wed Jan 24 16:35:30 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 24 Jan 2007 15:35:30 -0600 Subject: Simple Matrix class In-Reply-To: <7xodooi16j.fsf@ruckus.brouhaha.com> References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> <1169664540.120687.211350@s48g2000cws.googlegroups.com> <1169670271.547292.141110@l53g2000cwa.googlegroups.com> <7xodooi16j.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > You might look at the Numerical Recipes books for clear descriptions > of how to do this stuff in the real world. Maybe the experts here > will jump on me for recommending those books since I think the serious > numerics crowd scoffs at them (they were written by scientists rather > than numerical analysts) but at least from my uneducated perspective, > I found them very readable and well-motivated. As a scientist (well, former scientist) and programmer, I scoff at them for their code. The text itself is decent if you need a book that covers a lot of ground. For any one area, though, there are usually better books. _Matrix Computations_, which I mentioned elsewhere, is difficult to beat for this area. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From me at rpatterson.net Mon Jan 15 18:42:40 2007 From: me at rpatterson.net (Ross Patterson) Date: Mon, 15 Jan 2007 15:42:40 -0800 Subject: Cygwin Python/PIL TCL/TK fork rebase solution Message-ID: <87ejpvluvj.fsf@superfluity.lefae.org> I recently was forced to build PIL under Cygwin Python 2.4.3 and ran into the Cygwin fork/rebase issue with TCL/TK yet again. Unfortunately, none of the rebase workarounds I found through my copious STFWing worked this time. Through trial and error I found that the following worked: rebase -b 0x1000000000 /bin/tk84.dll I post this here mostly for documenatation so that others can find a more current solution than what's already available through STFWing. But I'm also curious about rebase and to understand more about how one chooses what base address and offset to use. In my trial and error I found that the default base address of 0x70000000 didn't work, nor did the value of 0x68000000 I found through my STFWing. I found the value of 0x1000000000 by incrementing from 0x10000000 to 0x20000000 to 0x30000000 and so on until I found one that worked. So if anyone wants to explain to me how to choose base address and offset values, that would be cool. Ross From smusnmrNOSPAM at yahoo.com Sat Jan 6 14:00:24 2007 From: smusnmrNOSPAM at yahoo.com (Siggi) Date: Sat, 6 Jan 2007 20:00:24 +0100 Subject: Python and SDK5.1 are just terrific!!! References: <0Kynh.432$sE.358@read3.inet.fi> Message-ID: Thanks, Jussi, for your post, but I found that PythonWin's SDK5.0 option works well with MS SDk5.1. Just had an Email read for me using a small Python program: correct English, even the date such as 12/06/06 was correctly transformed into the names of the month and year. Python is great1 Siggi "Jussi Salmela" schrieb im Newsbeitrag news:0Kynh.432$sE.358 at read3.inet.fi... > Siggi kirjoitti: >> Gabriel Genellina wrote: >> >>> After you download and install version 5.1, it should appear on the >>> list. >> >> It should, but it does not! Shutting down and starting the WinXP Home >> system anew did not help. >> The SDK 5.1 installation went smoothly, however. What can I do to find >> out >> what is wrong? >> >> siggi >> > > > (Sorry for the long post!) > > > Unfortunately I can't comment on this 5.0/5.1 issue but if you look at > page > http://www.cs.unc.edu/~parente/tech/tr02.shtml > you'll find the pyTTS system. I've used it and everything works. > > The funny thing is that the page has a link named "Microsoft SAPI 5.1 > redistributable" which links to > http://www.cs.unc.edu/Research/assist/packages/SAPI5SpeechInstaller.msi > ie. a SAPI 5 installer. So I'm starting to wonder if it matters at all > whether the speech kit is a version 5 or 5.1. > > Anyway: pyTTS works with Python 2.4 as advertized in the accompanying > examples. I've used it to resolve the following dilemma: how to guarantee > that I'm aware of new mail appearing on my ISP. > > I had an unfortunate experience where a guy I was working with sent me (to > my home) mail that I didn't expect to receive just at the moment and to > which I would have liked to react immediately. Why I didn't notice the > mail coming: I was outside my house pumping more air to my wife's bicycle > tires! The mail notification was shown and erased and one more icon among > the more than dozen icons on my Windows System Tray didn't account for > much. > > So I figured out that a voice to remind me would be nice. I have a low > rate inbox, usually only a maximum of hald a dozen messages per day so I > wouldn't have to listen the voice all day long. So the voice keeps > repeating that I have new mail at my ISP until I download the mail and > otherwise keeps quiet. So here is my program and a skeleton of the INI > file it uses. The program is not finished (I have a few ideas still) but > it runs all day long on my computer keeping me happy. > > ========================== > New Email Notifier.py > ========================== > #!/usr/bin/python > > ''' > License: MIT License. See License.txt. If that file is not attached, > the license is http://www.opensource.org/licenses/mit-license.php, > where > = 2006 and = Jussi Salmela, Turku, Finland > ''' > > # This program checks for new email at ISP and notifies if new email is > found > > import win32serviceutil > import win32service > import win32event > import pyTTS, sys, os, poplib, logging, time > import ConfigParser,pywintypes > > print '\nThis is the New Mail Notifier window\n' > notifierDirectory = r'C:\Python\OMAT___PROJEKTIT\New Email Notifier > Service' > logging.basicConfig(level=logging.DEBUG, > format='%(asctime)s %(levelname)-8s %(message)s', > filename=notifierDirectory+r'\error.log') > logging.info('=========================================================') > logging.info('New Email Notifier Service started') > config = ConfigParser.ConfigParser() > config.readfp(open(notifierDirectory+r'\New Email Notifier.INI')) > POP3Server = config.get('POP3','server') > POP3Account = config.get('POP3','account') > POP3Password = config.get('POP3','password') > totalMessagesFormat = config.get('messages','total_message') > newMessagesFormat = config.get('messages','new_message') > wakeupMessageFormat = config.get('messages','wakeup_message') > > tts = pyTTS.Create() > #set the speech volume percentage (0-100%) > tts.Volume = 100 > #explicitly set a voice > tts.SetVoiceByName(u'MSMary') > > uidDict = {} > # We wait to be stopped and check for new email every maxTimeToWait > seconds > maxTimeToWait = 1 # First check after 1 second > while True: > time.sleep(maxTimeToWait) > maxTimeToWait = 60 # Rest of the checks after 60 second > try: > # Connect to the ISP > a = poplib.POP3(POP3Server,110) > answer = a.getwelcome() > if answer[0:3] != '+OK': > raise ValueError,'a.getwelcome returned: ' + answer > answer = a.user(POP3Account) > if answer[0:3] != '+OK': > raise ValueError,'a.user returned: ' + answer > if answer[4:] == 'Password required': > answer = a.pass_(POP3Password) > if answer[0:3] != '+OK': > raise ValueError,'a.pass_ returned: ' + answer > answer = a.uidl() > if answer[0][0:3] != '+OK': > raise ValueError,'a.uidl returned: ' + repr(answer) > a.quit() > # Connection closed. Start handling the unique message identifiers > #logging.info('Connection succesfully opened, used and closed!') > print 'answer', answer, time.asctime() > uidList = [e.split()[1] for e in answer[1]] > print 'uidList', uidList > totalMessages = len(uidList) > uidDictNew = {} > for e in uidList: uidDictNew[e] = True > uidList = [e for e in uidList if e not in uidDict] > uidDict = uidDictNew > if totalMessages: > tts.Speak(totalMessagesFormat % totalMessages) > newMessages = len(uidList) > if newMessages: > tts.Speak(newMessagesFormat % newMessages) > except Exception,inst: > errorMsg = 'Unexpected error: %s' % sys.exc_info()[0] > logging.error(errorMsg) > logging.error(inst) > try: > tts.Speak(wakeupMessageFormat) > tts.Speak('I repeat: ' + wakeupMessageFormat) > tts.Speak(errorMsg) > tts.Speak(inst) > except pywintypes.com_error,inst: > errorMsg = 'Unexpected error: %s' % sys.exc_info()[0] > logging.error(errorMsg) > logging.error(inst) > > ========================== > New Email Notifier.INI > ========================== > [POP3] > server: myPOPserver > account: myAcoount > password: myPassword > [messages] > total_message: Your eemail server has. a total of %d messages. for you to > download > new_message: The number of new messages. since the last check. is %d > wakeup_message: Wake up, Youssi! This is your new eemail notifier, > reporting the following error! > > HTH, > Jussi From bearophileHUGS at lycos.com Sat Jan 13 19:43:46 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Jan 2007 16:43:46 -0800 Subject: Comparing a matrix (list[][]) ? In-Reply-To: References: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> Message-ID: <1168735426.313475.212710@11g2000cwr.googlegroups.com> Roberto Bonvallet: > What output are you expecting from your example matrix? If you are expecting > it to be 5 (the smallest positive element), using "min" is the way to do it: > >>> matrix = [[9, 8, 12, 15], > ... [0, 11, 15, 18], > ... [0, 0, 10, 13], > ... [0, 0, 0, 5]] > >>> min(min(x for x in row if x > 0) for row in matrix) > 5 This looks a bit like homework... To find the minimal number > 0 of the matrix this seems better: mat = [[9, 8, 12, 15], [0, 11, 15, 18], [0, 0, 10, 13], [0, 0, 0, 5]] print min(el for row in mat for el in row if el > 0) Note that this raises TypeError is the matrix doesn't have one or more numbers > 0 If the OP needs the position he/she can do something like: nozeromin = 1e300 # or something similar pos = None, None for nrow, row in enumerate(mat): for ncol, el in enumerate(row): if el > 0 and el < nozeromin: nozeromin = el pos = nrow, ncol print nozeromin, pos Bye, bearophile From gagsl-py at yahoo.com.ar Sat Jan 27 13:21:12 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Jan 2007 15:21:12 -0300 Subject: IP address of webserver References: <1169918690.690636.42690@a75g2000cwd.googlegroups.com> Message-ID: "Johny" escribi? en el mensaje news:1169918690.690636.42690 at a75g2000cwd.googlegroups.com... > How can I find server's IP address? >>From console I can use ping, for example: > > C:\RobotP\cgi-bin>ping www.google.com > Pinging www.google.com [209.85.129.147] with 32 bytes of data: > [...] > But how can I find it directly from Python script? py> import socket py> help(socket.gethostbyname) Help on built-in function gethostbyname in module _socket: gethostbyname(...) gethostbyname(host) -> address Return the IP address (a string of the form '255.255.255.255') for a host. py> socket.gethostbyname("www.google.com") '209.85.165.147' -- Gabriel Genellina From sturlamolden at yahoo.no Wed Jan 10 15:43:42 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 Jan 2007 12:43:42 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168458486.538863.316130@k58g2000hse.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> Message-ID: <1168461822.591030.74360@i56g2000hsf.googlegroups.com> oyekomova wrote: > Thanks for your help. I compared the following code in NumPy with the > csvread in Matlab for a very large csv file. Matlab read the file in > 577 seconds. On the other hand, this code below kept running for over 2 > hours. Can this program be made more efficient? FYI - The csv file was > a simple 6 column file with a header row and more than a million > records. > > > import csv > from numpy import array > import time > t1=time.clock() > file_to_read = file('somename.csv','r') > read_from = csv.reader(file_to_read) > read_from.next() > datalist = [ map(float, row[:]) for row in read_from ] I'm willing to bet that this is your problem. Python lists are arrays under the hood! Try something like this instead: # read the whole file in one chunk lines = file_to_read.readlines() # count the number of columns n = 1 for c in lines[1]: if c == ',': n += 1 # count the number of rows m = len(lines[1:]) #allocate data = empty((m,n),dtype=float) # create csv reader, skip header reader = csv.reader(lines[1:]) # read for i in arange(0,m): data[i,:] = map(float,reader.next()) And if this is too slow, you may consider vectorizing the last loop: data = empty((m,n),dtype=float) newstr = ",".join(lines[1:]) flatdata = data.reshape((n*m)) # flatdata is a view of data, not a copy reader = csv.reader([newstr]) flatdata[:] = map(float,reader.next()) I hope this helps! > Robert Kern wrote: > > oyekomova wrote: > > > I would like to know how to convert a csv file with a header row into a > > > floating point array without the header row. > > > > Use the standard library module csv. Something like the following is a cheap and > > cheerful solution: > > > > > > import csv > > import numpy > > > > def float_array_from_csv(filename, skip_header=True): > > f = open(filename) > > try: > > reader = csv.reader(f) > > floats = [] > > if skip_header: > > reader.next() > > for row in reader: > > floats.append(map(float, row)) > > finally: > > f.close() > > > > return numpy.array(floats) > > > > -- > > Robert Kern > > > > "I have come to believe that the whole world is an enigma, a harmless enigma > > that is made terrible by our own mad attempt to interpret it as though it had > > an underlying truth." > > -- Umberto Eco From robert.kern at gmail.com Sun Jan 21 18:25:21 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 Jan 2007 17:25:21 -0600 Subject: Reading Fortran Data In-Reply-To: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> Message-ID: Tyler wrote: > Hello All: > > After trying to find an open source alternative to Matlab (or IDL), I > am currently getting acquainted with Python and, in particular SciPy, > NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's > NumPy manual, I have a quick question (hopefully) regarding how to read > in Fortran written data. > > The data files are not binary, but ASCII text files with no formatting > and mixed data types (strings, integers, floats). For example, I have > the following write statements in my Fortran code: Konrad Hinsen has a module for reading this kind of file. http://dirac.cnrs-orleans.fr/ScientificPython/ Specifically, Scientific.IO.FortranFormat . -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tubby at bandaheart.com Thu Jan 18 23:44:29 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 18 Jan 2007 23:44:29 -0500 Subject: Determining when a file is an Open Office Document In-Reply-To: <1169171820.851021.49200@l53g2000cwa.googlegroups.com> References: <1169171820.851021.49200@l53g2000cwa.googlegroups.com> Message-ID: Ross Ridge wrote: > tubby wrote: >> Silly question, but here goes... what's a good way to determine when a >> file is an Open Office document? I could look at the file extension, but >> it seems there would be a better way. VI shows this info in the files: >> >> mimetypeapplication/vnd.oasis.opendocument.textPK > > It's a ZIP archive. Thanks, I used this approach: import zipfile if zipfile.is_zipfile(filename): ... Now, If only I could something like that on PDF files :) From Barry.Carroll at psc.com Mon Jan 8 19:07:58 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 8 Jan 2007 16:07:58 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A6A@eugsrv400.psc.pscnet.com> John: <<> > > Hi Barry, > > Please always reply on-list if the communication is non-private -- and > meaningful :-) Right. I noticed I hadn't "replied-to-all", so I resent the post to the mailing list. Slip of the mouse, no disrespect intended to the list ;^) > > I don't know; here are some things you could check out: > > (1) Windows XP versus *x: The limit on open file handles is 512 in > Windows XP; write yourself a reference-preserving [hint: append to a > list] multiple file opener on *x and see how many you get open. I have > vague recollections of the number 1024 being mentioned. By rough calculation, we had been through over 500 table invocations when the error message started showing up. That fits well enough with the number of Windows file handles. I'll check the Linux value. > > (2) Python 2.4 versus 2.5: Read the "what's new" doc, fire up your > googler, ... I read through the 2.5 release notes and didn't see anything that looked related. I may have been looking for the wrong thing. I'll check again. > IMHO, the attitude should be to program defensively so that you need > neither to know nor care about such implementation-specific concerns. > Operating systems these days give you enough file handles to do any > reasonable job. It's many moons since MS-DOS 2.n with its max 20 open > file handles made folks implement LRU caches for file handles. > > Simple rules about unwanted objects include: > (1) If an object has a free() or close() method, then call it! > (2) Unbind *all* references to the object. I tend to agree with you. I am not the lead programmer on this project, however, so my preferences do not always get implemented. This time, though, as I said, the explicit file close has been retained. > Have you checked out my point 2 (holding multiple references to your > Parser objects)? Not yet, but I will. > > Cheers, > John Again, thanks. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From ironfroggy at gmail.com Mon Jan 15 21:38:42 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Mon, 15 Jan 2007 21:38:42 -0500 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: References: Message-ID: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> On 1/15/07, Steven D'Aprano wrote: > On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote: > > > assert foo(0x10) == 0 # Assertions are much better tests than prints :-) > > I dispute that assertion (pun intended). Hah! > Firstly, print statements work even if you pass the -O (optimize) flag > to Python. Your asserts don't. This is true, but the concept can be adapted to a things like an assert_() function. > Secondly, a bare assertion like that gives you very little information: it > just tells you that it failed: > > >>> x = 1 > >>> assert x == 0 > Traceback (most recent call last): > File "", line 1, in ? > AssertionError > > To provide the same information that print provides, you need something > like this: > > assert x == 0, "x == %s not 0" % x What information would I need to know if my test passed? Nothing, I say. I only want to know when the tests fail, especially as I add more of them. Having no output is a great way to know nothing puked. > Thirdly, and most importantly, assert and print aren't alternatives, > but complementary tools. Assertions are good for automated testing and > simple data validation, where you already know what values you should > have. Printing is good for interactively exploring your data when you're > uncertain about the values you might get: sometimes it is hard to know > what you should be asserting until you've seen what results your function > returns. True, but I intended my statement as a nudge towards more proper testing. Even when testing things out, I often use an assert rather than a print, to verify some condition. > -- > Steven D'Aprano > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From exarkun at divmod.com Sun Jan 14 19:47:23 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 14 Jan 2007 19:47:23 -0500 Subject: python - process id In-Reply-To: <109f01c7383d$45666f10$0301a8c0@tmesa.com> Message-ID: <20070115004723.11447.1419711265.divmod.quotient.16857@ohm> On Sun, 14 Jan 2007 16:36:58 -0800, bruce wrote: >hi... > >is there a way to have a test python app, get its' own processID. i'm >creating a test python script under linux, and was wondering if this is >possible.. See the os module, the getpid function. > >also, i've tried using an irc client to join the irc #python channel, and >for some reason i keep getting the err msg saying that the 'address is >banned' i've never been to the python channel, but i'm using dsl, so i'm >getting a dynamic address.. and yeah, i've tried changing the address a >number of times.. IRC bans can cover a wide range of addresses. Someone else on your ISP may have abused the channel badly enough to get a large range of addresses, maybe every address you could possibly get, banned from the channel. Jean-Paul From __peter__ at web.de Wed Jan 3 12:14:42 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Jan 2007 18:14:42 +0100 Subject: type classobj not defined? References: Message-ID: Wesley Brooks wrote: > Dear Users, > > I'm in the process of adding assert statements to a large piece of > code to aid with bug hunting and came across the following issue; > > Using python in a terminal window you can do the following: > >>type(False) == bool > True > > I would like to check that an object is a class, here's an example: > >>class b: > ....def __init__(self): > ........self.c = 1 > ....def d(self): > ........print self.c > >>type(b) > > > But the following fails: > >>type(b) == classobj > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'classobj' is not defined > > For the time being I'll use b.__name__ == b to ensure I'm getting the > right class. Is there a reason why the other types such as bool are > defined but classobj isn't? No idea. You can easily define it yourself, though: >>> class Classic: pass ... >>> classobj = type(Classic) >>> isinstance(Classic, classobj) True Note that "newstyle" classes (those deriving from object) are of type 'type', not 'classobj': >>> class Newstyle(object): pass ... >>> isinstance(Newstyle, classobj) False >>> isinstance(Newstyle, (classobj, type)) True The inspect module wraps the functionality in a function: >>> import inspect >>> inspect.isclass(Newstyle) True >>> inspect.isclass(Classic) True Peter From jhefferon at smcvt.edu Tue Jan 30 07:34:24 2007 From: jhefferon at smcvt.edu (Jim) Date: 30 Jan 2007 04:34:24 -0800 Subject: error messages containing unicode In-Reply-To: References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> Message-ID: <1170160464.576122.62230@h3g2000cwc.googlegroups.com> Thank you for the reply. It happens that, as I understand it, none of the options that you mentioned is a solution for my situation. On Jan 29, 9:48 pm, Steven D'Aprano wrote: > The easiest ways to fix that are: > > (1) subclass an exception that already knows about Unicode; But I often raise one of Python's built-in errors. And also, is it really true that subclassing one of Python's built-ins give me something that is unicode deficient? I assumed that I had missed something (because that's happened so many times before :-) ). For instance, I write a lot of CGI and I want to wrap everything in a try .. except. try: main() except Exception, err: print "Terrible blunder: ",str(err) so that the err can be one of my exceptions, or can be one that came with Python. (And, that I can see, err.args can be either the relevant string or a tuple containing the relevant string and the documentation is silent on whether in the built-in exceptions if err.args is a tuple then the string is guaranteed to be first in the tuple.) > (2) convert the file name to ASCII before you store it; or I need the non-ascii information, though, which is why I included it in the error message. > (3) add a __str__ method to your exception that is Unicode aware. I have two difficulties with this: (1) as above I often raise Python's built-in exceptions and for those __str__() is what it is, and (2) this goes against the meaning of __str__() that I find in the documentation in ref/customization.html which says that the return value must be a string object. Obviously no one will come to my house and slap me if I violate that, but I'll venture that it would be odd if the best practice were to be to do the opposite of the documentation. > I'm going to be lazy and do a real simple-minded version of (2): > > >>> class MyBetterException(Exception):... def __init__(self, arg): > ... self.args = arg.encode('ascii', 'replace') > ... self.unicode_arg = arg # save the original in case This is illuminating. How do you know that for exceptions __init__() should take one non-self argument? I missed finding this information. Thanks again, Jim From cfbolz at gmx.de Sat Jan 20 10:23:44 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sat, 20 Jan 2007 16:23:44 +0100 Subject: Py 2.5 on Language Shootout In-Reply-To: <1169275613.093797.67320@v45g2000cwv.googlegroups.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> Message-ID: <45B23400.2010906@gmx.de> pgarrone at acay.com.au wrote: >>> Looking over the benchmarks, one gains the impression that Python is a >>> slow language. >> What does that even mean - a slow language? >> > > The alioth benchmarks provide a set of numbers by which > languages may be compared. Wrong. The benchmarks provide a set of numbers by which _implementations_ of languages can be compared. After all, it is possible that someone implements a magic-pixie-dust-interpreter that executes Python programs several orders of magnitude fastes than CPython. Or you could say that C is slow because if you use CINT, a C interpreter ( http://root.cern.ch/root/Cint.html ) to execute it, it is slow. Cheers, Carl Friedrich Bolz From gandalf at designaproduct.biz Fri Jan 5 11:16:08 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 17:16:08 +0100 Subject: find a .py path In-Reply-To: References: Message-ID: <459E79C8.5070601@designaproduct.biz> hg i'rta: > Hi, > > Is there an easy way for a script being executed (from anywhere) to know > where is is ... something in os.path ? > __file__ You can also use os.argv[0] but that is not the same... Laszlo From jura.grozni at gmail.com Tue Jan 16 14:25:33 2007 From: jura.grozni at gmail.com (azrael) Date: 16 Jan 2007 11:25:33 -0800 Subject: How can I create a linked list in Python? In-Reply-To: References: Message-ID: <1168975533.142147.124370@51g2000cwl.googlegroups.com> How can I implement a linked list like the implementations in c with struct-s and arrays (or pointers). to simbolize the working principe Gary Herron je napisao/la: > Dongsheng Ruan wrote: > > with a cell class like this: > > > > #!/usr/bin/python > > > > import sys > > > > class Cell: > > > > def __init__( self, data, next=None ): > > self.data = data > > self.next = next > > > > def __str__( self ): > > return str( self.data ) > > > > def echo( self ): > > print self.__str__() > > > If you really want a list (as Python defines a list - with all the methods) then you should use Python's lists. They are quite efficient and convenient: > > l = [Cell(1), Cell(2), Cell(3)] > > However, if what you want is each cell to refer to a next cell (which after all is what a linked list does), then you already have it with the next attribute. (In other languages you might implement 'next' as a pointer, while in Python we call it a reference -- but it amounts to the same thing.) Create it this way: > > c = Cell(3) > b = Cell(2, c) > a = Cell(1, b) > > or > > a = Cell(1, Cell(2, Cell(3))) > > However, I'll repeat this: The concept of a linked list if a figment of languages with pointer data types. Python abstracts that by allowing attributes to contain references to other objects. However, you're much better off if you can use Python's list data structure rather than try to emulate an outdated concept in a modern language. > > Gary Herron From gagsl-py at yahoo.com.ar Wed Jan 24 20:04:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 22:04:55 -0300 Subject: Beginners Tutorial in PDF Format? In-Reply-To: References: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net> <1169415358.277431.130640@s34g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070124215923.01e3cb50@yahoo.com.ar> At Wednesday 24/1/2007 17:57, W. Watson wrote: >Gabriel Genellina wrote: > > "W. Watson" escribi? en el mensaje > > news:FJTsh.36658$Gr2.32367 at newssvr21.news.prodigy.net... > > Robert Hicks wrote: > >> W. Watson wrote: > >>> I'd like to print a tutorial in one fell swoop, but it seems most on the > >>> various sites are page by page embedded descriptions in the page. Any > >>> available as a pdf? > >> > >> http://docs.python.org/download.html > >> > >> http://www.diveintopython.org/ > >> > >> Thanks, but the first url takes me to a web page that contains the > >> complete > >> tutorial. Does choosing pdf (USA) in the table download a file that > >> contains > >> all the documents on the list below and to the left? > > > > Try again. The first url goes to this page: > > Download Python 2.5 Documentation (19 September 2006): To download an > > archive containing all the documents for this version of Python in one > > of various formats [pdf included, you can choose between Letter/A4]. > > Below, it says "These documents are not available for download > > individually." > > >There is nothing there with the title "Python 2.5 Documentation". What do you mean? The html tag contains "Download Python Documentation", the outstanding header (H3) says "Download Python 2.5 Documentation (19 September 2006)". There are links for downloading the docs in various formats, including the PDF format you want. Perhaps you have some browser problem. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From grahn+nntp at snipabacken.dyndns.org Tue Jan 9 06:57:57 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 9 Jan 2007 11:57:57 GMT Subject: Colons, indentation and reformatting. (2) References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> <45a33a24$0$7658$4c368faf@roadrunner.com> <1168329449.577659.214890@s34g2000cwa.googlegroups.com> Message-ID: <slrneq6uv2.tcj.grahn+nntp@frailea.sa.invalid> On 8 Jan 2007 23:57:29 -0800, Paddy <paddy3118 at netscape.net> wrote: > > OK, whilst colons are not sufficient to re-format a completely > mis-indented file. I'm thinking that they are sufficient for > reformatting most pasted code blocks when refactoring say? Let's put it this way: if the formatter can assume the original code is valid (i.e. has the intended indentation) then it can do all kinds of nifty things to it. Personally, I'm happy with what Emacs' python-mode offers: suggested indents as I type, and a command to indent/de-dent the highlighted block one step. /Jorgen -- // Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn! From CRhode at LacusVeris.com Wed Jan 17 09:43:39 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Wed, 17 Jan 2007 08:43:39 -0600 Subject: Conflicting needs for __init__ method In-Reply-To: <87r6tu80kl.fsf@benfinney.id.au> References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <mailman.2741.1168898073.32031.python-list@python.org> <pan.2007.01.16.03.02.03.4711@REMOVEME.cybersource.com.au> <740c3aec0701160837r33340866w5ddef3e09a0de537@mail.gmail.com> <873b6abp12.fsf@benfinney.id.au> <740c3aec0701170103k29c17df9xdb8c32a3a878ac00@mail.gmail.com> <87r6tu80kl.fsf@benfinney.id.au> Message-ID: <20070117144339.GL1906@loki> Ben Finney wrote this on Wed, Jan 17, 2007 at 08:27:54PM +1100. My reply is below. > I recommend, instead, separate factory functions for separate input > types. Uh, how 'bout separate subclasses for separate input types? -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 7? ? Wind SW 10 mph From goodepic at gmail.com Fri Jan 5 16:01:25 2007 From: goodepic at gmail.com (goodepic) Date: 5 Jan 2007 13:01:25 -0800 Subject: Problem Running Working Code on Mac In-Reply-To: <w3fnh.11876$Du.9197@newsfe15.lga> References: <1167946511.531632.41750@11g2000cwr.googlegroups.com> <w3fnh.11876$Du.9197@newsfe15.lga> Message-ID: <1168030884.878349.119950@38g2000cwa.googlegroups.com> I got rid of all the warnings but the pgdb one. I got postgresql and pygresql installed, but the pgdb installed on the base python install of python 2.3, and isn't found by my updated python 2.5 install, into which I've successfully installed the other modules I needed. Anyway, getting mysql and pypar didn't help, and I get those same three exact warnings when I run the script successfully on my work PC. I'm getting the same exact error quoted above still. Any more ideas? I really appreciate any help here!! From __peter__ at web.de Thu Jan 25 06:05:39 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Jan 2007 12:05:39 +0100 Subject: logging module and doctest References: <1169703145.393435.166020@m58g2000cwm.googlegroups.com> <ep9q9p$1o2$02$1@news.t-online.com> Message-ID: <epa2tb$4lj$00$1@news.t-online.com> Peter Otten wrote: > Gary Jefferson wrote: > >> I've written a logging.filter and would like to use doctest on it >> (using a StreamHandler for stdout), but this doesn't seem possible. >> Output from the logger seems to disappear (running the doctest strings >> through the interpreter as-is yields expected results). I assume this >> is because doctest does something with logging. > > It redirects stdout to a StringIO subclass to capture the output. > >> Is there any way to make these work together? > > Using the StreamHandler with something like > > class WrapStdOut(object): > def __getattr__(self, name): > return getattr(sys.stdout, name) > > instead of sys.stdout directly should work. Or create the StreamHandler inside your doctest where sys.stdout is already redirected. Peter From kirby.urner at gmail.com Thu Jan 18 16:22:48 2007 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: 18 Jan 2007 13:22:48 -0800 Subject: Tiling and Spacefilling Message-ID: <1169155368.600589.211310@a75g2000cwd.googlegroups.com> [ slightly improved over Math Forum draft ] Probably a fault line or cultural divide between acutely differing schools of thought, is in this area of tiling or mosaic making. Some schools consider this a stupid waste of time, others a core topic, whereas a 3rd group stays more neutral on the issue, and a tiny 4th group has no idea what I'm talking about. I'm in the second group (core topic) as tiling is to spacefilling as figurate are to polyhedral numbers. We may start in a plane, in deference to some millenia of pre-NASA reflex conditioning, but we're still on a runway, accelerating, and before long (way sooner than in traditional curricula), we'll be airborne, moving up into higher D. Tetrahedra are most definitely a feature of K-5. If NCTM doesn't grasp that, it's missing the boat. Back to tiling: we have the classifications, the Escher lithographs (which follow into Part Two), and the tie ins to Mesopotamian religions, the three biggies especially, and their respective sacred geometries. I know "sacred geometry" is taboo in traditional mathematics, but this is ~M!, Katrina Network type stuff, closer to George Bush Sr.'s "voodoo economics" (except managed more by geeks (Bush was more of a jock, not that we can't share power)). Rolling forward, we get to the Kepler-Penrose aperiodic tiling studies, various heuristics, again finding echoes in Part Two (in what some Russians call stereometry), where we likely look at Hargittai & Hargittai (Hungarian), plus Chakovian coordinates (quadrays, simplicials, whatever nomenclature). I've already made the case for Polyhedra numerous times. Thanks to breakthroughs in architecture in the 20th century, we're obligated to teach about the hexapent in some way shape or form. Katrina Network is strong on this, but you'll find other sources. Top of my list would be J. Baldwin's 'Bucky Works' (packed with ~M!). For a more prefrequency approach, I recommend Cromwell's 'Polyhedra', and its cartoon proof of Euler's V + F = E + 2 based on the interdigitating trees of Von Staudt's. And of course we're not about to bleep over Fuller's volumes tables, nor MITEs, nor the Jitterbug Trans- formation -- all pure gold as far as we're concerned. So to recap... Given I'm of a school which regards tiling as core, I'm putting my shoulder behind two big initiatives in computer science these days: CP4E and HP4E. CP4E was hatched by Guido, BDFL of Python Nation, and DARPA, and carried forward billiantly (at least one doctoral dissertation already on file, about our early beginnings as a think tank slash on-line community [1]). HP4E was hatched by yours trully, though mostly as a marketing gimmick in homage to CP4E and Wanderer Glenn Stockton's global matrix campaign. I certainly take advantage of Python a lot, using its generators (a recent feature) to spit out successive terms in figurate and polyhedral number sequences, e.g. 1, 3, 6, 10... and 1, 12, 42, 92... (see my Focal Points for more details, plus my CP4E website, one of many curriculum "hot springs" in our cyberspace-based Python Nation [2][3]). Kirby [1] John Miller's PhD dissertation, Promoting Computer Literacy Through Programming Python (1.37 MB), looks at the issues around teaching with Python, and explores some of the threads taken up on edu-sig. http://www.python.org/community/sigs/current/edu-sig/ [2] Focal Points: http://mybizmo.blogspot.com/2006/09/focal-points.html [3] CP4E website: http://www.4dsolutions.net/ocn/cp4e.html === For more on ~M!: http://worldgame.blogspot.com/2007/01/m.html From no-spam at no-spam-no-spam.invalid Wed Jan 17 06:20:53 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 17 Jan 2007 12:20:53 +0100 Subject: 2.3-2.5 what improved? In-Reply-To: <mailman.2817.1169029744.32031.python-list@python.org> References: <mailman.2817.1169029744.32031.python-list@python.org> Message-ID: <eol0qn$kvj$1@news.albasani.net> Robin Becker wrote: > A large cgi based web Python-2.3 application needs to be speed improved. > experiments show the following under reasonable testing (these are 2 > second reportlab pdf productions) > > 1) 2.3 --> 2.5 improvement small 1-2% > 2) cgi --> fcgi improvement medium 10-12% > > I sort of remember claims being made about 2.5 being 10% faster than > 2.4/2.3 etc etc. Can anyone say where the speedups were? Presumably we > have a lot of old cruft that could be improved in some way eg moving > loops into comprehensions, using iterator methods etc. Are those sort of > things what we should look at? Python 2.5 became quite fat. For bare CGI the Python load/init time eats all improvements. Smaller scripts even loose lot of speed. I still like Python 2.3 for many other reasons for many applications - especially for CGI's, on Windows, for deployable apps, GUI's etc. because the fat coming with Python 2.4 is not balanced by necessary goods - mostly just fancy things. ( I run even a list of patches and module copies/addaptations down to 2.3 because of that :-) ) Real news come with Py3K Robert From bdesth.quelquechose at free.quelquepart.fr Sat Jan 6 07:09:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Jan 2007 13:09:16 +0100 Subject: howto overload with a NOP (empty statement) In-Reply-To: <adeb4$459f7a11$d443bb3a$14652@news.speedlinq.nl> References: <adeb4$459f7a11$d443bb3a$14652@news.speedlinq.nl> Message-ID: <459f8b36$0$316$426a74cc@news.free.fr> Stef Mientki a ?crit : > How should I overload / disable a method ? > In the example below I have defined the class "Power_Supply", derived > from baseclass "device". <off> Naming conventions are to use CamelCase for class names. So it would be better to name your classes 'PowerSupply' (no '_') and 'Device'. You're of course free to use whatever naming convention you want, including no convention at all, but Python relies *a lot* on naming conventions... </off> > The baseclass has a method "execute", <off> Do you know that Python let you define your own 'callable' objects ? class SomeCallable(object): def __init__(self, name): self.name = name def __call__(self): print "wow, %s has been called" % self.name foo = SomeCallable('foo') foo() This may or not make sens in the context of your application, but whenever you find yourself naming a method 'execute', it might be worth asking yourself if the object should in fact be a callable... </off> > which will be implemented in most > derived classes, but not in all. > > Now apparently it's not allowed to overload a method with an empty > statement. > I could write a nonsense dummy statement, like "A= 3", but isn't there > another way ? the 'pass' statement def noop(): pass > thanks, Stef Mientki > > class device: > def execute (self): > print 'execute not yet implemented for', self.Name The usual idiom for 'pure virtual methods' is to raise a NotImplementedError. Now if it's ok for a subclass to implement the method as a no-op, why not just implement it as a no-op in the base class itself ? From tjreedy at udel.edu Tue Jan 23 19:50:12 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Jan 2007 19:50:12 -0500 Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com><Xns98C17C03B6297duncanbooth@127.0.0.1><1169563580.634000.122540@v45g2000cwv.googlegroups.com> <7xbqkpbt6c.fsf@ruckus.brouhaha.com> Message-ID: <ep6ag4$lba$1@sea.gmane.org> "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xbqkpbt6c.fsf at ruckus.brouhaha.com... | or the Python idiom [(lambda i=i: i) for i in range(10)] While the idiom is commonly written this way, I think it would be clearer if the two related but different variables had two different names: [(lambda j=i:j) for i in range(10)] Terry Jan Reedy From bg_ie at yahoo.com Wed Jan 10 04:16:57 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 10 Jan 2007 01:16:57 -0800 Subject: Establishing if an Object is Defined Message-ID: <1168420616.285450.306460@k58g2000hse.googlegroups.com> Hi, The following code works - one = 1 if one == 1: ok = 1 print ok but this does not, without exception - one = 2 if one == 1: ok = 1 print ok How do I establish before printing ok if it actually exists so as to avoid this exception? Thanks for your help, Barry. From S.Mientki-nospam at mailbox.kun.nl Wed Jan 3 11:47:26 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 03 Jan 2007 17:47:26 +0100 Subject: function without brackets ? In-Reply-To: <mailman.2241.1167835668.32031.python-list@python.org> References: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> <mailman.2241.1167835668.32031.python-list@python.org> Message-ID: <9ec5f$459bde0d$d443bb3a$24148@news.speedlinq.nl> > Hope this helps, > thanks You all guys, It's perfectly clear to me now ! cheers, Stef From Jeff.Demel at JavelinDirect.com Fri Jan 5 15:43:44 2007 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Fri, 5 Jan 2007 14:43:44 -0600 Subject: Learning to program in Python Message-ID: <136ED738BD4F1545B97E4AC06FF6370734C15C@DMSP-MSG-EVS01.mail.pvt> If I were you, I'd think up a project and just build it. The best way to really learn is to do, at least for me. If you run into problems, then you can come back and ask the group here. Believe me, I've asked some very basic questions, and everyone's been very friendly and helpful. As an EE major, maybe you can think of some project that interests you and build it. One thing that comes to mind is, maybe, a graphical program to lay out circuits? Parts inventory program? Circuit tester? I don't know, I was an English major, but you get the idea. Anyway, try to think of a project that includes several of the key fundamentals of programming that we do every day, like reading and writing files, reading and writing to a database, GUI development, and things like that. HTH -Jeff -----Original Message----- From: python-list-bounces+jeff.demel=javelindirect.com at python.org [mailto:python-list-bounces+jeff.demel=javelindirect.com at python.org] On Behalf Of jbchua Sent: Friday, January 05, 2007 2:22 PM To: python-list at python.org Subject: Learning to program in Python Hello everybody. I am an Electrical Engineering major and have dabbled in several languages such as Python, C, and Java in my spare time because of my interest in programming. However, I have not done any practical programming because I have no idea where to get started. I taught myself these languages basically by e-tutorials and books. This makes me feel as if I don't really know how to implement these languages. Does anybody have any advice on where to start applying my limited knowledge practically in order to advance my learning? -- http://mail.python.org/mailman/listinfo/python-list This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From kw at codebykevin.com Wed Jan 24 09:42:55 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 24 Jan 2007 09:42:55 -0500 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: <45B76FE8.5080701@codebykevin.com> References: <ep60jp$63v$1@aioe.org> <45B76FE8.5080701@codebykevin.com> Message-ID: <dc1aa$45b77070$4275d90a$10460@FUSE.NET> Kevin Walzer wrote: > > Tablelist: http://www.nemethi.de/ > Tabelist for Tkinter (with Tile support): > http://tkinter.unpythonic.net/wiki/TableListTileWrapper > Additionally, here is a link to some screenshots for Tablelist: http://www.nemethi.privat.t-online.de/tablelist/screenshots.html -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gbrunick at andrew.cmu.edu Mon Jan 8 19:47:27 2007 From: gbrunick at andrew.cmu.edu (Gerard Brunick) Date: Mon, 08 Jan 2007 19:47:27 -0500 Subject: Adding functions to classes after definition Message-ID: <45A2E61F.2080100@andrew.cmu.edu> Consider: A) >>> class C(object): ... pass ... >>> def f(*args): ... print args ... >>> C.f = f >>> C.f <unbound method C.f> >>> c=C() >>> c.f() (<__main__.C object at 0x04A51170>,) And B) >>> del c >>> C.f = types.MethodType(f, None, C) >>> C.f <unbound method C.f> >>> c = C() >>> c.f() (<__main__.C object at 0x04A51290>,) I don't understand A). It is my vague understanding, that methods are really properties that handle binding on attribute access, so B) should be the "right" way to add a method to a class after definition. Why does A show up as a method? Shouldn't it still just be a function? Certainly when you define a class, there is some magic in the __new__ method that turns functions in the initial dictionary into methods, but does this still happen for all setattr after that? Is is possible to set a class attribute equal to a regular (types.FunctionType) function? Any references that discuss these issues would be greatly appreciated. Thanks, Gerard From pavlovevidence at gmail.com Fri Jan 5 20:57:00 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 5 Jan 2007 17:57:00 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <1168042215.514023.121560@s80g2000cwa.googlegroups.com> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> Message-ID: <1168048620.409190.85870@v33g2000cwv.googlegroups.com> Martin Miller wrote: > ### non-redundant example ### > import sys > > class Pin: > def __init__(self, name, namespace=None): > self.name = name > if namespace == None: > # default to caller's globals > namespace = sys._getframe(1).f_globals > namespace[name] = self > > Pin('aap') # create a Pin object named 'aap' > Pin('aap2') # create a Pin object named 'aap2' > print aap.name > print aap2.name The problem with this is that it only works for global namespaces, while failing silently and subtly if used in a local namespace: def fun(): Pin('aap') aap1 = aap fun2() aap2 = aap print aap1 is aap2 def fun2(): Pin('aap') If it's your deliberate intention to do it with the global namespace, you might as well just use globals() and do it explicitly, rather than mucking around with Python frame internals. (And it doesn't make the class unusable for more straightforward uses.) for _name in ('aap','dcr'): globals()[_name] = Pin(_name) del _name Carl Banks From martin at v.loewis.de Wed Jan 3 10:50:36 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 03 Jan 2007 16:50:36 +0100 Subject: Filename encoding on XP In-Reply-To: <mailman.2227.1167786510.32031.python-list@python.org> References: <mailman.2227.1167786510.32031.python-list@python.org> Message-ID: <459bd0cc$0$20860$9b622d9e@news.freenet.de> kent sin schrieb: > What encoding does the NTFS store the filename? In UTF-16LE. However, on-disk storage is mostly irrelevant, what matters is what encoding is used on the OS API. Windows has two forms of file API: Wide (Unicode) and ANSI (byte-oriented). On NT, the Wide API is "native"; the ANSI API converts strings forth and back (introducing ? if the conversion fails). > I use walk, then print the filename, there are some ? in it, but some > Chinese characters were display with no problem. I suspect the > encoding of the filename is not unicode. You need to pass a Unicode string into walk as the directory; then recursively all results should also be Unicode strings. Regards, Martin From deets at nospam.web.de Wed Jan 24 12:59:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 Jan 2007 18:59:46 +0100 Subject: Thoughts on using isinstance References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <mailman.3077.1169645738.32031.python-list@python.org> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <mailman.3087.1169652310.32031.python-list@python.org> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> <pan.2007.01.24.16.49.21.555688@gmx.net> <1169659264.605545.211000@s48g2000cws.googlegroups.com> Message-ID: <51pl4jF1klvcfU1@mid.uni-berlin.de> abcd wrote: > good point. is there place that documents what methods/attrs I should > check for on an object? for example, if its a list that I expect I > should verify the object that is passed in has a ??? function? etc. Don't check, try. Catch a possible exception, and continue with another type assumption. The only thing one often checks is for basestring, as basestring supports iteration, but more than often isn't supposed to be iterated over. Small example to gather all strings out of a tree of objects (untested): def foo(arg): # string case if isinstance(arg, basestring): return [arg] # dict-like try: res = [] for value in arg.itervalues(): res.extend(foo(value)) return res except AttributeError: pass # generally iterables res = [] for value in arg: res.extend(foo(value)) return res Diez From bignose+hates-spam at benfinney.id.au Wed Jan 31 01:36:03 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 31 Jan 2007 17:36:03 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <mailman.3297.1170139632.32031.python-list@python.org> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> Message-ID: <871wlbwvn0.fsf@benfinney.id.au> "manstey" <manstey at csu.edu.au> writes: > Could I also do something like the following? I can't immediately see a problem with the code you posted. Does it do what you want it to do? > What does it mean to store the parent class as a private variable in > the child class? I don't understand this question. It's up to you what it means; I leave it to the people who know the purpose of the program to decide whether "parent" is even an appropriate term. -- \ "I took a course in speed waiting. Now I can wait an hour in | `\ only ten minutes." -- Steven Wright | _o__) | Ben Finney From simon at brunningonline.net Wed Jan 17 06:05:11 2007 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 17 Jan 2007 11:05:11 +0000 Subject: Python and Soap protocol In-Reply-To: <164s123s8zosf$.gx6o8cywx5af.dlg@40tude.net> References: <164s123s8zosf$.gx6o8cywx5af.dlg@40tude.net> Message-ID: <8c7f10c60701170305w19a46b05i12041d817f660f89@mail.gmail.com> On 1/16/07, Grzegorz Smith <gregtech at wp.pl> wrote: > Hi folks > I must write webb application that will comunicate with delphi desktop > application by SOAP protocol. Can you recommend any Python Soap Libary? > I founded: SOAPpy and Zolera SOAP Infrastructure (ZSI). Any tip which is > better to use? IFAICT, SOAPpy isn't maintained any longer, so on that basis I'd recommend ZSI. -- Cheers, Simon B simon at brunningonline.net From hg at nospam.org Mon Jan 8 02:40:07 2007 From: hg at nospam.org (hg) Date: Mon, 08 Jan 2007 08:40:07 +0100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> Message-ID: <%Isoh.22447$X97.12337@newsfe18.lga> sturlamolden wrote: > The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that > if an object's 'internal' variables or states cannot be kept private, > programmers get an irresistible temptation to mess with them in > malicious ways. But if you are that stupid, should you be programming > in any language? The most widely used language is still C, and there is > no concept of private data in C either, nor is it needed. void test(void) { static int i; } Do you agree that i is "private" to test ? hg From CedricCicada at gmail.com Fri Jan 19 14:12:05 2007 From: CedricCicada at gmail.com (CedricCicada at gmail.com) Date: 19 Jan 2007 11:12:05 -0800 Subject: My first try using logger didn't work. Why? In-Reply-To: <1169233154.076956.231540@q2g2000cwa.googlegroups.com> References: <1169221734.071338.107190@11g2000cwr.googlegroups.com> <1169224835.820468.316040@v45g2000cwv.googlegroups.com> <1169233154.076956.231540@q2g2000cwa.googlegroups.com> Message-ID: <1169233925.571841.75480@a75g2000cwd.googlegroups.com> Vinay (or anybody else), Well, now that logging is working, how do I stop it from working? I'm developing in PythonWin. When I run my test script, I get one message. When I run it a second time, I get two, a third time gets me three, and so on. I feel like the Sorceror's Apprentice! Rob From tim at tdw.net Wed Jan 24 10:24:40 2007 From: tim at tdw.net (Tim Williams) Date: Wed, 24 Jan 2007 15:24:40 +0000 Subject: smtplib starttls gmail example - comments? In-Reply-To: <G63739065.350.594.3@mxextra> References: <W63698683.410.134.1@mxextra> <9afea2ac0701240256kae247b3s666be6529362c84e@mail.gmail.com> <G63739065.350.594.3@mxextra> Message-ID: <9afea2ac0701240724v6416c530v2e97d7c7ccd701f3@mail.gmail.com> On 24/01/07, BJ Swope <bigblueswope at gmail.com> wrote: > > > > On 1/24/07, Tim Williams <tim at tdw.net> wrote: > > > > On 24/01/07, py <py at th.on> wrote: > > > I would love for anybody to comment on this code with regard to > redundancy/efficiency/wordiness or whatever else. > > > for instance, do i understand correctly that i cant have a try: else: > without an intervening except:? > > > -dave > > > > > > stdout.write("calling smtp server...") > > > try: > > > server = SMTP(msgsmtp) > > > except: > > > stdout.write("FAIL.") #using .write to avoid the implied > \n with print > > > else: > > > server.set_debuglevel(msgdebug) > > > stdout.write("starting tls...") > > > server.ehlo(msgfrom) > > > try: server.starttls () > > > except: stdout.write("FAIL.") > > > else: > > > server.ehlo(msgfrom) #neessary duplication (?) > > > stdout.write("logging in...") > > > try: server.login(msgfrom, msgpass) > > > except: stdout.write("FAIL.") > > > else: > > > stdout.write("sending...") > > > try: server.sendmail(msgfrom, msgto, msgtxt + > "\n.\n") > > > except: stdout.write("FAIL.") > > > else: > > > try: > > > server.quit() > > > except sslerror: # a known and largely > ignored issue with early EOF in ssl protocol > > > stdout.write("success.") > > > else: > > > stdout.write("success.") > > > -- > > > > > > *** Not tested but should have the same functionality and error > > handling as your script *** > > > > this_host = 'myhostname.mydom1.com' > > print "calling smtp server...", # the trailing comma removes '\n' > > try: > > server = > smtplib.SMTP(msgsmtp,local_hostname=this_host) > > server.set_debuglevel(msgdebug) > > print "starting tls...", > > server.starttls() > > server.ehlo(this_host) # RFC requirement for 2nd EHLO after > requesting TLS > > print "logging in...", > > server.login(msgfrom, msgpass) > > print "sending...", > > failed = server.sendmail(msgfrom, msgto, msgtxt + "\n.\n") > > try: > > server.quit() > > except: pass > > print "success." > > except: > > print "FAIL.", > > > > if failed: > > print "failed:", failed # some recipients, but not all of them, > failed > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > Both examples have included the cardinal sin in smtp... > > They both send the message text followed by new line dot new line. > > The smtp protocol specifically mentions CRLF dot CRLF. Please please > please use \r\n.\r\n in your code... > Ha, yeah I didn't spot that, but then I wasn't looking for it either :) However, Its not an issue with smtplib because its takes these kind of things into account by: * modifying line endings that aren't RFC compliant to CRLFs. * normalising/changing a single leading dot (.) to dot dot (..) * adding the CRLF dot CRLF to the end of the supplied message text. So adding adding "\n.\n" to the end of the msg text will just add a line containing ".." to the end of the message text, it won't terminate the DATA part. that line should therefore be just failed = server.sendmail(msgfrom, msgto, msgtxt) :) From jzgoda at o2.usun.pl Mon Jan 22 16:53:36 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 22 Jan 2007 22:53:36 +0100 Subject: Python Windows Editors In-Reply-To: <ea71a$45b5141c$d443bb3a$3908@news.speedlinq.nl> References: <p5Qsh.51413$wc5.6534@newssvr25.news.prodigy.net> <ep33ul$6cr$1@atlantis.news.tpi.pl> <ea71a$45b5141c$d443bb3a$3908@news.speedlinq.nl> Message-ID: <ep3bq3$k4e$1@atlantis.news.tpi.pl> Stef Mientki napisa?(a): > Any text editor is only as good as the >> programmer who uses it. ;) >> > Yes but an IDE is different ;-) Would it make me better Fortran programmer? ;) -- Jarek Zgoda http://jpa.berlios.de/ From __peter__ at web.de Fri Jan 26 15:17:14 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Jan 2007 21:17:14 +0100 Subject: Unicode error handler References: <mailman.3212.1169841312.32031.python-list@python.org> Message-ID: <epdnjh$8e1$03$1@news.t-online.com> Rares Vernica wrote: > Is there an encode/decode error handler that can replace all the > not-ascii letters from iso-8859-1 with their closest ascii letter? A mapping, not an error handler, but it might do the job: http://effbot.org/zone/unicode-convert.htm Peter From macdev at artins.org Fri Jan 5 04:16:31 2007 From: macdev at artins.org (Ben Artin) Date: Fri, 05 Jan 2007 04:16:31 -0500 Subject: checking one's type References: <mailman.2314.1167986448.32031.python-list@python.org> Message-ID: <macdev-30049E.04162805012007@reserved-multicast-range-not-delegated.example.com> In article <mailman.2314.1167986448.32031.python-list at python.org>, belinda thom <bthom at cs.hmc.edu> wrote: > I've been using the following hack to determine if a type is > acceptable and I suspect there is a better way to do it: > > e.g. > > if type(s) == type("") : > print "okay, i'm happy you're a string" > > If anyone knows a better way, I'm all ears. If you want to know whether something is specifically a string, but not a Unicode string, then you want isinstance(foo, str). If you want to check whether something is a general string (including Unicode strings), you want isinstance(foo, basestring). hth Ben -- If this message helped you, consider buying an item from my wish list: <http://artins.org/ben/wishlist> I changed my name: <http://periodic-kingdom.org/People/NameChange.php> From martin at v.loewis.de Wed Jan 10 01:42:22 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 10 Jan 2007 07:42:22 +0100 Subject: distutils and ctypes In-Reply-To: <mailman.2504.1168386142.32031.python-list@python.org> References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> <45A3FF17.2070509@v.loewis.de> <mailman.2497.1168377134.32031.python-list@python.org> <45a41b1f$0$19653$9b622d9e@news.freenet.de> <mailman.2504.1168386142.32031.python-list@python.org> Message-ID: <45A48ACE.9000404@v.loewis.de> Robert Kern schrieb: > To which I say that doing the type-checking and error handling is much easier in > Python than using the C API. Add to that the tediousness of the edit-compile-run > cycle of C and the finickiness of refcounting. Sure: edit-compile-run is tedious, but in the given case, it is necessary anyway. Also, refcounting is finicky, but with ctypes, you often have to use just as finicky memory management APIs. (such as using specific allocation and deallocation routines, or having to do memory management at all when in C you would do stack allocation). My main concern with ctypes is that you have to duplicate information from the header files, which is error-prone, especially when the header files may change (either across versions or across target systems). Regards, Martin From bussieremaillist at gmail.com Sun Jan 14 00:19:23 2007 From: bussieremaillist at gmail.com (bussiere maillist) Date: Sun, 14 Jan 2007 06:19:23 +0100 Subject: speech recognition linux and python Message-ID: <8a8f62c80701132119t74137a9ayd0a6ee2912f83ef9@mail.gmail.com> just for my hobby, i'am looking in a way to try voice recongnition on linux with python but with google i didn't find anything probant. By the way does someones can give me some tips or url to digg in this way particulary ? Is there anyway to use python for voice recognition on linux ? If yes with what ? Regards bussiere "speech recognition linux and python" From stargaming at gmail.com Wed Jan 31 13:08:26 2007 From: stargaming at gmail.com (Stargaming) Date: Wed, 31 Jan 2007 19:08:26 +0100 Subject: where has Stani's Py Editor gone? In-Reply-To: <774wh.208375$MO2.74678@fe3.news.blueyonder.co.uk> References: <774wh.208375$MO2.74678@fe3.news.blueyonder.co.uk> Message-ID: <epqlut$1s5r$1@ulysses.news.tiscali.de> John Pote schrieb: > Hi everyone, > > Been trying to get the latest version of Stani's Python Editor the last few > days. But I cannot get any response out of 'pythonide.stani.be'. Anyone know > what's happened? > > Ta much, > > John Pote > > http://developer.berlios.de/project/showfiles.php?group_id=4161 From "trades\" at (none) Mon Jan 29 18:17:11 2007 From: "trades\" at (none) (none) Date: Mon, 29 Jan 2007 17:17:11 -0600 Subject: deepcopy alternative? Message-ID: <45be808e$0$27074$4c368faf@roadrunner.com> I have a very complex data structure which is basically a class object containing (sometimes many) other class objects, function references, ints, floats, etc. The man for the copy module states pretty clearly that it will not copy methods or functions. I've looked around for a while (prob just using the wrong keywords) and haven't found a good solution. As a workaround I've been using cPickle, loads(dumps(obj)) which is incredibly slow (~8 sec for a 1000 elem list). I believe the only thing stopping me from doing a deepcopy is the function references, but I'm not sure. If so is there any way to transform a string into a function reference(w/o eval or exec)? Example from copy import deepcopy a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj[funcRef]) b = deepcopy(a) TypeError: function() takes at least 2 arguments (0 given) All I want is a deepcopy of the list. Any suggestions would be appreciated. Jack Trades PS: If the answer to this is in __getstate__() or __setstate__() is there some reference to how these should be implemented besides the library reference? From heikki at osafoundation.org Wed Jan 10 17:57:44 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 10 Jan 2007 14:57:44 -0800 Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error In-Reply-To: <YK%oh.17173$sR.6972@newssvr29.news.prodigy.net> References: <YK%oh.17173$sR.6972@newssvr29.news.prodigy.net> Message-ID: <ovWdnZTGuYL38jjYnZ2dnUVZ_rqdnZ2d@comcast.com> John Nagle wrote: > I have a little test case for M2Crypto, which just opens up SSL > connections to > web servers and reads their certificates. This works fine. > > But if I execute > > socket.setdefaulttimeout(5.0) Yup, this is a known problem, this breaks all M2Crypto code that uses sockets. The Twisted wrapper part still works, as it hands the network activity to Twisted. If you can make do without setdefaulttimeout you should be fine. This is bug https://bugzilla.osafoundation.org/show_bug.cgi?id=2341 The bug has a patch that works on Linux, but it would need Windows and Mac specific parts before it can be checked in. -- Heikki Toivonen From martin at v.loewis.de Mon Jan 29 16:11:51 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 29 Jan 2007 22:11:51 +0100 Subject: Convert from unicode chars to HTML entities In-Reply-To: <pan.2007.01.29.05.13.04.686937@REMOVEME.cybersource.com.au> References: <pan.2007.01.29.03.05.23.166735@REMOVEME.cybersource.com.au> <45bd7a82$0$17928$4d3efbfe@news.sover.net> <pan.2007.01.29.05.13.04.686937@REMOVEME.cybersource.com.au> Message-ID: <45BE6317.4040506@v.loewis.de> Steven D'Aprano schrieb: > A few issues: > > (1) It doesn't seem to be reversible: > >>>> '© and many more...'.decode('latin-1') > u'© and many more...' > > What should I do instead? For reverse processing, you need to parse it with an SGML/XML parser. > (2) Are XML entities guaranteed to be the same as HTML entities? Please make a terminology difference between "entity", "entity reference", and "character reference". An (external parsed) entity is a named piece of text, such as the copyright character. An entity reference is a reference to such a thing, e.g. © A character reference is a reference to a character, not to an entity. xmlcharrefreplace generates character references, not entity references (let alone generating entities). The character references in XML and HTML both reference by Unicode ordinal, so it is "the same". > (3) Is there a way to find out at runtime what encoders/decoders/error > handlers are available, and what they do? Not through Python code. In C code, you can look at the codec_error_registry field of the interpreter object. Regards, Martin From gagsl-py at yahoo.com.ar Tue Jan 2 21:57:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Jan 2007 23:57:13 -0300 Subject: Iterate through list two items at a time In-Reply-To: <enf2he$2sr1@cnn.xsj.xilinx.com> References: <enf2he$2sr1@cnn.xsj.xilinx.com> Message-ID: <7.0.1.0.0.20070102234931.04a2d658@yahoo.com.ar> At Tuesday 2/1/2007 22:57, Dave Dean wrote: > myList = [1,2,3,4,5,6] > >I'd like to be able to pull out two items at a time - simple examples would >be: >Create this output: >1 2 >3 4 >5 6 b=iter(a) for x in b: y=b.next() print x,y b=iter(a) for x,y in ((item, b.next()) for item in b): print x,y >Create this list: >[(1,2), (3,4), (5,6)] b=iter(a) [(item, b.next()) for item in b] Note that they don't behave the same at the corner cases (empty list, single item, odd length...) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From horpner at yahoo.com Mon Jan 8 10:03:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 8 Jan 2007 16:03:53 +0100 Subject: recursive function References: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> Message-ID: <slrneq4ne7.k8.horpner@FIAD06.norwich.edu> On 2007-01-08, cesco <fd.calabrese at gmail.com> wrote: > Hi, > > I have a dictionary of lists of tuples like in the following example: > dict = {1: [(3, 4), (5, 8)], > 2: [(5, 4), (21, 3), (19, 2)], > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]] > > In this case I have three lists inside the dict but this number > is known only at runtime. I have to write a function that > considers all the possible combinations of tuples belonging to > the different lists and return a list of tuples of tuples for > which the sum of the first element of the most inner tuple is > equal to N. > > For example, assuming N = 24, in this case it should return: > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19, > 2), (0, 2))] What do you mean by "most inner tuple"? > A simple list comprehension would be enough if only I knew the > number of keys/lists beforehand len(dict.keys()). -- Neil Cerutti Next Sunday Mrs. Vinson will be soloist for the morning service. The pastor will then speak on "It's a Terrible Experience." --Church Bulletin Blooper From jhefferon at smcvt.edu Tue Jan 30 08:29:22 2007 From: jhefferon at smcvt.edu (Jim) Date: 30 Jan 2007 05:29:22 -0800 Subject: error messages containing unicode In-Reply-To: <epngj2$sv9$03$1@news.t-online.com> References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> <pan.2007.01.30.02.48.10.853852@REMOVEME.cybersource.com.au> <1170160464.576122.62230@h3g2000cwc.googlegroups.com> <528sn0F1nhkoiU1@mid.uni-berlin.de> <1170162459.577853.282090@l53g2000cwa.googlegroups.com> <epngj2$sv9$03$1@news.t-online.com> Message-ID: <1170163762.145431.133400@j27g2000cwj.googlegroups.com> On Jan 30, 8:18 am, Peter Otten <__pete... at web.de> wrote: > >>> try:... raise Exception(u"gew?hnlich ?hnlich ?blich") > ... except Exception, e: > ... print e.message > ... > gew?hnlich ?hnlich ?blich Ah, so that's what "If there is a single argument (as is preferred), it is bound to the message attribute" means. Through some imbecility I failed to understand it. Thank you. > If you're writing to a file you still have to encode explicitly. Yes; I know that. It wasn't what to do with the unicode object that confused me, it was how to get it in the first place. Much obliged, Jim From macdev at artins.org Sun Jan 7 06:31:08 2007 From: macdev at artins.org (Ben Artin) Date: Sun, 07 Jan 2007 06:31:08 -0500 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <macdev-1AECB4.06310807012007@reserved-multicast-range-not-delegated.example.com> In article <1168128425.058049.221320 at v33g2000cwv.googlegroups.com>, "time.swift at gmail.com" <time.swift at gmail.com> wrote: > Coming from a C++ / C# background, the lack of emphasis on private data > seems weird to me. I've often found wrapping private data useful to > prevent bugs and enforce error checking.. > > It appears to me (perhaps wrongly) that Python prefers to leave class > data public. What is the logic behind that choice? > > Thanks any insight. One thing that the other posters didn't mention is that if you access data members of a class in C++ you end up with a very tight coupling with that class. If the class later changes so that the data is no longer part of the public interface, then every user of the class has to change the code and recompile. In Python, on the other hand, if I have a piece of public data that I later decide to replace with an accessor method, I can do that without changing any of the code that uses the class. So, insistence on private data in C++ is a good thing because it reduces the level of coupling between a class and its clients. In Python, this is not an issue, because the same loose coupling can be obtained with data as well as accessor methods, and therefore public data is used when possible and private data when necessary. hth Ben -- If this message helped you, consider buying an item from my wish list: <http://artins.org/ben/wishlist> I changed my name: <http://periodic-kingdom.org/People/NameChange.php> From AleydisGP at gmail.com Sun Jan 7 16:35:27 2007 From: AleydisGP at gmail.com (AleydisGP at gmail.com) Date: 7 Jan 2007 13:35:27 -0800 Subject: Working with Excel inside Python Message-ID: <1168205727.130771.257030@51g2000cwl.googlegroups.com> I have a .plt file (which is a tab delimited ASCII file) and I want to format it to get a .dbf with data in rows and columns, detele some rows/columns and substitute decimal '.' with ','. All this using Python (I'm using Pythonwin). The .plt file looks like this: * ISCST3 (02035): Tersa * MODELING OPTIONS USED: * CONC URBAN ELEV DFAULT * PLOT FILE OF ANNUAL VALUES FOR SOURCE GROUP: ALL * FOR A TOTAL OF 400 RECEPTORS. * FORMAT: (3(1X,F13.5),1X,F8.2,2X,A6,2X,A8,2X,I8.8,2X,A8) * X Y AVERAGE CONC ZELEV * ___________ ___________ ___________ ______ 430342.00000 4580537.00000 0.25426 19.28 430842.00000 4580537.00000 0.27233 14.72 431342.00000 4580537.00000 0.30566 2.84 431842.00000 4580537.00000 0.30379 0.21 432342.00000 4580537.00000 0.27413 1.13 432842.00000 4580537.00000 0.25462 0.00 433342.00000 4580537.00000 0.25114 0.00 433842.00000 4580537.00000 0.28779 0.00 434342.00000 4580537.00000 0.29707 0.00 434842.00000 4580537.00000 0.31067 0.00 .... I recorded a macro in Excel with the whole process, but when trying to translate it into Python I get syntax errors which I don't know how to solve. This is my python code: ## ------------------------------------------ import win32com.client excel = win32com.client.Dispatch("Excel.Application") excel.Visible = 0 workbook=excel.Workbooks.Open('D:\AN00GALL.plt') excel.Columns("A:A").Select excel.Selection.Replace What:=".", Replacement:=",", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False excel.Columns("A:A").Select excel.Selection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 1), Array(2, 1), Array(14, 1), Array(29, 1), Array(42, 1), _ Array(53, 1), Array(59, 1), Array(71, 1), Array(79, 1)), ThousandsSeparator:=" ", _ TrailingMinusNumbers:=True excel.Selection.Delete Shift:=xlToLeft excel.Rows("1:6").Select excel.Selection.Delete Shift:=xlUp excel.Rows("2:2").Select excel.Selection.Delete Shift:=xlUp excel.Columns("A:C").Select excel.Selection.NumberFormat = "0.00000" excel.Columns("D:D").Select excel.Selection.NumberFormat = "0.00" excel.ActiveWorkbook.SaveAs Filename:= _ "D:\AN00GALL.dbf", FileFormat:= _ xlDBF4, CreateBackup:=False excel.Quit() ## ------------------------------------------ Any ideas on what am I doing wrong? Thank you. From dieterv at optionexplicit.be Fri Jan 26 03:25:04 2007 From: dieterv at optionexplicit.be (Dieter Verfaillie) Date: Fri, 26 Jan 2007 09:25:04 +0100 Subject: Module for SVG? In-Reply-To: <9e2f512b0701251058k97ead4h89ccf1f4a40f269a@mail.gmail.com> References: <9e2f512b0701251058k97ead4h89ccf1f4a40f269a@mail.gmail.com> Message-ID: <1169799904.5334.12.camel@PO001> On Thu, 2007-01-25 at 15:58 -0300, Sebastian Bassi wrote: > Hello, > > I found http://www2.sfk.nl/svg as a Python module for writing SVG. > Last update was in 2004 and I am not sure if there is something > better. > Any recommendation for generating SVG graphics? > Best, > SB. Cairo ( http://cairographics.org/pycairo ), using cairo.SVGSurface(). As a bonus, if you'd ever need it, you can switch to a different Surface (for example ps or pdf) and use the same drawing code with it. There's a good tutorial on http://www.tortall.net/mu/wiki/CairoTutorial hth, Dieter From tim.tadh at gmail.com Mon Jan 1 21:36:10 2007 From: tim.tadh at gmail.com (Tim Henderson) Date: 1 Jan 2007 18:36:10 -0800 Subject: OO question In-Reply-To: <1167700159.792649.61210@a3g2000cwd.googlegroups.com> References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> <1167639280.181587.242490@s34g2000cwa.googlegroups.com> <1167700159.792649.61210@a3g2000cwd.googlegroups.com> Message-ID: <1167705370.185259.126380@v33g2000cwv.googlegroups.com> On Jan 1, 8:09 pm, fejkadr... at hushmail.com wrote: > Lets say I have those two classes, Person and Address. How would one > implement the relationship between them? First, a Person can have one > or more addresses (or none), that could be represented as a list of > Addresses, right? But then, if I have an Address I want to see which > persons who live there, then I would have a list of Persons in each > Address. > > Is this doubly-linked way of doing it a good way of doing it, or is > there > a better "OO way" I haven't learned yet? Since you are making an address book and not a person book I would start out by making a simple list of addresses. Each address could have a "person" or a "name" field. You could then sort your list by the name of each person associated with each address. If an address has no person associated with it then you put it at the beginning (or end if you want) of the list. I think this would most closely mimic how a rolodex works. It doesn't really matter if you implement it as a list of dictionaries or a list classes I believe they would be equivalent in this case. tim From wleftwich at gmail.com Wed Jan 3 22:43:32 2007 From: wleftwich at gmail.com (Wade Leftwich) Date: 3 Jan 2007 19:43:32 -0800 Subject: Iterate through list two items at a time References: <enf2he$2sr1@cnn.xsj.xilinx.com> <12pmahqc7kclbfc@corp.supernews.com> Message-ID: <1167882211.696350.271620@s34g2000cwa.googlegroups.com> Jeffrey Froman wrote: > Dave Dean wrote: > > > I'm looking for a way to iterate through a list, two (or more) items at a > > time. > > Here's a solution, from the iterools documentation. It may not be the /most/ > beautiful, but it is short, and scales well for larger groupings: > > >>> from itertools import izip > >>> def groupn(iterable, n): > ... return izip(* [iter(iterable)] * n) > ... > >>> list(groupn(myList, 2)) > [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] > >>> list(groupn(myList, 3)) > [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)] > >>> list(groupn(myList, 4)) > [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)] > >>> for a,b in groupn(myList, 2): > ... print a, b > ... > 0 1 > 2 3 > 4 5 > 6 7 > 8 9 > 10 11 > >>> > > Jeffrey This works great except you lose any 'remainder' from myList: >>> list(groupn(range(10),3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] # did not include (9,) The following might be more complex than necessary but it solves the problem, and like groupn() it works on infinite lists. from itertools import groupby, imap def chunk(it, n=0): if n == 0: return iter([it]) grouped = groupby(enumerate(it), lambda x: int(x[0]/n)) counted = imap(lambda x:x[1], grouped) return imap(lambda x: imap(lambda y: y[1], x), counted) >>> [list(x) for x in chunk(range(10), 3)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] Note the chunks are iterators, not tuples as in groupn(): >>> [x for x in chunk(range(10), 3)] [<itertools.imap object at 0xb78d4c4c>, <itertools.imap object at 0xb78d806c>, <itertools.imap object at 0xb78d808c>, <itertools.imap object at 0xb78d4c6c>] -- Wade Leftwich Ithaca, NY From http Sat Jan 20 00:43:45 2007 From: http (Paul Rubin) Date: 19 Jan 2007 21:43:45 -0800 Subject: OT Annoying Habits (Was: when format strings attack) References: <mailman.2917.1169243036.32031.python-list@python.org> Message-ID: <7xirf2w8vi.fsf@ruckus.brouhaha.com> "Carroll, Barry" <Barry.Carroll at psc.com> writes: > When I was last a regular Usenet citizen the Internet was new, GUI > interfaces were experimental and the World Wide Web didn't exist yet. > Newsreader software was text-based. Top-posting was the common > practice, because it was the most convenient. No. Top posting has always been an aberrance. It first appeared in Usenet when Usenet (a word whose etymology comes from "Unix" and "network") started attracting Microsoft Windows users, who were in the habit of using Windows products that top-posted. That happened fairly far along in Usenet's evolution, since Usenet got started in the late 1970's when there was no such thing as Microsoft. Usenet itself inherited some of its conventions from Arpanet culture, which got started in the 1960's. > you didn't have to page through an arbitrarily large number of > messages, most of which you'd already read umpteen times, to get to > the new stuff you were interested in. Proper Usenet convention has always been to trim out the previous stuff except what you were directly replying to, and to intersperse that stuff, like this message. The practice of splatting in umpteen layers of unedited past messages (whether at the top or bottom) is another abomination popularized by those same Windows products. From rridge at csclub.uwaterloo.ca Fri Jan 19 15:48:14 2007 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 19 Jan 2007 12:48:14 -0800 Subject: Determining when a file is an Open Office Document References: <eop5ci$et5$1@solaris.cc.vt.edu> <1169171820.851021.49200@l53g2000cwa.googlegroups.com> <eopicc$95t$1@solaris.cc.vt.edu> Message-ID: <1169239691.159739.304050@l53g2000cwa.googlegroups.com> tubby wrote: > Now, If only I could something like that on PDF files :) PDF files should begin with "%PDF-" followed by a version number, eg. "%PDF-1.4". The PDF Reference notes that Adobe Acrobat Reader is a bit more flexiable about what it will accept: 13. Acrobat viewers require only that the header appear somewhere within the first 1024 bytes of the file. 14. Acrobat viewers also accept a header of the form %!PS-Adobe-N.n PDF-M.m So identifying PDF files is pretty easy. If you want to examine the contents of a PDF file you're better off using Postscript, Ghostscript specifically, since PDF is essentially Postscript with a special dictionary of commands. Ross Ridge From S.Mientki-nospam at mailbox.kun.nl Sat Jan 6 17:56:43 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 06 Jan 2007 23:56:43 +0100 Subject: still struggling, howto use a list-element as a name ? Sory, hit send button to early In-Reply-To: <441e$45a02246$d443bb3a$24795@news.speedlinq.nl> References: <b7908$459fef43$d443bb3a$26766@news.speedlinq.nl> <45a01981$0$296$426a74cc@news.free.fr> <I_Unh.390$_B1.309@read3.inet.fi> <441e$45a02246$d443bb3a$24795@news.speedlinq.nl> Message-ID: <bcf0b$45a0291e$d443bb3a$4323@news.speedlinq.nl> Stef Mientki wrote: > Jussi Salmela wrote: >> Bruno Desthuilliers kirjoitti: >>> Stef Mientki a ?crit : >>>> In the example below, "pin" is an object with a number of properties. >>>> Now I want >>>> 1- an easy way to create objects that contains a number of these "pin" >>>> 2- an multiple way to access these "pin", i.e. >>>> device.pin[some_index] >>>> device.some_logical_name >>>> ad 1: >>>> a dictionary (as "pinlist" in the example) seems a very >>>> convenient way (from a viewpoint of the device creator). >>>> As you can see in the "__init__" section this dictionary can easily >>>> be transported to the pin-objects. >>>> >>>> ad 2: >>>> THAT's the problem: how do automate these lines "self.GND = >>>> self.pin[0]" >>>> >>>> I'm also in for other solutions. >>> >>> I'm afraid I don't understand your design (nor the domain FWIW). >> ditto >>> <snip> >>> >>> But the whole thing still looks awfully convulted and kludgy to me, >>> and I suspect serious design flaws... Why don't you try and explain >>> your real problem, instead of asking how to implement what you >>> *think* is the solution ? >> ditto > > thank you all guys. > I'm just doing some exercises in Python, > and therefor I'm trying to rewrite some programs > I've written in other languages into Python. > > The first program I tried to convert was a MatLab program, > which could almost be written identical in Python. > Even with my little experience in Python, > I can tell you that it could have been written in Python > in a much better way, but I deliberately did not, > to show other people who are familiar with MatLab. > > The second example I'm now exercising with, > is a simulator of (electrical) circuits, > which I build in Delphi > http://oase.uci.kun.nl/~mientki/data_www/pic/jalss/jalss.html > > > Sorry, pressed send button too soon, so here it continuous: In this exercise, I don't attempt to write "beautiful" Python code, but the first thing is to write a simple "user-interface" for non-Pythians. I understand that standardization about naming conventions is important, but the purpose here is to serve the user, who has to write and unerstand this, therefore IORLW is in the domain always written in capitals, spaces here makes it lot easier to compare the different actions, in this domain we're used to 2 spaces etc. def IORLW(S): S.Accu_ZERO ( S.Accu | S.lit [S.PC] ) def ANDLW(S): S.Accu_ZERO ( S.Accu & S.lit [S.PC] ) def XORLW(S): S.Accu_ZERO ( S.Accu ^ S.lit [S.PC] ) def SUBLW(S): S.AddLW (~S.Accu + 1 ) def ADDLW(S): S.AddLW ( S,Accu ) So to come back to my last question: this is what the user has to do: define devices with pins, and the actions what todo when input signals changes. class LED (device): pinlist ={ # pin name type init-value other-parameters 1: ('Cathode', _DIG_IN, [], _par2), 2: ('Anode', _DIG_OUT, [], _par33) } Status = {True:('On'), False:('Off')} def execute (self): old = self.On self.On = (~self.Cathode.Value & self.Anode.Value) > 0 if self.On <> old : print self.Name, self.Status[self.On] And now this looks quit familiar, although I miss the "with" statement of Delphi to make it even more readable ;-) like this class LED (device): pinlist ={ # pin name type init-value other-parameters 1: ('Cathode', _DIG_IN, [], _par2), 2: ('Anode', _DIG_OUT, [], _par33) } Status = {True:('On'), False:('Off')} def execute (self): with self: old = On On = ( ~Cathode.Value & Anode.Value) > 0 if On <> old : print Name, Status[On] thanks again for all your wonderfull help, cheers, Stef Mientki From deets at nospam.web.de Tue Jan 16 05:46:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 16 Jan 2007 11:46:55 +0100 Subject: html + javascript automations = [mechanize + ?? ] or something else? References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> <m3lkk3dznr.fsf@netmaster.kds.com.ua> Message-ID: <513oovF1ib4g4U1@mid.uni-berlin.de> > Up to my knowledge, there no way to test javascript but to fire up a > browser. > > So, you might check Selenium (http://www.openqa.org/selenium/) and its > python module. No use in that, as to be remote-controlled by python, selenium must be run on the server-site itself, due to JS security model restrictions. Diez From weekender_ny at yahoo.com Mon Jan 15 23:12:35 2007 From: weekender_ny at yahoo.com (John) Date: 15 Jan 2007 20:12:35 -0800 Subject: html + javascript automations = [mechanize + ?? ] or something else? Message-ID: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> I have to write a spyder for a webpage that uses html + javascript. I had it written using mechanize but the authors of the webpage now use a lot of javascript. Mechanize can no longer do the job. Does anyone know how I could automate my spyder to understand javascript? Is there a way to control a browser like firefox from python itself? How about IE? That way, we do not have to go thru something like mechanize? Thanks in advance for your help/comments, --j From NikitaTheSpider at gmail.com Wed Jan 24 11:55:35 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Wed, 24 Jan 2007 11:55:35 -0500 Subject: Regex for URL extracting References: <1169655624.981833.29730@j27g2000cwj.googlegroups.com> Message-ID: <NikitaTheSpider-0B72FC.11553524012007@news-server.nc.rr.com> In article <1169655624.981833.29730 at j27g2000cwj.googlegroups.com>, "Johny" <python at hope.cz> wrote: > Does anyone know about a good regular expression for URL extracting? Extracting URLs from what? If it is HTML, then I'd look at some existing HTML parsing modules like Beautiful Soup and Barnes' HTMLData. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From hg at nospam.org Thu Jan 18 11:44:44 2007 From: hg at nospam.org (hg) Date: Thu, 18 Jan 2007 17:44:44 +0100 Subject: what can be used in a signal handler References: <3zKrh.30692$sE7.26486@newsfe21.lga> <eontet$dbu$1@gemini.csx.cam.ac.uk> Message-ID: <FDTrh.21215$cv2.14581@newsfe13.lga> Nick Maclaren wrote: > > In article <3zKrh.30692$sE7.26486 at newsfe21.lga>, > hg <hg at nospam.org> writes: > |> > |> I posted an equivalent question earlier ... but am still not sure: > |> > |> I currently (under Linux) have a program that uses Queue.put > |> (raw_input('')) in a signal handler and Queue.get() in the main/only > |> thread. > |> > |> It works but I want to know if it is legal / what type of synchro API I > |> have the right to use in a signal handler. > > Strictly, no and none. > > C and POSIX's specifications of signal handling is a complete mess. > ALL handling of ALL real signals is undefined behaviour, though few > programmers realise that and POSIX depends on it. As that would make > all Unices (and Microsoft systems) unusable, you can reasonably assume > that there is some signal handling that will work. > > But what? Which is where you came in. > > The situation is that most things that seem to work do actually work, > in some environments and under some circumstances. You can never be > sure when they will stop working, however, and all bets are off when > you port signal handling code to a new system. And, really but REALLY, > do not mix it with very high levels of optimisation or rely on it > being in any way thread safe. > > I can't tell you whether the code of Queue is intended to work if an > active Queue.get is interrupted by a signal which then does a Queue.put, > but that is the sort of circumstance where things get very hairy. Even > if Python has code to enable that case, it won't be 100% reliable on all > systems. > > Sorry. But that is the situation :-( > > > Regards, > Nick Maclaren. Fair, I'll find a way around then. Regards, hg From deets at nospam.web.de Thu Jan 11 18:20:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Jan 2007 00:20:24 +0100 Subject: Python nuube needs Unicode help In-Reply-To: <1168550858.233814.292900@p59g2000hsd.googlegroups.com> References: <1168550858.233814.292900@p59g2000hsd.googlegroups.com> Message-ID: <50nv1uF1hje7oU1@mid.uni-berlin.de> gheissenberger at gmail.com schrieb: > HELP! > Guy who was here before me wrote a script to parse files in Python. > > Includes line: > print u > where u is a line from a file we are parsing. > However, we have started recieving data from Brazil. If I open file to > parse in VI, looks like: > > <Utt id="3" transcribe="yes" audioRoot="A1" > audio="313-20070102144528.wav" grammarSet="G3" rawText="não" > recValue="{data:CHOICE=NO;}" conf="970" rawText2="" conf2="0" > transcribedText="não" parsableText="não"/ > > Clearly those "nã" are some non-Ascii characters, but how do I get > print to understand that? > > I keep getting: > "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in > position 40: > ordinal not in range(128)" > Does the error happen at the print u line? If yes, what happens is that you try and print a unicode object. Which means that it has to be converted (actually the right term is encoded) to a byte-string. If you don't do that explicitely, it will be done implicitly, using the default encoding - which is ascii. If you have non-ascii characters, you end up with the error you see. What to do? Use something like this: print u.encode('utf-8') instead. Diez From garyjefferson123 at yahoo.com Tue Jan 23 00:49:01 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 22 Jan 2007 21:49:01 -0800 Subject: selective logger disable/enable In-Reply-To: <1169442596.209314.162410@s34g2000cwa.googlegroups.com> References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> <1169349399.938121.238430@38g2000cwa.googlegroups.com> <1169395276.181654.160810@a75g2000cwd.googlegroups.com> <1169437763.213781.163660@38g2000cwa.googlegroups.com> <1169442596.209314.162410@s34g2000cwa.googlegroups.com> Message-ID: <1169531341.221067.205500@11g2000cwr.googlegroups.com> Vinay Sajip wrote: > > BTW I would also advise reading PEP-282 to understand more about the > logging approach. You've been most helpful, Vinay. The PEP section on Filters states that I can do what I've been trying to do with filters, but doesn't provide enough information to do it (or, at least, I'm too thick to guess at how it would work by looking at the API and PEP and trying a dozen different ways). Luckily, the examples you point to from your original package do provide enough info; log_test15.py held the key. I still feel like it would be more intuitive if filters were inherited down the hierarchy instead of having to go through the extra steps of getting at the root handler first, but I'm sure there are good reasons for not doing this. One more question, is there any way to get the list of all named loggers (from the Manager, perhaps)? Or... maybe I don't need this, either, as MatchFilter (log_test18.py) seems to do what I was thinking I need the list of logger names for... most excellent. Thanks, Gary BTW, the python logging module is one of the best readily available loggers I've come across in any language. From michael at mustun.ch Sat Jan 6 09:43:05 2007 From: michael at mustun.ch (Michael M.) Date: Sat, 06 Jan 2007 15:43:05 +0100 Subject: Python re expr from Perl to Python Message-ID: <GzOnh.112$a81.91@nntpserver.swip.net> In Perl, it was: ## Example: "Abc | def | ghi | jkl" ## -> "Abc ghi jkl" ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st pipe). $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; ## -- remove [ and ] in text $na =~ s/\[//g; $na =~ s/\]//g; # print "DEB: \"$na\"\n"; # input string na="Abc | def | ghi | jkl [gugu]" # output na="Abc ghi jkl gugu" How is it done in Python? From maxerickson at gmail.com Tue Jan 16 13:03:53 2007 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 16 Jan 2007 18:03:53 +0000 (UTC) Subject: urllib2 and HTTPBasicAuthHandler References: <45acf775$0$5070$ba4acef3@news.orange.fr> Message-ID: <Xns98BA84E5AE44Fmaxericksongmailcom@80.91.229.5> "m.banaouas" <banaouas.medialog at wanadoo.fr> wrote: > Hi all, > I started to use urllib2 library and HTTPBasicAuthHandler class > in order to authenticate with a http server (Zope in this case). > I don't know why but it doesn't work, while authenticating with > direct headers manipulation works fine! > ... > port':'8080','path':'manage','realm':'Zope'} > url = '%(prot)s://%(host)s:%(port)s/%(path)s' % data ... Are you certain that the realm on the server matches 'Zope'? HTTPBasicAuthHandler uses the realm to look for the password, if the realm the server provides is different, urllib2 will respond as if it does not have a user/password. If you are only doing one request, it isn't that big a deal; if you are doing many requests or want urllib2 to handle the response for other reseans, you can use a default realm, see the bottom of this example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305288 (The advantage of using a default rather than making sure the realm is correct is that it can change and you won't have to do anything) max From anthony.cutrone at gmail.com Mon Jan 29 03:31:49 2007 From: anthony.cutrone at gmail.com (anthony.cutrone at gmail.com) Date: 29 Jan 2007 00:31:49 -0800 Subject: Web File System Message-ID: <1170059509.601069.153290@q2g2000cwa.googlegroups.com> Hi group, I have a development with a file system in Python, accessible from a graphic web application. I mustn't use an NTFS or EXT3 system, because those are not adapted for my use. Indeed, I would like my system to be able to recover files, and get precedent versions. I also want it to index words contained in files, to search with these. Files and folders have to be in an SQL database, mounted in ext3-like system. File would be identified by a single ID, and links with names should be connected on these IDs. Somebody have already worked (in Python) about this kind of things ? is there a publicly available framework or toolkit ? thanks From gagsl-py at yahoo.com.ar Sun Jan 21 09:40:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Jan 2007 11:40:57 -0300 Subject: A solution to the MSVCRT vs MSVCR71 problem? In-Reply-To: <45B3267A.80605@v.loewis.de> References: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> <mailman.2958.1169368253.32031.python-list@python.org> <45B3267A.80605@v.loewis.de> Message-ID: <7.0.1.0.0.20070121113404.036150c8@yahoo.com.ar> At Sunday 21/1/2007 05:38, Martin v. L?wis wrote: >Gabriel Genellina schrieb: > > This would only work, if runtime dll's were compatibles between them, > > and they are not. You can't blindly redirect a call to msvcr71.__xyz to > > msvcr80.__xyz and expect that to work magically - it may have a > > different number of arguments, or different types, or even may not exist > > anymore. > >Actually, the libraries *are* binary-compatible (on the ABI level). You >just can't mix two libraries in a single program easily. That's a good thing - but is this just by accident, or is documented somewhere? I remember that I tried something like that in the past, and failed. (Perhaps earlier versions where not fully backwards compatible - or I didn't try hard enough that time). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bill.scherer at verizonwireless.com Fri Jan 5 15:33:03 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Fri, 05 Jan 2007 15:33:03 -0500 Subject: Learning to program in Python In-Reply-To: <NYOBGCEXSMTP20HNkjg0000841d@nyobgcexsmtp20.uswin.ad.vzwcorp.com> References: <NYOBGCEXSMTP20HNkjg0000841d@nyobgcexsmtp20.uswin.ad.vzwcorp.com> Message-ID: <459EB5FF.80801@verizonwireless.com> jbchua wrote: >Hello everybody. > >I am an Electrical Engineering major and have dabbled in several >languages such as Python, C, and Java in my spare time because of my >interest in programming. However, I have not done any practical >programming because I have no idea where to get started. I taught >myself these languages basically by e-tutorials and books. This makes >me feel as if I don't really know how to implement these languages. >Does anybody have any advice on where to start applying my limited >knowledge practically in order to advance my learning? > > > Given your major, I think you'll find Unum very handy: http://home.tiscali.be/be052320/Unum.html It allows one to work with familiar terms naturally: >>> 1 / ( (2*pi) * (1*Mega*OHM) * (.1*Micro*F) ) 1.59154943092 [1/s] >>> (note that Unum doesn't provide the metric prefixes in this example, but thats easy enough to code oneself) They have tutorial which you may find useful. HTH, Bill From hg at nospam.org Wed Jan 10 02:35:29 2007 From: hg at nospam.org (hg) Date: Wed, 10 Jan 2007 08:35:29 +0100 Subject: maximum number of threads References: <mailman.2531.1168438769.32031.python-list@python.org> Message-ID: <DQ6ph.113451$gl2.72305@newsfe16.lga> Jean-Paul Calderone wrote: > On Wed, 10 Jan 2007 12:11:59 -0200, Felipe Almeida Lessa > <felipe.lessa at gmail.com> wrote: >>On 1/10/07, Laurent Pointal <laurent.pointal at limsi.fr> wrote: >>>This is a system configurable limit (up to a maximum). >>> >>>See ulimit man pages. >>> >>>test >>> >>> ulimit -a >>> >>>to see what are the current limits, and try with >>> >>> ulimit -u 2000 >>> >>>to modify the maximum number of user process (AFAIK each thread use a >>>process entry on Linux) >> >>I don't think it's only this. > > Indeed you are correct. The actual limit you are hitting is the size > of your address space. Each thread is allocated 8MB of stack. 382 > threads consumes about 3GB of address space. Even though most of this > memory isn't actually allocated, the address space is still used up. So, > when you try to create the 383rd thread, the kernel can't find anyplace > to put its stack. So you can't create it. > > Try reducing your stack size or reducing the number of threads you create. > There's really actually almost no good reason to have this many threads, > even though it's possible. > > exarkun at charm:~$ python Desktop/test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > Exception raised: can't start new thread > > Biggest number of threads: 382 > exarkun at charm:~$ ulimit -Ss 4096 > exarkun at charm:~$ python Desktop/test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > 400 > 450 > 500 > 550 > 600 > 650 > 700 > 750 > Exception raised: can't start new thread > > Biggest number of threads: 764 > exarkun at charm:~$ > > Jean-Paul Would increasing the swap size do it also then ? hg From michael at mustun.ch Thu Jan 4 11:12:34 2007 From: michael at mustun.ch (Michael M.) Date: Thu, 04 Jan 2007 17:12:34 +0100 Subject: code optimization (calc PI) / New Algorithme for PI In-Reply-To: <1167926262.512546.209130@s80g2000cwa.googlegroups.com> References: <hOPmh.82$9v1.124@nntpserver.swip.net> <slrneppql6.3v8.nick@irishsea.home.craig-wood.com> <We9nh.196$Je6.90@nntpserver.swip.net> <1167926262.512546.209130@s80g2000cwa.googlegroups.com> Message-ID: <DH9nh.200$Je6.136@nntpserver.swip.net> casevh at comcast.net wrote: >>Yes, this "gmpy" sounds good for calc things like that. >>But not available on my machine. >>ImportError: No module named gmpy > > > What type of machine? Windoof with Cygwin. > > The home page for gmpy is http://sourceforge.net/projects/gmpy/ > > I have Windows versions available at http://home.comcast.net/~casevh/ > > casevh > If the binary works, I don't know. Maybe there is also a gmpy module already in Cygwin. From gagsl-py at yahoo.com.ar Thu Jan 18 09:42:35 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 11:42:35 -0300 Subject: urllib2 and transfer-encoding = chunked References: <1169108468.497013.228520@l53g2000cwa.googlegroups.com> Message-ID: <eoo10v$pgf$1@sea.gmane.org> <jdvolz at gmail.com> escribi? en el mensaje news:1169108468.497013.228520 at l53g2000cwa.googlegroups.com... >I am having errors which appear to be linked to a previous bug in > urllib2 (and urllib) for v2.4 and v2.5 of Python. Has this been fixed? > Has anyone established a standard workaround? I keep finding old > posts about it, that basically give up and say "well it's a known bug." > Any help would be greatly appreciated. Perhaps if you said what the supposed error is... -- Gabriel Genellina From domma at procoders.net Tue Jan 23 13:24:41 2007 From: domma at procoders.net (Achim Domma) Date: Tue, 23 Jan 2007 19:24:41 +0100 Subject: Overloading assignment operator Message-ID: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Hi, I want to use Python to script some formulas in my application. The user should be able to write something like A = B * C where A,B,C are instances of some wrapper classes. Overloading * is no problem but I cannot overload the assignment of A. I understand that this is due to the nature of Python, but is there a trick to work around this? All I'm interested in is a clean syntax to script my app. Any ideas are very welcome. regards, Achim From hg at nospam.org Thu Jan 11 03:49:50 2007 From: hg at nospam.org (hg) Date: Thu, 11 Jan 2007 09:49:50 +0100 Subject: Newbie question: SMTP -> SQL Server References: <1168529572.873867.207730@k58g2000hse.googlegroups.com> Message-ID: <j0tph.33102$X97.7130@newsfe18.lga> jrpfinch wrote: > I have an externally-written piece of software that spits out emails > using SMTP (a few hundred per hour) and I would like to dump the > content of them in an MS SQL Server database. > > I have barely used Python before but it looks as if it could do the > job. I have no experience with mail agents. My starting point is this > recipe: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440690 > > I know that there are various libraries that can connect to MS SQL > server and I am going to research these. http://sourceforge.net/projects/mysql-python > > I have two questions: > > i) Does this sound like an efficient way of transferring data to the > database? Not certain I understand > ii) Looking through the Python documentation, I cannot see a way to > set the password on the SMTP server. I would like to have a password - > does anyone know how to use the recipe above to set one? s = smtplib.SMTP() .... s.login(...,'password') > > Any other useful nudges in the right direction appreciated. > > Many thanks > > Jon hg From steve at REMOVE.THIS.cybersource.com.au Mon Jan 1 00:14:13 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 01 Jan 2007 16:14:13 +1100 Subject: I want to see all the variables References: <s57lh.335$c46.311@newsfe05.lga> <45952426.1080800@websafe.com> <pan.2006.12.29.16.35.00.363156@REMOVE.THIS.cybersource.com.au> <8yelh.90$Q4.82@newsfe02.lga> <pan.2006.12.29.22.46.14.436601@REMOVE.THIS.cybersource.com.au> <FPylh.22$eq5.11@newsfe02.lga> <459722fc$0$30313$9b4e6d93@newsspool1.arcor-online.net> <pan.2006.12.31.02.56.19.358717@REMOVE.THIS.cybersource.com.au> <2v0hp2tbk8uq2pbqi6874b4tidbck2tpga@4ax.com> Message-ID: <pan.2007.01.01.05.14.12.260857@REMOVE.THIS.cybersource.com.au> On Sun, 31 Dec 2006 19:48:55 -0800, Tom Plunket wrote: > Steven D'Aprano wrote: > >> What does the author of the original class know about *my* needs and >> requirements? > > The only thing that the original class author might know is that mucking > with data marked private may well cause problems, and hiding it > therefore prevents those problems. Sure. That's the risk I take when I muck about with somebody else's private attributes. >> It may turn out that accessing his "private" attributes is exactly what >> I need to solve my problem. > > It may also turn out that you /think/ that's what you need to do, but > actually need to do something different. And how is that different from *any* programming task? I might think I need a binary tree, when all I really need is a simple list. An error is an error, whether it is with a public API or a private one. > E.g. it may well be possible to access the bytes on the disk that holds > your database directly, and that may be "easier" than going through the > db API, but doing so may also be highly prone to error. No, I doubt it is "easier" -- but if I'm programming a database recovery tool that fixes corrupted databases because the db vendor's supplied tool is broken or non-existent, that might be exactly what I need to do. >> I'm with the Python philosophy on this one: post all the "Don't Touch >> This" warning signs you like, but if somebody really wants to access my >> private attributes, to do something I never even imagined, they should >> be allowed to. > > You are allowed to. Have you been following the thread? Your answer's > been mentioned several times. Yes, mostly by me. Do try to keep up. > At the same time, you should ponder very > carefully the reasons why the original author deemed it important to > make those attributes private in the first place. In my experience, it is mostly because they come from bondage-and-domination languages where it is expected that everything is private except for a small, carefully chosen public API, rather than from languages like Python that encourages openness and a philosophy of "we're all adults here". I wonder how many double-underscore "private" attributes are used in the Python standard library? That should give you an idea of "best practice" use of private attributes in Python. -- Steven. From tsuraan at gmail.com Mon Jan 8 11:13:42 2007 From: tsuraan at gmail.com (tsuraan) Date: Mon, 8 Jan 2007 10:13:42 -0600 Subject: Suitability for long-running text processing? In-Reply-To: <c2701f5c0701080801w4d3c378elf901db19610a2e9e@mail.gmail.com> References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> <c2701f5c0701080801w4d3c378elf901db19610a2e9e@mail.gmail.com> Message-ID: <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> > I just tried on my system > > (Python is using 2.9 MiB) > >>> a = ['a' * (1 << 20) for i in xrange(300)] > (Python is using 304.1 MiB) > >>> del a > (Python is using 2.9 MiB -- as before) > > And I didn't even need to tell the garbage collector to do its job. Some > info: It looks like the big difference between our two programs is that you have one huge string repeated 300 times, whereas I have thousands of four-character strings. Are small strings ever collected by python? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070108/634808c4/attachment.html> From martin.witte at gmail.com Sat Jan 6 17:53:04 2007 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 6 Jan 2007 14:53:04 -0800 Subject: Doing date/time + TZ math in python In-Reply-To: <459ee41c$0$4805$88260bb3@free.teranews.com> References: <459ee41c$0$4805$88260bb3@free.teranews.com> Message-ID: <1168123983.983339.163010@s80g2000cwa.googlegroups.com> Joshua J. Kugler wrote: > I've read docs (datetime, time, pytz, mx.DateTime), googled, and > experimented. I still don't know how to accomplish what I want to > accomplish. > > I'm loading up a bunch of date/time data that I then need to do math on to > compare it to the current date/time. I can get the current time easily > enough: > > currentTime = datetime.datetime.now(pytz.timezone('America/Anchorage')) > > Then, I want to import data/time pairs that are in "%Y-%m-%d %H:%M:%S" > format. > > So, I do: > > For each loop, extract time data, blah, blah, then: > readingTime = datetime.datetime(rYr, rMo, rDay, rHr, rMin, rSec, > tzinfo=pytz.timezone('America/Anchorage')) > > The problem is, how do I create a datetime object and tell it that it's > America/Anchorage *daylight savings time* instead of whatever the system is > currently set at? pytz only has America/Anchorage, and I saw no way to > tell it explicitly that the timezone is in Daylight instead of Standard > time (e.g. using AKST vs. AKDT for the time zone). > > I'm sure there is a way to do it, and I'm sure it's quite simple, but it > hasn't jumped out at me yet. Is there a module that I haven't seen that > would be better suited for this? > > Thanks! > > j > > -- > Joshua Kugler > Lead System Admin -- Senior Programmer > http://www.eeinternet.com > PGP Key: http://pgp.mit.edu/ ID 0xDB26D7CE > > -- > Posted via a free Usenet account from http://www.teranews.com It looks like3 you're 9 hours in this example: http://docs.python.org/lib/datetime-tzinfo.html, see e.g. http://www.worldtimezone.com/index12.php From jf.pieronne at laposte.net Fri Jan 26 02:13:47 2007 From: jf.pieronne at laposte.net (=?ISO-8859-1?Q?Jean-Fran=E7ois_Pi=E9ronne?=) Date: Fri, 26 Jan 2007 08:13:47 +0100 Subject: Module for SVG? In-Reply-To: <mailman.3164.1169751502.32031.python-list@python.org> References: <mailman.3164.1169751502.32031.python-list@python.org> Message-ID: <45b9aa2f$0$30992$426a74cc@news.free.fr> Sebastian Bassi a ?crit : > Hello, > > I found http://www2.sfk.nl/svg as a Python module for writing SVG. > Last update was in 2004 and I am not sure if there is something > better. > Any recommendation for generating SVG graphics? I have ported to Python the Ruby SVG graph generation library http://www.germane-software.com/software/SVG/SVG::Graph/ some examples: http://www.germane-software.com/software/SVG/SVG::Graph/screenshots.html If you have some interest let me know. JF From schpok at gmail.com Sun Jan 7 21:59:53 2007 From: schpok at gmail.com (schpok at gmail.com) Date: 7 Jan 2007 18:59:53 -0800 Subject: Module to read svg Message-ID: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> I'm looking for a module to load an SVG document so that I can read out its contents in some graphics-centric way. For example, path elements store their vertices in a long attribute string you need to parse. An ideal module would get me these vertices in a list. SVGdraw seems to only write, but not read. I'm interested in a pretty simple subset of the actual spec, where SVG Tiny is sufficient. W3C's python spec seems just what I want: http://www.w3.org/TR/SVGMobile12/python-binding.html Does anyone know if there's an actual free implementation of this? Before I start salvaging out code from Skencil, is there anything else I might look at? Thanks, Schpok From wd.jonsson at gmail.com Wed Jan 24 08:36:19 2007 From: wd.jonsson at gmail.com (wd.jonsson at gmail.com) Date: 24 Jan 2007 05:36:19 -0800 Subject: Missing .dlls when installing PyQt!? :( Message-ID: <1169645779.368746.157750@l53g2000cwa.googlegroups.com> Hello! I must be doing something wrong here because I'm getting all these missing .dll messages after installing PyQT. This is what I've done (no step excluded): 1. Fresh installation of Python25 2. I run the PyQt-gpl-4.1.1-Py2.5-Qt4.2.2.exe file which should include SIP 3. I run the qt-win-opensource-4.2.2-mingw.exe file 4. I try to launch the C:\Program Files\PyQt4\examples\tools\qtdemo\qtdemo.pyw file Result: Error message says: Can't find mingwm10.dll After searching for the file I found it in the C:\Qt\4.2.2\bin directory. I copied the dll to the windows dir just to run in to the next missing dll error (QtCore4.dll) which is also located in the same directory. What have I missed? I've been trying to install QT for 6 hours now... Gah, please help! :) From fredrik at pythonware.com Thu Jan 25 04:32:49 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 Jan 2007 10:32:49 +0100 Subject: Subclassing cElementTree.XMLTreeBuilder References: <1169695233.737016.95950@a75g2000cwd.googlegroups.com> Message-ID: <ep9tg2$2s4$2@sea.gmane.org> "mukappa" wrote: > Is it possible to subclass cElementTree.XMLTreeBuilder? no, it's a factory function. if you need to extend it, you'll have to wrap it. but I'm not sure I see the use case; what is it you're trying to do here? </F> From bearophileHUGS at lycos.com Fri Jan 19 08:04:01 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 Jan 2007 05:04:01 -0800 Subject: Iterator length In-Reply-To: <pan.2007.01.19.11.36.29.99822@REMOVE.THIS.cybersource.com.au> References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> <1169167258.553202.190130@m58g2000cwm.googlegroups.com> <1169168139.350836.79790@s34g2000cwa.googlegroups.com> <pan.2007.01.19.11.36.29.99822@REMOVE.THIS.cybersource.com.au> Message-ID: <1169211840.951796.87080@q2g2000cwa.googlegroups.com> Steven D'Aprano: > > s = "aaabbbbbaabbbbbb" > > from itertools import groupby > > print [(h,leniter(g)) for h,g in groupby(s)] > > s isn't an iterator. It's a sequence, a string, and an iterable, but not > an iterator. If you look better you can see that I use the leniter() on g, not on s. g is the iterator I need to compute the len of. > I hope you know what sequences and strings are :-) Well, I know little still about the C implementation of CPython iterators :-) But I agree with the successive things you say, iterators may be very general things, and there are too many drawbacks/dangers, so it's better to keep leniter() as a function separated from len(), with specialized use. Bye and thank you, bearophile From nmm1 at cus.cam.ac.uk Wed Jan 24 12:12:19 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 24 Jan 2007 17:12:19 GMT Subject: The reliability of python threads References: <mailman.3092.1169657938.32031.python-list@python.org> Message-ID: <ep841j$anu$1@gemini.csx.cam.ac.uk> In article <mailman.3092.1169657938.32031.python-list at python.org>, "Carl J. Van Arsdall" <cvanarsdall at mvista.com> writes: |> Hey everyone, I have a question about python threads. Before anyone |> goes further, this is not a debate about threads vs. processes, just a |> question. |> |> With that, are python threads reliable? Or rather, are they safe? I've |> had some strange errors in the past, I use threading.lock for my |> critical sections, but I wonder if that is really good enough. |> |> Does anyone have any conclusive evidence that python threads/locks are |> safe or unsafe? Unsafe. They are built on top of unsafe primitives (POSIX, Microsoft etc.) Python will shield you from some problems, but not all. There is precious little that you can do, because the root cause is that the standards and specifications are hopelessly flawed. Regards, Nick Maclaren. From pierre at saiph.com Tue Jan 30 10:49:01 2007 From: pierre at saiph.com (Imbaud Pierre) Date: Tue, 30 Jan 2007 16:49:01 +0100 Subject: data design In-Reply-To: <1170169714.066396.227860@s48g2000cws.googlegroups.com> References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170169714.066396.227860@s48g2000cws.googlegroups.com> Message-ID: <45bf68f8$0$30987$426a74cc@news.free.fr> Szabolcs Nagy a ?crit : >>The lazy way to do this: have modules that initialize bunches of >>objects, attributes holding the data: the object is somehow the row of >>the "table", attribute names being the column. This is the way I >>proceeded up to now. >>Data input this way are almost "configuration data", with 2 big >>drawbacks: >> - Only a python programmer can fix the file: this cant be called a >> configuration file. >> - Even for the author, these data aint easy to maintain. >> >>I feel pretty much ready to change this: >>- make these data true text data, easier to read and fix. >>- write the module that will make python objects out of these data: >>the extra cost should yield ease of use. >> >>2 questions arise: >>- which kind of text data? >> - csv: ok for simple attributes, not easy for lists or complex >> data. >> - xml: the form wont be easier to read than python code, >> but an xml editor could be used, and a formal description >> of what is expected can be used. >>- how can I make the data-to-object transformation both easy, and able >> to spot errors in text data? >> >>Last, but not least: is there a python lib implementing at least part >>of this dream? > > > there is a csv parser and multiple xml parsers in python (eg > xml.etree) I used both. both are ok, but only bring a low layer parsing. > also there is a ConfigParser module (able to parse .ini > like config files) Used this years ago, I had forgotten. Another fine data text format. > > i personally like the python module as config file the most > > eg if you need a bunch of key-value pairs or lists of data: > * python's syntax is pretty nice (dict, tuples and lists or just > key=value) But only python programmer editable! > * xml is absolutely out of question > * csv is very limited > * .ini like config file for more complex stuff is not bad but then you > can use .py as well. > Thanks a lot for your advices. From gagsl-py at yahoo.com.ar Fri Jan 19 20:15:22 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 22:15:22 -0300 Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A9C@eugsrv400.psc.psc net.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A9C@eugsrv400.psc.pscnet.com> Message-ID: <7.0.1.0.0.20070119205257.033b9310@yahoo.com.ar> At Friday 19/1/2007 18:43, Carroll, Barry wrote: >Secondly, can someone point me to the Standard Usenet Convention that >mandates against top-posting. This is not sarcasm; I would really like >to see it. There are some guidelines, like RFC 1855 (not a real standard, or enforced in any way): http://www.faqs.org/ftp/rfc/rfc1855.txt "If you are sending a reply to a message or a posting be sure you summarize the original AT THE TOP OF THE MESSAGE, or include just enough text of the original to give a context (...) But do not include the entire original!" (capitals added by me). >You see, I recently returned to Usenet after a LONG absence. >When I was last a regular Usenet citizen the Internet was new, GUI >interfaces were experimental and the World Wide Web didn't exist yet. >Newsreader software was text-based. Top-posting was the common >practice, because it was the most convenient: you didn't have to page >through an arbitrarily large number of messages, most of which you'd >already read umpteen times, to get to the new stuff you were interested >in. Really? Top posting a common practice? I'm not a youngster either and I've never seen top posting as a *norm* but an exception. Old newsreaders had a new/quoted ratio, and enforced it to be rather high - so it was not easy to forget to trim the quoted text. http://www.i-hate-computers.demon.co.uk/quote.html Digging a bit one can find some old recommendations, like the Big Dummy's Guide to the Internet (1993): http://www.cs.indiana.edu/docproject/bdgtti/bdgtti_2.html Or people puzzled on how this works: http://groups.google.com/group/news.newusers.questions/browse_thread/thread/a75b1f4cfe470276/b38f62fc633db61e -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From arkanes at gmail.com Mon Jan 8 13:12:52 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 8 Jan 2007 12:12:52 -0600 Subject: Why less emphasis on private data? In-Reply-To: <pjvoh.192$cQ2.1@read3.inet.fi> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <%Isoh.22447$X97.12337@newsfe18.lga> <slrneq4nqc.k8.horpner@FIAD06.norwich.edu> <pjvoh.192$cQ2.1@read3.inet.fi> Message-ID: <4866bea60701081012m7698b60fyd92cc005a5fe83a2@mail.gmail.com> Private data in the C++ and Java OO worlds is so taught so much and emphasized so often that people have started thinking of it as being desirable for its own sake. But the primary motivation for it grew out of the need to maintain compatible interfaces. These languages rely on a great deal of shared information between provides and clients of interfaces in order to work correctly - public/private interfaces are simply a reflection of that requirement (and the fact that your clients still need to see the stuff you declare as private is an example of a leak in that abstraction). Python doesn't have these problems, so the only use for private information is to warn your clients away from access to certain names. There's no need for compiler enforcement of that, as a convention is just as effective. The remaining arguments are generally outgrowths of "but my code is SECRET", which just isn't true in general, even less true of Python, and not really a healthy attitude anyway. From vithi99 at hotmail.com Mon Jan 15 13:53:26 2007 From: vithi99 at hotmail.com (vithi) Date: 15 Jan 2007 10:53:26 -0800 Subject: How to write code to get focuse the application which is open from server In-Reply-To: <m%Oqh.10311$pQ3.45@newsread4.news.pas.earthlink.net> References: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> <45a0dae2$0$8948$4c368faf@roadrunner.com> <1168837895.073936.270330@11g2000cwr.googlegroups.com> <m%Oqh.10311$pQ3.45@newsread4.news.pas.earthlink.net> Message-ID: <1168887206.135633.182600@s34g2000cwa.googlegroups.com> Dennis, I am sorry that was a typing error. I try like that app.Print.OK.Click() but it was not working. The printer window was not IdentifiedIs their any method I can use to achive the same goal. How the window title was used as class name?. Could you please help me to solve this problem. thanks this is the error meassage Traceback (most recent call last): File "C:\Python24\test1.py", line 10, in -toplevel- app.Print.Ok.CloseClick() File "c:\python24\pywinauto\pywinauto\application.py", line 237, in __getattr__ ctrls = _resolve_control( File "c:\python24\pywinauto\pywinauto\application.py", line 854, in _resolve_control ctrl = _get_ctrl(criteria) File "c:\python24\pywinauto\pywinauto\application.py", line 622, in _get_ctrl dialog = controls.WrapHandle( File "c:\python24\pywinauto\pywinauto\findwindows.py", line 62, in find_window windows = find_windows(**kwargs) File "c:\python24\pywinauto\pywinauto\findwindows.py", line 177, in find_windows windows = findbestmatch.find_best_control_matches( File "c:\python24\pywinauto\pywinauto\findbestmatch.py", line 483, in find_best_control_matches raise MatchError(items = name_control_map.keys(), tofind = search_text) MatchError: Could not find 'Print' in '['', u'Transparent Windows Client0', u'Transparent Windows Client2', u'Transparent Windows Client1', u'Print - \\\\Remote', u'Transparent Windows Client', u'Print - \\\\RemoteTransparent Windows Client']' This is the code import sys import time import application app = application.Application() qi=app.window_(title_re = ".*ArcView.*") time.sleep(2) qi.TypeKeys("%FP") time.sleep(2) app.Print.Ok.CloseClick() Dennis Lee Bieber wrote: > On 14 Jan 2007 21:11:35 -0800, "vithi" <vithi99 at hotmail.com> declaimed > the following in comp.lang.python: > > > > > my code goes like that > > "goes like"? Don't type similarities from memory -- cut&paste the > actual code (or, preferably, a stripped down version that you've > actually run) that shows the behavior in question. > > > app=application.Application() > > qi = app.window_(title_re = ".*arcMap.*") > > qi.TypeKeys("%FP") > > app,Print.OK.Click() > > > And what is that last line supposed to be doing. "app,anything" is > two separate objects: an application object, and something called Print > with an attribute called OK which itself has a method called Click > > I suspect, at a minimum, that last line is supposed to be > > app.Print.OK.Click() > ^ period, not From larry.bates at websafe.com Thu Jan 11 18:33:17 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 11 Jan 2007 17:33:17 -0600 Subject: Newbie question: SMTP -> SQL Server In-Reply-To: <mailman.2585.1168533856.32031.python-list@python.org> References: <1168529572.873867.207730@k58g2000hse.googlegroups.com> <j0tph.33102$X97.7130@newsfe18.lga> <1168531934.015865.177100@i56g2000hsf.googlegroups.com> <mailman.2585.1168533856.32031.python-list@python.org> Message-ID: <45A6C93D.4060605@websafe.com> Steve Holden wrote: > jrpfinch wrote: >> Thank you. I have just realised I completely misunderstand how SMTP >> servers work. From what I can tell, when you run the cookbook script >> it listens locally on port 8025. >> >> You then have to configure a Linux (in my case) account with a username >> and password so my external piece of software (on another Windows >> machine) can log in and use the SMTP server. >> >> Then I write the some code in the cookbook example to redirect any mail >> content to the MS SQL server database. >> >> Note that the external piece of software can only talk SMTP - this is >> why I am having to develop this script. >> >> Does this sound sensible? Any tips on how to configure my Linux box (I >> don't have much experience with Linux either)? >> >> Many thanks >> >> Jon >> > Presumably you can configure the external piece of software at least to > the extent of setting the email address it delivers to? > > In that case it will be *much* simpler to set up an account on a mail > server to receive these emails. That way the server will be available > whenever the SMTP-based sender wants or needs to send mail, and you can > use Python to collect the emails in batched using the POP protocol, as a > client. > > Once you receive the email messages then yes, it's perfectly practical > to save the content in a SQL server database. mxODBC is one possible > driver package (though it requires you to purchase a license for > commercial use), and I seem to remember there's another one called > adodbapi that is open source. There are almost certainly others, but > it's a while since I used SQL Server with Python. > > regards > Steve Good advice. BTW-You can use dbi and odbc modules to work with SQL server without purchasing anything. From fdelente at mail.cpod.fr Sat Jan 27 02:22:15 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 27 Jan 2007 07:22:15 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <slrnerkjtc.1f8.horpner@FIAD06.norwich.edu> <45ba50c7$0$31432$426a74cc@news.free.fr> <slrnerks72.jc.horpner@FIAD06.norwich.edu> <12rl5mq4nnqoea0@corp.supernews.com> Message-ID: <45bafda7$0$2417$426a74cc@news.free.fr> My system is Linux, and the distribution is Slackware 10.1. I have /lib/libncurses.so.5.4 /lib/libncursesw.so.5.4 so I even have the wide-chars version available. Any hint on the python configuration? I didn't find any function that would allow the unrestricted display of 8-bit chars. -- Fabrice DELENTE From dantonio at iasi.cnr.it Fri Jan 5 06:51:12 2007 From: dantonio at iasi.cnr.it (Fulvio D'Antonio) Date: Fri, 5 Jan 2007 12:51:12 +0100 Subject: CPU management Message-ID: <00ce01c730bf$cca10560$a5059296@IBM75CFA6491AB> Hello everybody, I usally develop a lot of expensive (in terms of CPU usage) algorithms. I would like to develop something that allows my application to run quietly all day long with a little CPU usage, so that I can work in the meanwhile! I was wondering if there is a way to limit the CPU usage: e.g. 10% instead of 100%, or to let the algorithm to be resumed only when the CPU usage changes. I think these kind of things are called "resource management". So, are there facilities for this in Python= I'm running Python2.4 on Windows XP. Thank you for your help. Fulvio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070105/737de92b/attachment.html> From bignose+hates-spam at benfinney.id.au Thu Jan 18 20:22:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 Jan 2007 12:22:04 +1100 Subject: Determining when a file is an Open Office Document References: <eop5ci$et5$1@solaris.cc.vt.edu> Message-ID: <87mz4f6car.fsf@benfinney.id.au> tubby <tubby at bandaheart.com> writes: > Silly question, but here goes... what's a good way to determine when > a file is an Open Office document? I could look at the file > extension, but it seems there would be a better way. Yes, the name of a file may be useful for communicating with humans about that file's intended use, but is a lousy, unreliable way to make a definite statement about the actual contents of the file. The Unix 'file' command determines the type of a file by its contents, not its name. This functionality is essentially a database of "magic" byte patterns mapping to file types, and is provided by a library called "libmagic", distributed with most GNU/Linux distributions. <URL:http://packages.debian.org/testing/source/file> There is a Python interface to the "magic" functionality. It's in Debian; I'm not sure if it's part of the "magic" code base, or written separately to interface with it. Either way, you can get the source for those packages and find out more. <URL:http://packages.debian.org/unstable/python/python-magic> -- \ "If life deals you lemons, why not go kill someone with the | `\ lemons (maybe by shoving them down his throat)." -- Jack Handey | _o__) | Ben Finney From timr at probo.com Fri Jan 19 03:42:10 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 19 Jan 2007 08:42:10 GMT Subject: How to read and write huge binary files References: <1169136850.518228.103360@l53g2000cwa.googlegroups.com> Message-ID: <p011r21i4if66oob7vu403jdsrukr1kih7@4ax.com> "Lad" <python at hope.cz> wrote: > >What is a good way to read binary data from HUGE file and write it >to another file? How huge? I regularly process 100-megabyte MPEG files in Python, both by reading the whole thing in as a string, and by using "mmap" to map the file into memory. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gnewsg at gmail.com Wed Jan 17 08:29:47 2007 From: gnewsg at gmail.com (billie) Date: 17 Jan 2007 05:29:47 -0800 Subject: 2.3-2.5 what improved? In-Reply-To: <eol0qn$kvj$1@news.albasani.net> References: <mailman.2817.1169029744.32031.python-list@python.org> <eol0qn$kvj$1@news.albasani.net> Message-ID: <1169040587.340057.11040@m58g2000cwm.googlegroups.com> robert wrote > Robin Becker wrote: > > A large cgi based web Python-2.3 application needs to be speed improved. > > experiments show the following under reasonable testing (these are 2 > > second reportlab pdf productions) > > > > 1) 2.3 --> 2.5 improvement small 1-2% > > 2) cgi --> fcgi improvement medium 10-12% > > > > I sort of remember claims being made about 2.5 being 10% faster than > > 2.4/2.3 etc etc. Can anyone say where the speedups were? Presumably we > > have a lot of old cruft that could be improved in some way eg moving > > loops into comprehensions, using iterator methods etc. Are those sort of > > things what we should look at? > > Python 2.5 became quite fat. For bare CGI the Python load/init > time eats all improvements. Smaller scripts even loose lot of speed. > I still like Python 2.3 for many other reasons for many > applications - especially for CGI's, on Windows, for deployable > apps, GUI's etc. because the fat coming with Python 2.4 is not > balanced by necessary goods - mostly just fancy things. What do you mean? Fat of libraries or fat itself? I tought that 2.5 was faster than precedent versions! :-\ From cbc at unc.edu Thu Jan 18 11:14:13 2007 From: cbc at unc.edu (Chris Calloway) Date: Thu, 18 Jan 2007 11:14:13 -0500 Subject: Zope 3 Boot Camp and Sprint registration open Message-ID: <45af9ce4_3@news.unc.edu> The Triangle (NC) Zope and Python Users Group invites you to register for Camp 5 and the BBQ Sprint: http://trizpug.org/boot-camp/camp5/ This is a Zope 3 boot camp followed by a Plone 3 sprint. The boot camp is taught by Philipp von Weitershausen, author of Web Component Development with Zope 3. The training has previously only been offered in Europe and is now available in North America for the first time. The sprint includes several sponsored and invited sprinters. TriZPUG hopes you will participate in Camp 5 in Chapel Hill, NC. Camp 5: Saturday March 10 - Tuesday March 13, 2007 BBQ Sprint: Wednesday March 14 - Saturday March 17, 2007 -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From tpawley at gmail.com Tue Jan 9 04:56:44 2007 From: tpawley at gmail.com (Torabisu) Date: 9 Jan 2007 01:56:44 -0800 Subject: General Question About Python In-Reply-To: <1168254451.098796.144790@42g2000cwt.googlegroups.com> References: <1168254451.098796.144790@42g2000cwt.googlegroups.com> Message-ID: <1168336603.962731.5470@11g2000cwr.googlegroups.com> I think the best I've heard is, "Programming in Python is like writing poetry". Its really a beautiful language, so simple, short, powerful and to the point. We use it in conjunction with Django to implement a web based device management solution for our products. We've also written a multi-threaded gateway / modem pool server that assists us with data calls, sms'ing, and gprs based communication. Its quite weird, we're looking for Python skills but are battling to find at the moment... Normally Python on its own will probably not land you a job, but the last two companies I've worked for are doing indepth Python development, so hopefully the tables are turning a bit. Enteng wrote: > To those who program in python, what programs do you do? > Also what community projects are you involved in(OSS probably)? > Will mastering the language land me a job? > > I'm thinking about learning the language as a hobby. Just curious :) From horpner at yahoo.com Tue Jan 16 10:01:19 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Jan 2007 16:01:19 +0100 Subject: Regular expressions question References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> <Xns98BA7A00DDBC0duncanbooth@127.0.0.1> <1168957361.204348.30080@s34g2000cwa.googlegroups.com> <slrneqpp4e.r8.horpner@FIAD06.norwich.edu> <1168958674.976563.91260@l53g2000cwa.googlegroups.com> Message-ID: <slrneqpqam.r8.horpner@FIAD06.norwich.edu> On 2007-01-16, Victor Polukcht <vpolukcht at gmail.com> wrote: > On Jan 16, 5:40 pm, Neil Cerutti <horp... at yahoo.com> wrote: >> On 2007-01-16, Victor Polukcht <vpoluk... at gmail.com> wrote: >> >> > Actually, i'm trying to get the values of first field (Global) , fourth >> > (200, 4), and fifth (100%) and sixth (100%). >> >> > Everything except fourth is simple. >> >>> g = "Global etsi3 * 4 ok 30 100% 100% Outgoing" >> >>> import re >> >>> r = re.search('\*\s+(\d+)', g) >> >>> r.group() >> '* 4' >> >>> r.group(1)'4' > > The same regular expression should work for another string (with *200). Sorry about that. It should have been: r = re.search('\*\s*(\d+)', g) -- Neil Cerutti From melih.onvural at gmail.com Mon Jan 29 15:44:07 2007 From: melih.onvural at gmail.com (Melih Onvural) Date: 29 Jan 2007 12:44:07 -0800 Subject: Executing Javascript, then reading value Message-ID: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> I need to execute some javascript and then read the value as part of a program that I am writing. I am currently doing something like this: import htmllib, urllib, formatter class myparser(htmllib.HTMLParser): insave = 0 def start_div(self, attrs): for i in attrs: if i[0] == "id" and i[1] == "pr": self.save_bgn() self.insave = 1 def end_div(self): if self.insave == 1: print self.save_end() self.insave = 0 parser = myparser(formatter.NullFormatter()) #def getPageRank(self, url): try: learn_url = "http://127.0.0.1/research/getPageRank.html?q=http:// www.yahoo.com&" pr_url = urllib.urlopen(learn_url) parser.feed(pr_url.read()) except IOError, e: print e but the result is the javascript function and not the calculated value. Is there anyway to get the javascript to execute first, and then return to me the value? thanks in advance, Melih Onvural From ivoras at fer.hr Tue Jan 2 09:53:40 2007 From: ivoras at fer.hr (Ivan Voras) Date: Tue, 02 Jan 2007 15:53:40 +0100 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: <1167720155.296077.233010@42g2000cwt.googlegroups.com> References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <qt5jp2pq4a6a9b4gpha1rvou0cl7ji1gem@4ax.com> <mailman.2191.1167695021.32031.python-list@python.org> <1167720155.296077.233010@42g2000cwt.googlegroups.com> Message-ID: <endrll$gjk$1@news1.carnet.hr> Ramdas wrote: > Well, > > I need to add users from a web interface for a web server, which runs > only Python. I need to add users, set quotas and in future even look at > managing ip tables to limit bandwidth. > > I know os.system(), but this has to be done through a form entry > through a web interface. > > Anyways thanks, do advise if there more pythonic solutions What you're looking for is actually a pretty complex thing. You *could* in theory manage /etc/passwd (and its "shadow" file) - you can find crypto primitives like MD5 and DES on the 'net, but note that you must run your script under the 'root' account in order to write (and even read!) the passwd database. The same goes for using os.system and the built-in OS utility. Be aware of security implications if you're running your web server under the root account. From ejensen at visi.com Tue Jan 16 14:18:42 2007 From: ejensen at visi.com (Ed Jensen) Date: Tue, 16 Jan 2007 19:18:42 -0000 Subject: How to determine what exceptions a method might raise? Message-ID: <12qq98ijkn5mld8@corp.supernews.com> I'm really enjoying using the Python interactive interpreter to learn more about the language. It's fantastic you can get method help right in there as well. It saves a lot of time. With that in mind, is there an easy way in the interactive interpreter to determine which exceptions a method might raise? For example, it would be handy if there was something I could do in the interactive interpreter to make it tell me what exceptions the file method might raise (such as IOError). Thanks in advance. From skip at pobox.com Fri Jan 12 09:31:18 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 12 Jan 2007 08:31:18 -0600 Subject: How much slower is dict indexing vs. list indexing? In-Reply-To: <1168611039.720278.13430@s34g2000cwa.googlegroups.com> References: <1168555253.601611.258600@k58g2000hse.googlegroups.com> <mailman.2606.1168556128.32031.python-list@python.org> <1168611039.720278.13430@s34g2000cwa.googlegroups.com> Message-ID: <17831.39862.421489.36796@montanaro.dyndns.org> Emin> It sounds like it's probably not worth the effort in general, but Emin> might be for extremely ultra-critical parts of code. Even in extremely ultra-critical parts of code I doubt the loss of readability would be worth it. If there are situations where you can really gain by switching from a natural indexing scheme to lists, there are probably other places in your code where you will gain just as much benefit without the corresponding loss of readability. Indexing lists only appears to be about twice as fast as indexing dicts: % timeit.py -s "data = {'a' : 1, 'b' :2, 'c' : 3}" "for k in 'abc': x = data[k]" 100000 loops, best of 3: 4.61 usec per loop % timeit.py -s "data = [1, 2, 3]" "for k in [0, 1, 2]: x = data[k]" 100000 loops, best of 3: 2.97 usec per loop If you're worried about regaining a couple microseconds per index you probably shouldn't be using Python. Skip From chris at kateandchris.net Tue Jan 30 10:55:43 2007 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 30 Jan 2007 10:55:43 -0500 Subject: printing to a redirected stdout from a process that was called with "2>&1 > /dev/null &" In-Reply-To: <d49424c0701300742s1a1b9bfqce132b6abb2d4387@mail.gmail.com> References: <1170112357.792999.241280@s48g2000cws.googlegroups.com> <20070130153919.GA12259@kateandchris.net> <d49424c0701300742s1a1b9bfqce132b6abb2d4387@mail.gmail.com> Message-ID: <20070130155543.GB12259@kateandchris.net> On Tue, Jan 30, 2007 at 10:42:22AM -0500, Jason Persampieri wrote: > Sadly, the group is tied to Python 2.3 for now. Subprocess for 2.2 and 2.3: http://www.lysator.liu.se/~astrand/popen5/ Win32 installers for subversion for 2.2 and 2.3: http://www.lysator.liu.se/~astrand/popen5/ -Chris > > Actually, I got around this problem by using an intermediate process that > happens to handle output on its own (bsub). > > On 1/30/07, Chris Lambacher <[1]chris at kateandchris.net> wrote: > > The subprocess module is probably a good starting point: > [2]http://docs.python.org/dev/lib/module-subprocess.html > > It will allow you greater control over what happens with the output of a > process that you start. Specifically look at the the stdout and stderr > arguments to Popen. You can provide these with an open file descriptor > or a > file object and it will dump the output into there. > > -Chris > > > > _jason > > > > -- > > [3]http://mail.python.org/mailman/listinfo/python-list > > References > > Visible links > 1. mailto:chris at kateandchris.net > 2. http://docs.python.org/dev/lib/module-subprocess.html > 3. http://mail.python.org/mailman/listinfo/python-list From fairwinds at eastlink.ca Mon Jan 1 09:34:10 2007 From: fairwinds at eastlink.ca (David Pratt) Date: Mon, 01 Jan 2007 10:34:10 -0400 Subject: Collecting list of module dependencies Message-ID: <45991BE2.2010803@eastlink.ca> Hi. Is anyone aware of any code to create a list of dependent modules for a python module. Ideally am looking for something with a method to create a unique list of imported modules that excludes imports from the module being analyzed. Many thanks. Regards, David From sigzero at gmail.com Thu Jan 11 15:26:18 2007 From: sigzero at gmail.com (Robert Hicks) Date: 11 Jan 2007 12:26:18 -0800 Subject: Learning Python book, new edition? In-Reply-To: <mailman.2580.1168528978.32031.python-list@python.org> References: <mailman.2580.1168528978.32031.python-list@python.org> Message-ID: <1168547177.121582.320840@k58g2000hse.googlegroups.com> I would get "Core Python Programming" by Wesley Chun. It covers just about everything under the sun and includes version 2.5. Robert From maxm at mxm.dk Wed Jan 24 14:52:06 2007 From: maxm at mxm.dk (Max M) Date: Wed, 24 Jan 2007 20:52:06 +0100 Subject: Email attachments In-Reply-To: <mailman.3085.1169652009.32031.python-list@python.org> References: <mailman.3085.1169652009.32031.python-list@python.org> Message-ID: <45b7b8e7$0$13987$edfadb0f@dread15.news.tele.dk> Steve Holden skrev: > I'm having some trouble getting attachments right for all recipients, > and it seems like Apple's mail.app is the pickiest client at the moment. > It doesn't handle attachments that both Thunderbird and Outlook find > perfectly acceptable. > > Since the code I'm using is currently ugly and embedded, before I trim > it down for posting could anyone who's successfully generated emails > with attachments received by mail.app let me know if they had any > problems along the way? Google hasn't given me much on this, but I'm not > feeling very creative today. This method is used in one of my Plone products, and there is also a bit of imap in there. But it is probably simple enough to extract the attachment relevant parts.... security.declareProtected(EDIT_CONTENTS_PERMISSION, 'sendMessage') def sendMessage(self, to=None, cc=None, bcc=None, inReplyTo=None, subject=None, body='', attachments=None, mode=None, folderPath=None, uid=None, REQUEST=None): "Sends a message" site_encoding = self._site_encoding() ################## # Create the message msg = Message() msg.set_payload(body, site_encoding) ##################################### # if attachment, convert to multipart # file fields are posted even if empty, so we need to remove those :-s if attachments is None: attachments = [] attachments = [a for a in attachments if a] if attachments or (mode == 'Forward'): mimeMsg = MIMEMultipart() mimeMsg.attach(msg) # If mode is Forward we get original message as attachment if mode == 'Forward' and folderPath and uid: original = self.fetchMessageFromPath(folderPath, uid) mimeMsg.attach(original) for attachment in attachments: # Add the attachment tmp = email.message_from_string(str(attachment.headers)) filename = tmp.get_param('filename', 'Attachment', 'Content-Disposition') # clean up IE paths filename = filename[max(filename.rfind('/'), filename.rfind('\\'), filename.rfind(':') )+1:] contentType = tmp['Content-Type'] attach_part = Message() attach_part.add_header('Content-Type', contentType, name=filename) attach_part.add_header('Content-Disposition', 'attachment', filename=filename) attach_part.set_payload(attachment.read()) Encoders.encode_base64(attach_part) mimeMsg.attach(attach_part) msg = mimeMsg ######################## # set headers on message from_ = self.getEmail() msg['From'] = from_ msg['Reply-To'] = from_ if to: msg['To'] = to if cc: msg['Cc'] = cc if bcc: msg['Bcc'] = bcc msg['Date'] = self.ZopeTime().rfc822() # needed by some servers if inReplyTo: msg['In-Reply-To'] = inReplyTo msg['Subject'] = Header(subject, site_encoding) ################## # Send the message SMTPserver = self._mailhost() outbox = smtplib.SMTP(SMTPserver) try: cleaner = lambda adresses: [adress.strip() for adress in adresses.split(',') if adress.strip()] all_receivers = cleaner(to) + cleaner(cc) + cleaner(bcc) outbox.sendmail(from_, all_receivers, msg.as_string()) success = 1 except: success = 0 ###################################### # append the message to the 'Sent' box if success: Sent = self.getSentboxName() connection = self.getConnection() try: connection.append(Sent, msg.as_string(), ('\\Seen',)) except: # we don't want to not send messages just because the sentbox isn't set correctly pass ################################# # returns a portal status message if REQUEST: if success: message = 'Succes! The message was sent ' else: message = 'Error! The message could not be sent' REQUEST.RESPONSE.redirect(self.absolute_url() + '/mxmImapClient_compose?portal_status_message=%s' % message) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From gagsl-py at yahoo.com.ar Mon Jan 15 19:05:20 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 21:05:20 -0300 Subject: whats wrong with my reg expression ? In-Reply-To: <ef60af090701151543m1479689cg462a0f263401e5d1@mail.gmail.co m> References: <ef60af090701151441j2dbc2308ka8f326a181b6bba8@mail.gmail.com> <7.0.1.0.0.20070115195902.05c75aa0@yahoo.com.ar> <ef60af090701151543m1479689cg462a0f263401e5d1@mail.gmail.com> Message-ID: <7.0.1.0.0.20070115210348.05c788e0@yahoo.com.ar> At Monday 15/1/2007 20:43, Gert Cuykens wrote: >PS i also cant figure out what is wrong here ? > > rex=re.compile('^"(?P<value>[^"]*)"$',re.M) > for v in l: > v=rex.match(v).group('value') > v=v.replace('""','"') > return(l) > > v=rex.match(v).group('value') >AttributeError: 'NoneType' object has no attribute 'group' match() returns None when there is no match, so you have to split that in two steps: m = rex.match(v) if m: v = m.group('value') else: # no match found! -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From Barry.Carroll at psc.com Wed Jan 17 14:18:52 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 17 Jan 2007 11:18:52 -0800 Subject: *POLL* How many sheeple believe in the 911 fairy tale and willingto accept an Orwellian doublespeak and enslavement world ? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A7F@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: David Bostwick [mailto:david.bostwick at chemistry.gatech.edu] > Sent: Wednesday, January 17, 2007 10:43 AM > To: python-list at python.org > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > In article <1169058752.659674.6680 at s34g2000cwa.googlegroups.com>, "Robert > Hicks" <sigzero at gmail.com> wrote: > >Please, none of the real facts points to anything else except what > >actually happened. Two planes hit two towers and they came down. > > > > You're talking to the wind. This is a conspiracy precisely because people > deny the crackpots. Denial of their "evidence" proves that there is a > coverup. Logic is not involved, only belief that doesn't respond to > dissenting evidence. Ladies and Gentlemen: PLEASE take this discussion to a more appropriate forum. There are many forums where people will be happy to debate this: physics, firefighting, metallurgy, geopolitics, etc. This forum is about the Python programming language. Let's keep it that way. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From S.Mientki-nospam at mailbox.kun.nl Tue Jan 2 17:37:17 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 02 Jan 2007 23:37:17 +0100 Subject: list/dictionary as case statement ? In-Reply-To: <mailman.2226.1167776764.32031.python-list@python.org> References: <d59f3$459ad7cf$d443bb3a$14116@news.speedlinq.nl> <mailman.2226.1167776764.32031.python-list@python.org> Message-ID: <146b5$459ade8f$d443bb3a$5654@news.speedlinq.nl> > > Yes. Functions are (so called) first class objects. You can refer to one > by name, and pass that reference around in variables and other data > structures. > > That said, your code above won't work as written because function1 is > not in existence when you refer to it. > Yes, I just found that out. Thanks Gary and Grant, this principle really works like a charm. cheers, Stef Mientki From wesbrooks at gmail.com Wed Jan 3 11:57:41 2007 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 3 Jan 2007 16:57:41 +0000 Subject: type classobj not defined? Message-ID: <eec9f8ee0701030857o6218f87bpc40f63c62575098d@mail.gmail.com> Dear Users, I'm in the process of adding assert statements to a large piece of code to aid with bug hunting and came across the following issue; Using python in a terminal window you can do the following: >type(False) == bool True I would like to check that an object is a class, here's an example: >class b: ....def __init__(self): ........self.c = 1 ....def d(self): ........print self.c >type(b) <type 'classobj'> But the following fails: >type(b) == classobj Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'classobj' is not defined For the time being I'll use b.__name__ == b to ensure I'm getting the right class. Is there a reason why the other types such as bool are defined but classobj isn't? I'm running the following version of python: Python 2.4.3 (#1, Jun 13 2006, 11:46:08) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Cheers, Wesley Brooks From deets at nospam.web.de Fri Jan 26 12:29:34 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 26 Jan 2007 18:29:34 +0100 Subject: time series data and NumPy References: <1169830757.220964.196540@m58g2000cwm.googlegroups.com> Message-ID: <51us3uF1mdcpsU1@mid.uni-berlin.de> BBands wrote: > Good morning, > > I store time series data in a SQL database. The results of a typical > query using pyodbc look like this. > > Date Close > "2007-01-17" 22.57 > > Where Date is a datetime.date object and Close is a float. > > I'd like to put this data in a NumPy array for processing, but am > unsure as to how to handle the date. In the past I've used lists, but I > am looking to boost speed a bit as I wish to do a large number of > transformations and comparisons. > > Can one index an array using datetime objects? > > For example it would be nice to do a union of two arrays so that any > dates missing in either one were eliminated. > > Thoughts on doing rolling operations, such as an n-period average or > variance? > > Thoughts on working with time series data in arrays in general? I'm pretty sure you're out of luck here - even _if_ NumPy would handle arbitrary data-types (AFAIK it doesn't, but then I'm not a total expert there), it certainly won't be able to make its hi-performance functions work on them. What you could do would be to convert the date-column into a timestamp, which is a int/long, and use that. Would that help? diez From horpner at yahoo.com Mon Jan 8 10:10:22 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 8 Jan 2007 16:10:22 +0100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <%Isoh.22447$X97.12337@newsfe18.lga> Message-ID: <slrneq4nqc.k8.horpner@FIAD06.norwich.edu> On 2007-01-08, hg <hg at nospam.org> wrote: > sturlamolden wrote: > >> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that >> if an object's 'internal' variables or states cannot be kept private, >> programmers get an irresistible temptation to mess with them in >> malicious ways. But if you are that stupid, should you be programming >> in any language? The most widely used language is still C, and there is >> no concept of private data in C either, nor is it needed. > > > void test(void) > { > static int i; > } > > > Do you agree that i is "private" to test ? In C one uses the pointer to opaque struct idiom to hide data. For example, the standard FILE pointer. -- Neil Cerutti From vpolukcht at gmail.com Tue Jan 16 06:43:30 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 16 Jan 2007 03:43:30 -0800 Subject: Regular expressions question Message-ID: <1168947810.175793.228620@51g2000cwl.googlegroups.com> I have 2 strings: "Global etsi3 *200 ok 30 100% 100% Outgoing" and "Global etsi3 * 4 ok 30 100% 100% Outgoing" The difference is "*200" instead of "* 4". Is there ability to write a regular expression that will match both of that strings? From http Wed Jan 10 13:21:32 2007 From: http (Paul Rubin) Date: 10 Jan 2007 10:21:32 -0800 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <mailman.2408.1168248992.32031.python-list@python.org> <Xns98B269DCC12Fduncanbooth@127.0.0.1> <entr6s$ovo$1@news.albasani.net> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <eo38f1$6cu$1@gemini.csx.cam.ac.uk> Message-ID: <7x8xga215f.fsf@ruckus.brouhaha.com> nmm1 at cus.cam.ac.uk (Nick Maclaren) writes: > Yes, I know that it is a bit Irish for the best way to use a shared > memory system to be to not share memory, but that's how it is. But I thought serious MPI implementations use shared memory if they can. That's the beauty of it, you can run your application on SMP processors getting the benefit of shared memory, or split it across multiple machines using ethernet or infiniband or whatever, without having to change the app code. From Thomas.Ploch at gmx.net Tue Jan 9 19:56:53 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Wed, 10 Jan 2007 01:56:53 +0100 Subject: Question: Best Practice? (module 'shelve') In-Reply-To: <45A438AE.10105@gmx.net> References: <45A438AE.10105@gmx.net> Message-ID: <45A439D5.3080200@gmx.net> Thomas Ploch schrieb: > Hello fellows, > > I just wanted to know, if there is any best practice concerning > following code: > > import re, shelve > > class TextMatcher: > def __init__(self, patterns, email=False, dbName='textmatch.db'): > self._initPatterns(patterns) > self.email = email > self.dbName = dbName > if self.email: > self.emailList = [] > self.emailList.append( > re.compile(r'[a-zA-Z0-9_.]+@\w+\.\w+')) > > def match(self, src, url): > self.matchDict = {} > self.matchDict[url] = {} > # The next 2 functions just add stuff to self.matchDict > if self.email: > self._addEmails(src, url) > self._addPatterns(src, url) > # Is it good practice to open, write and close the db straight > # away? Or is it better to leave it open until the whole program > # has finished, and close it then? > self.openDB(self.dbName) > self.db[url] = self.matchDict[url] > self.db.close() > # I want to del the matchDict each time so it can't grow big. > # Is this good, or should it be left open, too? > del self.matchDict > > def openDB(self, dbName=None, modeflag='c'): > if dbName == None: > self.db = shelve.open('textmatch.db', flag=modeflag) > else: > self.db = shelve.open(dbName, flag=modeflag) > > s/del self.matchDict/self.matchDict.clear() and ignore the second question. When I read the sent message, it came to my mind. :-) Thomas From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 31 07:23:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 31 Jan 2007 13:23:03 +0100 Subject: another newbie question: why should you use "*args" ? In-Reply-To: <e1f8c$45c08065$83aef404$7421@news1.tudelft.nl> References: <e1f8c$45c08065$83aef404$7421@news1.tudelft.nl> Message-ID: <45c089de$0$6740$426a74cc@news.free.fr> stef a ?crit : > > why should I use *args, > as in my ignorance, > making use of a list (or tupple) works just as well, > and is more flexible in it's calling. Err... How so ? > So the simple conclusion might be: never use "*args", > or am I overlooking something ? Try writing generic higher order functions without it, and let us know. dummy example: def trace(func, *args, **kw): print "calling %s with %s %s" % (func.__name__, str(args), kw) try: result = func(*args, **kw) print "got %s" % str(result) return result except Exception, e: print "raised : %s" % e raise From jtravs at gmail.com Wed Jan 10 03:27:28 2007 From: jtravs at gmail.com (jtravs at gmail.com) Date: 10 Jan 2007 00:27:28 -0800 Subject: distutils and ctypes In-Reply-To: <mailman.2494.1168371562.32031.python-list@python.org> References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> <mailman.2494.1168371562.32031.python-list@python.org> Message-ID: <1168417648.227041.31110@o58g2000hsb.googlegroups.com> Robert Kern wrote: > jtravs at gmail.com wrote: > > > So finally, my question is, is there a way to get distutils to simply > > build a shared library on windows so that I can use ctypes with them??? > > Not out-of-box, no. The OOF2 project has added a bdist_shlib command which > should do most of what you want, though. It's somewhat UNIX-oriented, and I > think it tries to install the shared library to a standard location (e.g. > /usr/local/lib). You might want to modify it to install the shared library in > the package so it is easy to locate at runtime. > > http://www.ctcms.nist.gov/oof/oof2/ > http://www.ctcms.nist.gov/oof/oof2/source/oof2-2.0.1.tar.gz > > The code is in the shlib/ subdirectory. > Thank you very much - this looks like exactly what I want. John From ericclack at googlemail.com Tue Jan 16 17:36:03 2007 From: ericclack at googlemail.com (EricClack) Date: 16 Jan 2007 14:36:03 -0800 Subject: mod_python example code Message-ID: <1168986961.027481.107300@a75g2000cwd.googlegroups.com> I've been using Python, MySQL, Apache and mod_python for some time now and think that it is a great combination for many projects. However I have been constantly surprised by the lack of any visible mod_python examples on the web. So, I've released my framework in the hope that it will be useful to others and of course to seek comments, corrections, criticisms from the community. This framework takes care of: - templating (using Cheetah) - querying MySQL (using Manager objects) - sending emails - debugging (to Apache log or stdout) - users and security Download the framework from this page: http://www.bright-interactive.com/python/ It's licensed under the GPL. I hope to add more examples over the coming months (e.g. demonstrating emails, etc). However, the full source code is provided and its reasonably well commented, so you can always discover for yourself. -Eric. From Eric_Dexter at msn.com Sun Jan 14 02:40:23 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 13 Jan 2007 23:40:23 -0800 Subject: Tkinter code (with pmw) executing to soon please help In-Reply-To: <mailman.2704.1168749021.32031.python-list@python.org> References: <1168746063.322340.10410@l53g2000cwa.googlegroups.com> <mailman.2704.1168749021.32031.python-list@python.org> Message-ID: <1168760423.608731.213550@a75g2000cwd.googlegroups.com> > button[num] = Tkinter.Button(frame,text = returnstring, > command=callback(returnstring))# I understand this part of it def callback(text): def handler(event): print text It stopped calling it automaticaly but will not do anything when I click on the button. Does something have to change on this line as well. button[num] = Tkinter.Button(frame,text = returnstring, > command=callback(returnstring) Gabriel Genellina wrote: > <Eric_Dexter at msn.com> escribi? en el mensaje > news:1168746063.322340.10410 at l53g2000cwa.googlegroups.com... > > > Instead of creating my buttons and waiting for me to press them to > > execute they are executing when I create them and won't do my callback > > when I press them.. thanks for any help in advance > > This is a very frequent beginner's mistake. You are *calling* the event > handler at the moment you create the buttons. You have to provide a > *callable* but not call it yet. > > > button[num] = Tkinter.Button(frame,text = returnstring, > > command=callback(returnstring))# > > So `callback` should return a function, like this: > > def callback(text): > def handler(event): > print text > > -- > Gabriel Genellina From steve at REMOVEME.cybersource.com.au Sun Jan 14 22:43:55 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 15 Jan 2007 14:43:55 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <pan.2007.01.15.03.43.54.630644@REMOVEME.cybersource.com.au> On Sun, 14 Jan 2007 15:32:35 -0800, dickinsm wrote: > Suppose you're writing a class "Rational" for rational numbers. The > __init__ function of such a class has two quite different roles to > play. First, it's supposed to allow users of the class to create > Rational instances; in this role, __init__ is quite a complex beast. > It needs to allow arguments of various types---a pair of integers, a > single integer, another Rational instance, and perhaps floats, Decimal > instances, and suitably formatted strings. It has to validate the > input and/or make sure that suitable exceptions are raised on invalid > input. And when initializing from a pair of integers---a numerator > and denominator---it makes sense to normalize: divide both the > numerator and denominator by their greatest common divisor and make > sure that the denominator is positive. > > But __init__ also plays another role: it's going to be used by the > other Rational arithmetic methods, like __add__ and __mul__, to return > new Rational instances. For this use, there's essentially no need for > any of the above complications: it's easy and natural to arrange that > the input to __init__ is always a valid, normalized pair of integers. > (You could include the normalization in __init__, but that's wasteful Is it really? Have you measured it or are you guessing? Is it more or less wasteful than any other solution? > when gcd computations are relatively expensive and some operations, > like negation or raising to a positive integer power, aren't going to > require it.) So for this use __init__ can be as simple as: > > def __init__(self, numerator, denominator): > self.numerator = numerator > self.denominator = denominator > > So the question is: (how) do people reconcile these two quite > different needs in one function? I have two possible solutions, but > neither seems particularly satisfactory, and I wonder whether I'm > missing an obvious third way. The first solution is to add an > optional keyword argument "internal = False" to the __init__ routine, > and have all internal uses specify "internal = True"; then the > __init__ function can do the all the complicated stuff when internal > is False, and just the quick initialization otherwise. But this seems > rather messy. Worse than messy. I guarantee you that your class' users will, deliberately or accidentally, end up calling Rational(10,30,internal=True) and you'll spent time debugging mysterious cases of instances not being normalised when they should be. > The other solution is to ask the users of the class not to use > Rational() to instantiate, but to use some other function > (createRational(), say) instead. That's ugly! And they won't listen. > Of course, none of this really has anything to do with rational > numbers. There must be many examples of classes for which internal > calls to __init__, from other methods of the same class, require > minimal argument processing, while external calls require heavier and > possibly computationally expensive processing. What's the usual way > to solve this sort of problem? class Rational(object): def __init__(self, numerator, denominator): print "lots of heavy processing here..." # processing ints, floats, strings, special case arguments, # blah blah blah... self.numerator = numerator self.denominator = denominator def __copy__(self): cls = self.__class__ obj = cls.__new__(cls) obj.numerator = self.numerator obj.denominator = self.denominator return obj def __neg__(self): obj = self.__copy__() obj.numerator *= -1 return obj I use __copy__ rather than copy for the method name, so that the copy module will do the right thing. -- Steven D'Aprano From fccoelho at gmail.com Wed Jan 24 19:25:19 2007 From: fccoelho at gmail.com (Flavio) Date: 24 Jan 2007 16:25:19 -0800 Subject: raise UnicodeError, "label too long" References: <1169672223.231030.262610@l53g2000cwa.googlegroups.com> <pan.2007.01.24.21.23.25.331322@gmx.net> <1169675004.099912.79520@v33g2000cwv.googlegroups.com> <45B7D4F7.9020308@v.loewis.de> Message-ID: <1169684719.607504.307310@l53g2000cwa.googlegroups.com> something like this, for instance: http://.wikipedia.org/wiki/Copper%28II%29_hydroxide but even url with any non-ascii characters such as this http://.wikipedia.org/wiki/Ammonia also fail when passed to urlopen : File "/usr/lib/python2.4/encodings/idna.py", line 72, in ToASCII raise UnicodeError, "label too long" UnicodeError: label too long very strange, because I tried other unicode urls from the python console like this urllib2.urlopen(u'www.google.com') and it works normally: Martin v. L?wis escreveu: > Flavio schrieb: > > What I am doing is very simple: > > > > I fetch an url (html page) parse it using BeautifulSoup, extract the > > links and try to open each of the links, repeating the cycle. > > > > Beautiful soup converts the html to unicode. That's why when I try to > > open the links extracted from the page I get this error. > > > > This is bad, since some links do contain strings with non-ascii > > characters. > > Please try answering the exact question that Marc asked: > what is an example for unicode string that triggers the > exception? > > Regards, > Martin From gert.cuykens at gmail.com Mon Jan 22 15:55:13 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Mon, 22 Jan 2007 21:55:13 +0100 Subject: instancemethod In-Reply-To: <45b51298$0$8289$426a74cc@news.free.fr> References: <mailman.2961.1169417800.32031.python-list@python.org> <45b51298$0$8289$426a74cc@news.free.fr> Message-ID: <ef60af090701221255m575701e7jaae6bd858acbea5c@mail.gmail.com> Reading all of the above this is the most simple i can come too. import MySQLdb class Db: def __init__(self,server,user,password,database): self._db=MySQLdb.connect(server , user , password , database) self._db.autocommit(True) self.cursor=self._db.cursor() def excecute(self,cmd): self.cursor.execute(cmd) self.rowcount=int(self.cursor.rowcount) def close(self): self.cursor.close() self._db.close() def __del__(self): try: self.close() except: pass if __name__ == '__main__': gert=Db('localhost','root','******','gert') gert.excecute('select * from person') for row in gert.cursor: print row This must be the most simple it can get right ? PS i didn't understand the __getattr__ quit well but i thought it was just to overload the privies class From dimitri.pater at gmail.com Wed Jan 24 18:52:18 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Thu, 25 Jan 2007 00:52:18 +0100 Subject: Python does not play well with others In-Reply-To: <17846.49695.213309.406485@montanaro.dyndns.org> References: <NXyth.51860$wc5.6792@newssvr25.news.prodigy.net> <17846.49695.213309.406485@montanaro.dyndns.org> Message-ID: <e75321bd0701241552u3c670184k7643dfbde6d44b26@mail.gmail.com> On 1/24/07, skip at pobox.com <skip at pobox.com> wrote: > > > John> MySQLdb has version and platform compatibility problems. > > Got specific examples? I've successfully used MySQLdb on Linux, Mac and > Solaris with no compatibility problems at all. I have been using MySLQdb also on Linux, Mac *and* Windows in various applications and never encountered compatibility problems in the last two or three years. best regards, Dimitri --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070125/f787245b/attachment.html> From jan.dries at dcube-resource.be Sat Jan 13 19:22:54 2007 From: jan.dries at dcube-resource.be (Jan Dries) Date: Sun, 14 Jan 2007 01:22:54 +0100 Subject: sqlobject 0.8.0b1 and python 2.5 In-Reply-To: <5f56302b0701130618u4f47296fv73426a32064e81cd@mail.gmail.com> References: <5f56302b0701130618u4f47296fv73426a32064e81cd@mail.gmail.com> Message-ID: <45A977DE.4030900@dcube-resource.be> Daniel Nogradi wrote: > Since I'm starting to use sqlobject right now, if there is a > similar ORM tool that is comparable but up to date and actively > developed, that would be an option too. (Things like SQLAlchemy are > waaaay to complicated and complex for my needs. :)) Perhaps not really an answer to your question, but is SQLAlchemy really so much more complicated than SQLObject? I've been using SQLObject a lot the past few years, but have recently migrated some of my code to SQLAlchemy for various reasons: it's much better documented, has more features, performs better and at least seems to be more actively developed. My conclusion was that I had to make very little changes to make my SQLObject code work with SQLAlchemy. Defining your classes/tables is more verbose, but still straightforward. And by using the proper defaults and things like assign_mapper, actual use of SQLAlchemy comes very close to SQLObject. Regards, Jan From larry.bates at websafe.com Tue Jan 30 11:52:18 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 30 Jan 2007 10:52:18 -0600 Subject: data design In-Reply-To: <45bf69cb$0$31452$426a74cc@news.free.fr> References: <45bf5763$0$22792$426a34cc@news.free.fr> <45BF5CC5.5060306@websafe.com> <45bf69cb$0$31452$426a74cc@news.free.fr> Message-ID: <45BF77C2.7020306@websafe.com> Imbaud Pierre wrote: > Larry Bates a ?crit : >> Imbaud Pierre wrote: >> >>> The applications I write are made of, lets say, algorithms and data. >>> I mean constant data, dicts, tables, etc: to keep algorithms simple, >>> describe what is peculiar, data dependent, as data rather than "case >>> statements". These could be called configuration data. >>> >>> The lazy way to do this: have modules that initialize bunches of >>> objects, attributes holding the data: the object is somehow the row of >>> the "table", attribute names being the column. This is the way I >>> proceeded up to now. >>> Data input this way are almost "configuration data", with 2 big >>> drawbacks: >>> - Only a python programmer can fix the file: this cant be called a >>> configuration file. >>> - Even for the author, these data aint easy to maintain. >>> >>> I feel pretty much ready to change this: >>> - make these data true text data, easier to read and fix. >>> - write the module that will make python objects out of these data: >>> the extra cost should yield ease of use. >>> >>> 2 questions arise: >>> - which kind of text data? >>> - csv: ok for simple attributes, not easy for lists or complex >>> data. >>> - xml: the form wont be easier to read than python code, >>> but an xml editor could be used, and a formal description >>> of what is expected can be used. >>> - how can I make the data-to-object transformation both easy, and able >>> to spot errors in text data? >>> >>> Last, but not least: is there a python lib implementing at least part >>> of this dream? >> >> >> Use the configurations module. It was built to provide a way to parse >> configuration files that provide configuration data to program. It is >> VERY fast so the overhead to parse even thousands of lines of config >> data is extremely small. I use it a LOT and it is very flexible and >> the format of the files is easy for users/programmers to work with. >> >> -Larry Bates > U mean configParser? Otherwise be more specific (if U dont mind...) Sorry, yes I meant configParser module. Had a little "brain disconnect" there. -Larry From bearophileHUGS at lycos.com Mon Jan 15 03:38:56 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Jan 2007 00:38:56 -0800 Subject: Class list of a module In-Reply-To: <mailman.2729.1168848415.32031.python-list@python.org> References: <OF26C969EB.BAFF11A0-ONC1257264.002723D2-C1257264.0028BCA1@ an.cit.alcatel.fr> <OF26C969EB.BAFF11A0-ONC1257264.002723D2-C1257264.0028BCA1@an.cit.alcatel.fr> <mailman.2729.1168848415.32031.python-list@python.org> Message-ID: <1168850336.276790.73810@38g2000cwa.googlegroups.com> Gabriel Genellina: > >import inspect > def getClassList(aModule): > return [cls for cls in vars(aModule).itervalues() > if inspect.isclass(cls)] This is short enough too: from inspect import isclass getclasses = lambda module: filter(isclass, vars(module).itervalues()) Bye, bearophile From robin at alldunn.com Sun Jan 21 18:31:03 2007 From: robin at alldunn.com (Robin Dunn) Date: Sun, 21 Jan 2007 15:31:03 -0800 Subject: [ANN] wxPython 2.8.1.1 Message-ID: <45B3F7B7.4030006@alldunn.com> Announcing ---------- The 2.8.1.1 release of wxPython is now available for download at http://wxpython.org/download.php. This release adds a few minor enhancements and a number of bug fixes designed to further stabalize the 2.8.x release series. Source code is available, as well as binaries for both Python 2.4 and 2.5, for Windows and Mac, as well some pacakges for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. 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 GTK2, and Mac OS X 10.3+, in most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.1.1 ------------------ wxMSW: Fix lack of spin control update event when control lost focus Added a typeId property to the PyEventBinder class that holds the eventType ID used for that event. So when you need the eventType (such as when sending your own instance of standard events) you can use, for example, wx.EVT_BUTTON.typeId instead of wx.wxEVT_COMMAND_BUTTON_CLICKED. Note that there are a few composite events, such as EVT_MOUSE and EVT_SCROLL, that will actually bind multiple event types at once, and in these cases the typeId property may not give you what you want. You should use te component events in these cases. PyCrust now has an option for showing/hiding the notebook. wxMSW: Corrected drawing of bitmaps for disabled menu items. Enhanced the wx.lib.mixins.inspect module. In addition to showing a PyCrust window it is now a widget browser, which provides a tree loaded up with all the widgets in the app, optionally with the sizers too, and also a panel displaying the properties of the selected window. Run the demo and type Ctrl-Alt-I keystroke (or Cmd-Alt-I on the Mac) to see how it works. You can add this to your own apps with just a few lines of code. Added wx.SearchCtrl.[Get|Set]DescriptiveText wxMac: Added support for the wx.FRAME_FLOAT_ON_PARENT style. wxMac: the popups used for call tips and autocomplete lists in StyledTextCtrl (such as in PyShell) are now top-level float-on-parent windows so they are no longer clipped by the bounds of the stc window. Added EVT_TASKBAR_CLICK and use it to show taskbar icon menu on right button release, not press, under MSW (bug 1623761) Added wx.TreeCtrl.CollapseAll[Children]() and IsEmpty() methods Fix wx.MDIChidFrame.GetPosition() (patch 1626610) Fix attribute memory leak in wx.grid.Grid::ShowCellEditControl() (patch 1629949) wxGTK: Fix for controls on a toolbar being the full height of the toolbar instead of their natural height. wx.lib.customtreectrl patches from Andrea Gavana. wxMac: Applied patch #1622389, fixing two memory leaks in GetPartialTextExtents. More fixes for the native wx.ListCtrl on Mac. Added wx.aui.AuiNotebook.GetAuiManager(). Added wx.aui.AuiMDIParentFrame and wx.aui.AuiMDIChildFrame, which essentially implement the MDI interface using a normal wx.Frame and a wx.aui.AuiNotebook. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From steve at REMOVEME.cybersource.com.au Tue Jan 23 02:30:34 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 23 Jan 2007 18:30:34 +1100 Subject: OT: Trolling for fun and profit Message-ID: <pan.2007.01.23.07.30.34.764450@REMOVEME.cybersource.com.au> Oh the shame... I've been caught out by a troll. I received what I thought was a genuine email from a regular poster on this list (not one of the really high volume posters, but someone who is around enough that his name would be familiar) who, I thought, was trying to make a genuine point about posting styles, conventions and tolerance of different opinions. I disagreed with the point, but thought it was genuine and so responded to it. He's just replied to me with this comment: "The only reason I'm top-posting here is because it so obviously pushes your buttons." I well and truly got caught. I can't say its the first time I've ever been caught by a troll, but it hasn't been for many years, so I have to grudgingly give him points. He fooled me but good. I won't mention any names -- he doesn't need the publicity. But if you get an emotionally distraught email off-list from a regular, particularly if it goes on about tolerance and "why can't we all just get along?", be aware that there's a good chance he's just trolling. -- Steven D'Aprano From s.mientki at id.umcn.nl Wed Jan 31 09:05:10 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 31 Jan 2007 15:05:10 +0100 Subject: another newbie question: why should you use "*args" ? In-Reply-To: <1170247737.232403.114850@k78g2000cwa.googlegroups.com> References: <e1f8c$45c08065$83aef404$7421@news1.tudelft.nl> <1170247737.232403.114850@k78g2000cwa.googlegroups.com> Message-ID: <56667$45c0a216$83aef404$16652@news1.tudelft.nl> > It's bad practice to use built-ins like 'list' as a regular variable > name. > ok, but it was just an example (in practice, I always use very long names ;-) > >> # calling method 1: >> execute (S[0], S[4] ) >> >> # calling method 2: >> execute ( ( S[0], S[4] ) ) >> > > Let's take a look at those side-by-side: > execute (S[0], S[4] ) > execute ( ( S[0], S[4] ) ) > > Now, which one *looks* better? > > >> # or *the extra flexibility) >> mylist = ( S[0], S[4] ) >> execute ( mylist ) >> > > Also, take into consideration the opposite end of the pole; you have > your list of arguments (args), and your about to call a function that > was declared something like this: > def someFunction(arg1, arg2, arg3): > # etc. > Which is clearer? > someFunction(*args) > someFunction(args[0], args[1], args[2]) > > And if you've got a variable number of arguments, it becomes virtually > impossible to avoid using the *args syntax. > > # So with this construct, I have all flavours: def chunk_plot(*args): if len(args)==1: my_example_var = args[0] else: my_example_var = args for i in range ( len ( my_example_var ) ): ... do something with my_example_var [i] # calling the procedure chunk_plot (S[1], S[4]) chunk_plot ( ( S[1], S[4] ) ) my_action_list = ( S[1], S[2] ) chunk_plot ( my_action_list ) And sorry, no need for kwargs for now ;-) thanks guys, Stef -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070131/d3f994e0/attachment.html> From cvanarsdall at mvista.com Tue Jan 30 14:19:40 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 30 Jan 2007 11:19:40 -0800 Subject: The reliability of python threads In-Reply-To: <epmk7l$7k4$2@sea.gmane.org> References: <mailman.3092.1169657938.32031.python-list@python.org> <ep8gue$3tu$1@panix3.panix.com> <45B90118.5010408@mvista.com> <epmk7l$7k4$2@sea.gmane.org> Message-ID: <45BF9A4C.3070002@mvista.com> Steve Holden wrote: > [snip] > > Are you using memory with built-in error detection and correction? > > You mean in the hardware? I'm not really sure, I'd assume so but is there any way I can check on this? If the hardware isn't doing that, is there anything I can do with my software to offer more stability? -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From beliavsky at aol.com Tue Jan 2 00:20:31 2007 From: beliavsky at aol.com (Beliavsky) Date: 1 Jan 2007 21:20:31 -0800 Subject: Writing more efficient code In-Reply-To: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> References: <mailman.2185.1167676577.32031.python-list@python.org> <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1167715231.450710.325860@42g2000cwt.googlegroups.com> If in the newsgroup comp.lang.x somone asks how to do y, and you suggest using language z, without answering their question, which was how to do it in x, you will likely just annoy people and perhaps make it even less likely that they will try z. I have my own favorite language z and have not always heeded the above advice, but I think the principle is still correct. From webraviteja at gmail.com Mon Jan 1 01:44:55 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 31 Dec 2006 22:44:55 -0800 Subject: C app and Python In-Reply-To: <1167577264.741127.284630@48g2000cwx.googlegroups.com> References: <1167577264.741127.284630@48g2000cwx.googlegroups.com> Message-ID: <1167633895.328649.145780@i12g2000cwa.googlegroups.com> Vertilka wrote: > Hi, > I need to create an application that the user ask for python script to > run. > this script will call the C application functions (in my app. the > function will draw on screen). > > Do I need to create an extension ? Note that this is not a DLL, but a C > application. > or I need to embed Python in my C application. > > Thanks, > Vertilka A bit of both :-) http://www.python.org/doc/ext/extending-with-embedding.html Ravi Teja. From rrr at ronadam.com Tue Jan 16 07:32:12 2007 From: rrr at ronadam.com (Ron Adam) Date: Tue, 16 Jan 2007 06:32:12 -0600 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: <1168931486.610893.250040@38g2000cwa.googlegroups.com> References: <teTqh.2829$bp4.2788@bignews4.bellsouth.net> <mailman.2744.1168901460.32031.python-list@python.org> <pan.2007.01.16.02.07.39.523409@REMOVEME.cybersource.com.au> <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> <mailman.2762.1168916788.32031.python-list@python.org> <1168931486.610893.250040@38g2000cwa.googlegroups.com> Message-ID: <eoigss$mc4$1@sea.gmane.org> Carl Banks wrote: > Ron Adam wrote: >> There have been times where I would like assert to be a little more assertive >> than it is. :-) >> >> ie.. not being able to turn them off with the -0/-00 switches, and having them >> generate a more verbose traceback. > > Personally, I'd rather see it get less assertive, i.e., having it only > work in a special debugging mode. That way people who haven't RTFM > don't use it to make sure their input is correct. > > > Carl Banks Well, the manual could be improved in this area quite a bit. There also really need to be easier to find examples for both assert and warnings use. But it does only work in a special debugging mode. Didn't you RTFM? ;-) http://docs.python.org/ref/assert.html It just happens this mode is turned on by default. So you would like this to be turned off by default. I agree. I think there may be a way to change pythons default startup behavior for this. Warnings generated by warn() on the other hand can be silenced, but not completely ignored. But I also think they could be a more useful and flexible tool for debugging purposes. http://docs.python.org/lib/warning-functions.html I have to admit that part of why assert seems wrong to me is the meaning of the word implies something you shouldn't be able to ignore. While warnings seem like something that can be disregarded. I think maybe the best way to use both may be to combine them... assert <condition> warn(...) But I'm not sure that doesn't have problems of it's own. <shrug> Cheers, Ron From __peter__ at web.de Thu Jan 18 07:14:07 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Jan 2007 13:14:07 +0100 Subject: classes: need for an explanation References: <1169121502.779509.138890@m58g2000cwm.googlegroups.com> Message-ID: <eonoa0$dlm$01$1@news.t-online.com> 0k- wrote: > class Thing(object): > props?=?{} > def?__init__(self): > self.props["text"]?=?TxtAttr("something?important") > > t1 = Thing() > t2 = Thing() > > t2.props["text"].value = "another string" > > print "t1: %s\nt2: %s" % (t1.props["text"].value, > t2.props["text"].value) > > the above code outputs: > > t1: another string > t2: another string > > so the problem i cannot get through is that both t1 and t2 have the > same attr class instance. > could somebody please explain me why? :) Putting an assignment into the class body makes the name a /class/ attribute which is shared by all instances of the class: >>> class Thing: ... props = {} # this is a class attribute ... >>> t1, t2 = Thing(), Thing() >>> t1.props is t2.props True The solution is to move the attribute creation into the initializer: >>> class Thing: ... def __init__(self): ... self.props = {} # an instance attribute ... >>> t1, t2 = Thing(), Thing() >>> t1.props is t2.props False Peter From wolfgang.grafen at marconi.com Mon Jan 15 07:37:40 2007 From: wolfgang.grafen at marconi.com (Wolfgang Grafen) Date: Mon, 15 Jan 2007 13:37:40 +0100 Subject: indentation in python In-Reply-To: <1168750708.059882.107750@v45g2000cwv.googlegroups.com> References: <1168742956.828457.287610@m58g2000cwm.googlegroups.com> <1168750708.059882.107750@v45g2000cwv.googlegroups.com> Message-ID: <45AB7594.5000004@marconi.com> Dan Bishop wrote: > On Jan 13, 8:49 pm, "lee" <libi... at gmail.com> wrote: >> Can anyone tell me the basics about indentation in python......how we >> use it in loops and constructs..etc.... > > It's just like indentation in other languages, except that it's > syntactically required. > The indent rule is minimal: - indent the following line after a colon (:) - dedent when you leave that block to the level you wish to continue - you cannot have an empty block; use pass or None for an otherwise empty block - as always: have fun! From __peter__ at web.de Fri Jan 26 13:19:15 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Jan 2007 19:19:15 +0100 Subject: Handling empty form fields in CGI References: <mailman.3207.1169834026.32031.python-list@python.org> Message-ID: <epdgma$old$03$1@news.t-online.com> Christopher Mocock wrote: > Bit of a python newbie so need a little help with a CGI script I'm > trying to write. I've got it working fine as long as the fields of the > form are filled in correctly, however I need to be able to accept blank > entries. Therefore I want to convert any empty entries to an empty string. > > For example, if I call the following CGI script as: > > http://localhost/cgi-bin/test.cgi?myfield=hello > > ...it prints hello in the browser. But if I call it as: > > http://localhost/cgi-bin/test.cgi?myfield= > > I get an exception. I want it to treat myfield as an empty string and > not throw an exception. > > Any suggestions? You can catch the exception: def test(): try: value = form["myfield"].value except KeyError: value = "" print value or use form.getlist("myfield") and then check the length of the returned list of values. With both options you also have to decide what to do when 'myfield' is given twice: http://localhost/cgi-bin/test.cgi?myfield=42&myfield=24 Peter From robert.kern at gmail.com Sun Jan 21 18:22:22 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 Jan 2007 17:22:22 -0600 Subject: Reading Fortran Data In-Reply-To: <1169420913.789301.227430@11g2000cwr.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> <1169420913.789301.227430@11g2000cwr.googlegroups.com> Message-ID: <ep0sjp$hl4$1@sea.gmane.org> Eric_Dexter at msn.com wrote: > I don't know if this is helpfull or not but (or for that matter > current). http://cens.ioc.ee/projects/f2py2e/ offers some suggestions > and it looks like you can use it with c code also. f2py has been folded into numpy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From osv at javad.com Wed Jan 10 14:06:08 2007 From: osv at javad.com (Sergei Organov) Date: Wed, 10 Jan 2007 22:06:08 +0300 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <mailman.2408.1168248992.32031.python-list@python.org> <Xns98B269DCC12Fduncanbooth@127.0.0.1> <entr6s$ovo$1@news.albasani.net> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <eo38f1$6cu$1@gemini.csx.cam.ac.uk> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> <eo3bgm$c98$1@gemini.csx.cam.ac.uk> Message-ID: <eo3df0$2vk$1@sea.gmane.org> nmm1 at cus.cam.ac.uk (Nick Maclaren) writes: > In article <1168452879.866265.36880 at i39g2000hsf.googlegroups.com>, > "sturlamolden" <sturlamolden at yahoo.no> writes: [...] > |> I wonder if too much emphasis is put on thread programming these days. > |> Threads may be nice for programming web servers and the like, but not > |> for numerical computing. Reading books about thread programming, one > |> can easily get the impression that it is 'the' way to parallelize > |> numerical tasks on computers with multiple CPUs (or multiple CPU > |> cores). But if threads are inherently designed and implemented to stay > |> idle most of the time, that is obviously not the case. > > You have to distinguish "lightweight processes" from "POSIX threads" > from the generic concept. It is POSIX and Microsoft threads that are > inherently like that, Do you mean that POSIX threads are inherently designed and implemented to stay idle most of the time?! If so, I'm afraid those guys that designed POSIX threads won't agree with you. In particular, as far as I remember, David R. Butenhof said a few times in comp.programming.threads that POSIX threads were primarily designed to meet parallel programming needs on SMP, or at least that was how I understood him. -- Sergei. From mike.klaas at gmail.com Wed Jan 24 18:59:16 2007 From: mike.klaas at gmail.com (Klaas) Date: 24 Jan 2007 15:59:16 -0800 Subject: The reliability of python threads In-Reply-To: <mailman.3105.1169664198.32031.python-list@python.org> References: <mailman.3092.1169657938.32031.python-list@python.org> <ep841j$anu$1@gemini.csx.cam.ac.uk> <mailman.3095.1169659417.32031.python-list@python.org> <ep883i$iom$1@gemini.csx.cam.ac.uk> <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <mailman.3105.1169664198.32031.python-list@python.org> Message-ID: <1169683156.325444.185530@a34g2000cwb.googlegroups.com> On Jan 24, 10:43 am, "Carl J. Van Arsdall" <cvanarsd... at mvista.com> wrote: > Chris Mellon wrote: > > On 24 Jan 2007 18:21:38 GMT, Nick Maclaren <n... at cus.cam.ac.uk> wrote: > > >> [snip] > > > I'm aware of the issues with the POSIX threading model. I still stand > > by my statement - bringing up the problems with the provability of > > correctness in the POSIX model amounts to FUD in a discussion of > > actual problems with actual code. > > > Logic and programming errors in user code are far more likely to be > > the cause of random errors in a threaded program than theoretical > > (I've never come across a case in practice) issues with the POSIX > > standard.Yea, typically I would think that. The problem I am seeing is > incredibly intermittent. Like a simple pyro server that gives me a > problem maybe every three or four months. Just something funky will > happen to the state of the whole thing, some bad data, i'm having an > issue tracking it down and some more experienced programmers mentioned > that its most likely a race condition. THe thing is, I'm really not > doing anything too crazy, so i'm having difficult tracking it down. I > had heard in the past that there may be issues with threads, so I > thought to investigate this side of things. > > It still proves difficult, but reassurance of the threading model helps > me focus my efforts. > > > Emphasizing this means that people will tend to ignore bugs as being > > "the fault of POSIX" rather than either auditing their code more > > carefully, or avoiding threads entirely (the second being what I > > suspect your goal is). > > > As a last case, I should point out that while the POSIX memory model > > can't be proven safe, concrete implementations do not necessarily > > suffer from this problem.Would you consider the Linux implementation of threads to be concrete? > > -carl > > -- > > Carl J. Van Arsdall > cvanarsd... at mvista.com > Build and Release > MontaVista Software From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 25 10:33:36 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 25 Jan 2007 16:33:36 +0100 Subject: While loop with "or"? Please help! In-Reply-To: <1169730632.268861.321070@a75g2000cwd.googlegroups.com> References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> <1169730632.268861.321070@a75g2000cwd.googlegroups.com> Message-ID: <45b8cdcd$0$25927$426a74cc@news.free.fr> wittempj at hotmail.com a ?crit : > > On Jan 25, 11:26 am, wd.jons... at gmail.com wrote: (snip) >> #Runs the buildfinder function >> usrinp = buildfinder() >> >> def buildwhiler(): >> >> while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM >> print "Enter Y or N!" >> usr = str(raw_input('Y/N: ')) >> else: >> code continues > > also note that your naming of variables contains two different names > for one variable... Actually, usrinp and usr are really two different vars - the first one being global... And FWIW, it's one of the "other errors" I mentionned earlier <g> From steve at REMOVEME.cybersource.com.au Thu Jan 4 00:31:55 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 04 Jan 2007 16:31:55 +1100 Subject: code optimization (calc PI) / Full Code of PI calc in Python and C. References: <hOPmh.82$9v1.124@nntpserver.swip.net> <5020j6F1du59cU1@mid.uni-berlin.de> <XgQmh.98$9v1.124@nntpserver.swip.net> <459BFDCB.4000503@sschwarzer.net> <UGXmh.194$9v1.250@nntpserver.swip.net> <1167872076.937415.250340@11g2000cwr.googlegroups.com> <cuYmh.201$9v1.239@nntpserver.swip.net> Message-ID: <pan.2007.01.04.05.31.54.549423@REMOVEME.cybersource.com.au> On Thu, 04 Jan 2007 02:10:44 +0100, Michael M. wrote: > print "\nTiming a 1 million loop 'for loop' ..." > start = time.clock() > for x in range(1000000): > y = x # do something Why not "pass # do nothing"? > end = time.clock() > print "Time elapsed = ", end - start, "seconds" Are you aware that you're timing the CREATION of a rather large list, as well as the loop? [snip code] > #print "".join(pi) > print pi > > end_prg = time.clock() and also the time taken for I/O printing the digits? That can be quite slow. For timing functions and small snippets of code, you should investigate the timeit module. It is very flexible, and will often give more accurate results than roll-you-own timing. For example: >>> import timeit >>> t = timeit.Timer("for i in range(1000000): pass", "pass") >>> t.timeit(100) # time the loop one hundred times 29.367985010147095 Now compare it to the speed where you only create the list once. >>> t = timeit.Timer("for i in L: pass", "L = range(1000000)") >>> t.timeit(100) 16.155359983444214 -- Steven D'Aprano From deets at nospam.web.de Wed Jan 3 12:33:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Jan 2007 18:33:38 +0100 Subject: Unsubscribing from the list References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <ene064$bm5$1@sea.gmane.org> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <enghj3$qhf$1@sea.gmane.org> <mailman.2244.1167841321.32031.python-list@python.org> Message-ID: <5027niF1dm0f8U1@mid.uni-berlin.de> Dotan Cohen wrote: > On 03/01/07, Fredrik Lundh <fredrik at pythonware.com> wrote: >> if you're unable to follow written instructions, how on earth did you >> manage to subscribe to this list ? >> >> </F> >> > > Actually, I'm a compete idiot and I always post to the mailing list > instead of RTFM or STFW. What's the name of that big big website? > goobble or something?!? > > The first sentance under the heading "Python-list Subscribers" is: > The subscribers list is only available to the list administrator. > Admin address: Password: > > As I'm not an admin, I read no further. Well, you should work on your reading skills then - just a sentence further the solution lures: """ Python-list Subscribers (The subscribers list is only available to the list administrator.) Enter your admin address and password to visit the subscribers list: Admin address: Password: Visit Subscriber List To unsubscribe from Python-list, get a password reminder, or change your subscription options enter your subscription email address: Unsubscribe or edit options """ So, how about entering your email in that last input field, and press "Unsubscribe or edit options" Diez From martin at v.loewis.de Mon Jan 29 16:13:19 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 29 Jan 2007 22:13:19 +0100 Subject: python 2.3 module ref In-Reply-To: <6178735.qJi6sMvOM0@teancum> References: <6178735.qJi6sMvOM0@teancum> Message-ID: <45BE636F.6070304@v.loewis.de> David Bear schrieb: > Since redhat packages python2.3 with their distro (RHEL 4..) I was looking > for a module reference for that version. Looking at python.org I only see > current documentation. > > any pointers to a 2.3 module ref? http://www.python.org/doc/2.3/ http://www.python.org/doc/2.3/lib/lib.html Regards, Martin From rrr at ronadam.com Tue Jan 16 10:33:32 2007 From: rrr at ronadam.com (Ron Adam) Date: Tue, 16 Jan 2007 09:33:32 -0600 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: <slrneqpld3.1r4.horpner@FIAD06.norwich.edu> References: <teTqh.2829$bp4.2788@bignews4.bellsouth.net> <mailman.2744.1168901460.32031.python-list@python.org> <pan.2007.01.16.02.07.39.523409@REMOVEME.cybersource.com.au> <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> <mailman.2762.1168916788.32031.python-list@python.org> <1168931486.610893.250040@38g2000cwa.googlegroups.com> <mailman.2772.1168951023.32031.python-list@python.org> <slrneqpld3.1r4.horpner@FIAD06.norwich.edu> Message-ID: <eoirgr$6gn$1@sea.gmane.org> Neil Cerutti wrote: > On 2007-01-16, Ron Adam <rrr at ronadam.com> wrote: >> I have to admit that part of why assert seems wrong to me is >> the meaning of the word implies something you shouldn't be able >> to ignore. While warnings seem like something that can be >> disregarded. > > Experienced C coders expect assert to behave like that. > > The only reason (I know of) to turn off error checking is to > optimize. However, removing tests won't usually make a big enough > speed difference to be worth the burthen of testing two different > versions of the same source code. Ah... but that's the irony. The whole purpose of the existence of the second version you refer to, is to better check the first version. These checks should not change the flow of code that is executed! The problem with assert as a debugging tool, is it *can* change the execution flow by raising a catchable exception. So you do have *two* versions that may not behave the same. Like I suggested earlier, assert should not be turned off *ever*, but should be considered a nicer way to generate exceptions to do value checks. And warnings should never change code execution order, but we should be able to completely turn them off on the byte code level like asserts are when the -O command line option is given. I believe both of these features would be used a lot more if they where like this. > So to me the assert statement is either dubious syntax-sugar or > dangerous, depending on Python's command line arguments. Yep.. unless you use them in a very limited way. > The warning module would seem to have limited applications. > Searching my Python distribution shows that it's used for > deprecation alerts, and elsewhere for turning those selfsame > alerts off. How copacetic! It is the null module. ;-) I think you understand the point I'm trying to make. :-) Ron From gagsl-py at yahoo.com.ar Fri Jan 26 22:21:02 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Jan 2007 00:21:02 -0300 Subject: Calling python function from C and import questions References: <1169844647.673719.25810@j27g2000cwj.googlegroups.com> Message-ID: <epeh72$nok$1@sea.gmane.org> <sndive at gmail.com> escribi? en el mensaje news:1169844647.673719.25810 at j27g2000cwj.googlegroups.com... > Is there a better way to make a call from C than > > PyRun_SimpleString("import > foo_in_python\nfoo_in_python.bar(whatever)\n"); > > I already imported the foo_in_python using PyImport_ImportModule > and wonder why do I need to keep importing it every time I'm > calling a python function in that module. Sure. Use the reference to the module that you got from PyImport_ImportModule; you call a method using PyObject_CallMethod or similar. > Does anyone know why does the import tries to load .py files before > .pyc? It has to be sure that the .pyc is up-to-date; the .pyc contains a magic number and the modification time of the corresponding .py -- Gabriel Genellina From caleb.hattingh at gmail.com Tue Jan 23 06:34:08 2007 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 23 Jan 2007 03:34:08 -0800 Subject: I need suggests In-Reply-To: <1169551582.196591.48140@v45g2000cwv.googlegroups.com> References: <1169551582.196591.48140@v45g2000cwv.googlegroups.com> Message-ID: <1169552048.842059.237800@d71g2000cwa.googlegroups.com> Pat wrote: > I have to do a big programm. Could someone give me some suggests about > IDE (on Linux) and books to learn. http://groups.google.com/groups/search?q=python+ide&qt_s=Search Lots and lots to read :) Caleb From w.richert at gmx.net Thu Jan 11 16:01:37 2007 From: w.richert at gmx.net (Willi Richert) Date: Thu, 11 Jan 2007 22:01:37 +0100 Subject: Pythonic A*-Algorithm Message-ID: <200701112201.37129.w.richert@gmx.net> Hi, I'm looking for an A* implementation in Python (at least some wrapper around a C lib). So far I've only found http://arainyday.se/projects/python/AStar/ which looks not so promising. http://wiki.python.org/moin/PythonGraphApi lists all major available graph libraries in Python, hoping to find a path to some standard Python graph library (as DBAPI). But none of them seems to have a decent A*-implementation (at least with Fibonacci-heap, as pqueue is supposed to be). I know I could implement it myself as it is not that complicated, but I would rather like to align my project to some already existing and well established graph library containing A*. Thanks, wr From arkanes at gmail.com Tue Jan 9 11:02:06 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 9 Jan 2007 10:02:06 -0600 Subject: Execute binary code In-Reply-To: <1168355051.339026.211830@v33g2000cwv.googlegroups.com> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> <slrneq6vga.tcj.grahn+nntp@frailea.sa.invalid> <1168355051.339026.211830@v33g2000cwv.googlegroups.com> Message-ID: <4866bea60701090802w5d55d72boc40180f1ed4c6dbc@mail.gmail.com> On 9 Jan 2007 07:04:11 -0800, sturlamolden <sturlamolden at yahoo.no> wrote: > > Jorgen Grahn wrote: > > > For what it's worth[1], under Unix it /is/ impossible. The only way to bring in > > new code (short of dynamic libraries) is to call exec(2) or its variations, > > and all need a file system object to load the code from. > > The x86 processor cannot tell the difference between code segments and > data segments. If the executable code is stored in string, all you need > is a pointer to the string holding the code. You can cast the string > address to a function pointer (possibly through a void* if the compiler > complains), then dereference (call) the function pointer. > > Trojans, viruses and JIT compilers do this all the time. Here is an > (untested) example: > > static PyObject* > call_code_in_string(PyObject *self, PyObject *args) > { > char *s; > int size; > int arg1, arg2, arg3; > typedef int (*func_t)(int,int,int); > func_t pfunc; > if(!PyArg_ParseTuple(args, "s#(iii)", &s, &size, &arg1, &arg2, > &arg3)) return NULL; > pfunc = (func_t)((void *)s); /* if it fails, try > memcpy(&pfunc,&s,sizeof(void*)) instead */ > return PyInt_FromLong((long)pfunc(arg1, arg2, arg3)); > } > > Another possibility would be to just return the string address, and > then make the call possibly using ctypes. > > static PyObject* > get_string_addr(PyObject *self, PyObject *args) > { > char *s; > int size; > if(!PyArg_ParseTuple(args, "s#", &s, &size)) return NULL; > return PyInt_FromLong((long)((void*)s)); > } > This works fine if the binary data is "pure" asm, but the impresssion the OP gave is that it's a compiled binary, which you can't just "jump into" this way. From bruno.desthuilliers at websiteburo.com Fri Jan 19 08:34:48 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Fri, 19 Jan 2007 14:34:48 +0100 Subject: variable scope In-Reply-To: <be5994b50701181059qe0fff1elab2930eb6729d790@mail.gmail.com> References: <mailman.2873.1169134976.32031.python-list@python.org> <45af9ac4$0$290$426a34cc@news.free.fr> <be5994b50701181059qe0fff1elab2930eb6729d790@mail.gmail.com> Message-ID: <45B0C8F8.50703@websiteburo.com> gonzlobo a ?crit : <ot> Please keep this on clpy... </ot> > Sorry, but I don't understand. I *should* pass firstMsg to the > function like I did (PID_MinMax(firstMsg)), correct? Yes. > Then I should > pass the variable back to the main loop by 'return firstMsg', correct? s/variable/value/ Yes, you have to return the value from your function. But then, if you don't store this value somewhere, it's lost. What you have to understand is that you actually have *2* variables named 'firstMsg' : one in the 'main loop', and one in PID_MinMax(). Rebinding the second name has no impact on the first. So you have to explicitely assign the return value of PID_MinMax() to the main loop's firstMsg variable. Else, this value is simply discarded. HTH From ptmcg at austin.rr.com Sat Jan 27 14:18:24 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Jan 2007 11:18:24 -0800 Subject: extracting from web pages but got disordered words sometimes In-Reply-To: <1169896727.567159.239160@a34g2000cwb.googlegroups.com> References: <1169896727.567159.239160@a34g2000cwb.googlegroups.com> Message-ID: <1169925504.228972.275890@q2g2000cwa.googlegroups.com> On Jan 27, 5:18 am, "Frank Potter" <could.... at gmail.com> wrote: > There are ten web pages I want to deal with. > fromhttp://www.af.shejis.com/new_lw/html/125926.shtml > to http://www.af.shejis.com/new_lw/html/125936.shtml > > Each of them uses the charset of Chinese "gb2312", and firefox > displays all of them in the right form, that's readable Chinese. > > My job is, I get every page and extract the html title of it and > dispaly the title on linux shell Termial. > > And, my problem is, to some page, I get human readable title(that's in > Chinese), but to other pages, I got disordered word. Since each page > has the same charset, I don't know why I can't get every title in the > same way. > > Here's my python code, get_title.py : > > [CODE] > #!/usr/bin/python > import urllib2 > from BeautifulSoup import BeautifulSoup > > min_page=125926 > max_page=125936 > > def make_page_url(page_index): > return ur"".join([ur"http://www.af.shejis.com/new_lw/ > html/",str(page_index),ur".shtml"]) > > def get_page_title(page_index): > url=make_page_url(page_index) > print "now getting: ", url > user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > headers={'User-Agent':user_agent} > req=urllib2.Request(url,None,headers) > response=urllib2.urlopen(req) > #print response.info() > page=response.read() > > #extract tile by beautiful soup > soup=BeautifulSoup(page) > full_title=str(soup.html.head.title.string) > > #title is in the format of "title --title" > #use this code to delete the "--" and the duplicate title > title=full_title[full_title.rfind('-')+1::] > > return title > > for i in xrange(min_page,max_page): > print get_page_title(i) > [/CODE] > > Will somebody please help me out? Thanks in advance. This pyparsing solution seems to extract what you were looking for, but I don't know if this will render to Chinese or not. -- Paul from pyparsing import makeHTMLTags,SkipTo import urllib titleStart,titleEnd = makeHTMLTags("title") scanExpr = titleStart + SkipTo("- -",include=True) + SkipTo(titleEnd).setResultsName("titleChars") + titleEnd def extractTitle(htmlSource): titleSource = scanExpr.searchString(htmlSource, maxMatches=1)[0] return titleSource.titleChars for urlIndex in range(125926,125936+1): url = "http://www.af.shejis.com/new_lw/html/%d.shtml" % urlIndex pg = urllib.urlopen(url) html = pg.read() pg.close() print url,':',extractTitle(html) Gives: http://www.af.shejis.com/new_lw/html/125926.shtml : GSM?????????????? http://www.af.shejis.com/new_lw/html/125927.shtml : GSM ?????????????????? http://www.af.shejis.com/new_lw/html/125928.shtml : GSM?????????? http://www.af.shejis.com/new_lw/html/125929.shtml : GSM???????????????????? http://www.af.shejis.com/new_lw/html/125930.shtml : GSM??????????- ??GSM??GPRS??3G ???????? http://www.af.shejis.com/new_lw/html/125931.shtml : GSM????? ????????????????????????????????? http://www.af.shejis.com/new_lw/html/125932.shtml : ???? ???????????????????? http://www.af.shejis.com/new_lw/html/125933.shtml : GSM??????????????? ????????? http://www.af.shejis.com/new_lw/html/125934.shtml : GSM????????????? ??????????????????? http://www.af.shejis.com/new_lw/html/125935.shtml : GSM??????WCDMA?????????? http://www.af.shejis.com/new_lw/html/125936.shtml : GSM?????????????? From no-spam at no-spam-no-spam.invalid Mon Jan 1 09:10:41 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Mon, 01 Jan 2007 15:10:41 +0100 Subject: OO question In-Reply-To: <1167623232.105052.203550@42g2000cwt.googlegroups.com> References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> Message-ID: <enb4p9$9ei$1@news.albasani.net> fejkadress at hushmail.com wrote: > If I want to save all addresses to disk, I can have a method, say, > save() of AddressBook. But then what? What is a good object oriented > approach? Should each Address object take care of saving itself to the > file, with a method like writetofile(filename), or should the class > AddressBook take care of the saving and ask each object for its data? The OO religion likes to provide a big ego to objects. And be aware! All these egos then want to itch the programmer with question marks for years! And there are programming languages which draw more attention to what some unsolicited objects want, than to what the programmer wants. Python is not so. Remember, you are the boss. You say: "I want to save all addresses to disk". I'd say: Just dump them to disk unless you feel a functional need in order to make it more indirect. Robert From paddy3118 at netscape.net Thu Jan 25 15:46:50 2007 From: paddy3118 at netscape.net (Paddy) Date: 25 Jan 2007 12:46:50 -0800 Subject: The reliability of python threads In-Reply-To: <7xsldy7u6f.fsf@ruckus.brouhaha.com> References: <mailman.3092.1169657938.32031.python-list@python.org> <ep841j$anu$1@gemini.csx.cam.ac.uk> <mailman.3095.1169659417.32031.python-list@python.org> <ep883i$iom$1@gemini.csx.cam.ac.uk> <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <mailman.3105.1169664198.32031.python-list@python.org> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <ep9t4g$uf$1@gemini.csx.cam.ac.uk> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> <epb0s7$g2s$1@gemini.csx.cam.ac.uk> <1169754601.992058.205640@q2g2000cwa.googlegroups.com> <7xsldy7u6f.fsf@ruckus.brouhaha.com> Message-ID: <1169758010.223732.272340@k78g2000cwa.googlegroups.com> On Jan 25, 8:00 pm, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > "Paddy" <paddy3... at netscape.net> writes: > > No, you should think of the service that needs to be up. You seem to be > > talking about how it can't be fixed rather than looking for ways to > > keep things going. > But you're proposing cargo cult programming. i don't know that term. What I'm proposing is that if, for example, a process stops running three times in a year at roughly three to four months intervals , and it should have stayed up; then restart the server sooner, at aa time of your choosing, whilst taking other measures to investicate the error. > There is no reason > whatsoever to expect that restarting the server now and then will help > the problem in the slightest. Thats where we most likely differ. The problem is only indirecctly the program failing. the customer wants reliable service. Which you can get from unreliable components. It happens all the time in firmware controlled systems that periodically reboot themselves as a matter of course. > Nick used the fancy term Poisson > process but it just means that the probability of failure at any > moment is independent of what's happened in the past, like the > spontaneous radioactive decay of an atom. It's not like a mechanical > system where some part gradually gets worn out and eventually breaks, > so you can prevent the failure by replacing the part every so often. Whilst you sit agreeing on how many fairys can dance on the end of a pin or not Your company could be loosing customers. You and Nick seem to be saying it *must* be Poisson, therefore we can't do... > > > A little learning is fine but "it can't theoretically be fixed" is > > no solution.The best you can do is identify the unfixable situations precisely and > work around them. Precision is important. I'm sorry, but your argument reminds me of when Western statistical quality control first met with the Japanese Zero defects methodologies. We had argued ourselves into accepting a certain amount of defective cars getting out to customers as the result of our theories. The Japanese practices emphasized *no* defects were acceptable at the customer, and they seemed to deliver better made cars. > > The next best thing is have several servers running simultaneously, > with failure detection and automatic failover. Yah, finally. I can work with that > > If a server is failing at random every few months, trying to prevent > that by restarting it every so often is just shooting in the dark. "at random" - "every few months" Me thinking it happens "every few months" allows me to search for a fix. If thinking it happens "at random" leads you to a brick wall, then switch! > Think of your server stopping now and then because there's a power > failure, where you get power failures every few months on the average. > Shutting down your server once a month, unplugging it, and plugging it > back in will do nothing to prevent those outages. You need to either > identify and fix whatever is causing the power outages, or install a > backup generator. Yep. I also know that a mad bloke entering the server room with a hammer every three to four months is also not likely to be fixed by restarting the server every two months ;-) - Paddy. From sturlamolden at yahoo.no Fri Jan 12 21:18:32 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 12 Jan 2007 18:18:32 -0800 Subject: What is a perl hash in python In-Reply-To: <mailman.2653.1168622715.32031.python-list@python.org> References: <8301441.post@talk.nabble.com> <mailman.2653.1168622715.32031.python-list@python.org> Message-ID: <1168654709.254087.310500@m58g2000cwm.googlegroups.com> Karyn Williams wrote: > I am new to Pyton. I am trying to modify and understand a script someone > else wrote. I am trying to make sense of the following code snippet. I know > line 7 would be best coded with regex. I first would like to understand > what was coded originally. thelistOut looks like a hash to me (I'm more > familiar with perl). thelistOut seems to be a list of tuples. It also seems that one of the tuple elements are a list containing a single string. To be honest, this is one of the most ugly examples of Python code I have ever seen. I am not sure I would trust code written like this at all. One can very often tell the competence of the programmer from the looks of the code. To answer the subject: An associative container in Python is called a 'dictionary'. CPython dictonaries are implemented using hash tables (and one of the fastest hashing algorithms known to man). There is nothing in the Python semantics that mandates this particular implementation of dictionaries, though. Balanced binary trees could have been used instead of hashes, as they usually are in STL's associative containers, but in CPython a dictionary is implemented with a hash table under the hood. Dictionaries work like this: mydict = { key1 : val1, key2 : val2, key3 : val3 } oldval3 = mydict[key3] mydict[key3] = newval3 mydict[key4] = val4 From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 3 14:05:40 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 03 Jan 2007 20:05:40 +0100 Subject: array of class / code optimization References: <mailman.2221.1167763760.32031.python-list@python.org> <AOPmh.83$9v1.124@nntpserver.swip.net> Message-ID: <502d44F1d5nvlU2@mid.individual.net> mm wrote: > But I was looking for a "struct" equivalent like in c/c++. > And/or "union". I can't find it. class Honk(object): pass test = Honk() test.spam = 4 test.eggs = "Yum" Is it this what you're looking for? > Maybe you know a source (URL) "Python for c/c++ programmers" or > things like that. Have a look at "Learning Python" by Mark Lutz and David Ascher. I found it very helpful because they often refer to C/C++. Regards, Bj?rn -- BOFH excuse #344: Network failure - call NBC From banaouas.medialog at wanadoo.fr Tue Jan 16 18:45:53 2007 From: banaouas.medialog at wanadoo.fr (m.banaouas) Date: Wed, 17 Jan 2007 00:45:53 +0100 Subject: urllib2 and HTTPBasicAuthHandler In-Reply-To: <mailman.2789.1168970662.32031.python-list@python.org> References: <45acf775$0$5070$ba4acef3@news.orange.fr> <mailman.2789.1168970662.32031.python-list@python.org> Message-ID: <45ad6309$1$27408$ba4acef3@news.orange.fr> Max, I verified and determined that Zope realm is "Zope", by tcp spy tool witch shows me the server headers. Actually, I tried differents ways without success. It seems like it's not so easy to negociate a basic authentication process with urllib2, while it's based on very simple specifications, however urllib2 is considered as one of the most powerfull library in its category. You suggest to use default realm: # this creates a password manager passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # because we have put None at the start it will always use this username/password combination passman.add_password(None, auth_url, data['user'] , data['pass']) # create the AuthHandler auth_handler = urllib2.HTTPBasicAuthHandler(passman) # build an 'opener' using the handler we've created opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) req = urllib2.Request(url) f = urllib2.urlopen(req) data = f.read() print data but it doesn't work: urllib2.HTTPError: HTTP Error 401: Unauthorized Max Erickson a ?crit : > "m.banaouas" <banaouas.medialog at wanadoo.fr> wrote: > >> Hi all, >> I started to use urllib2 library and HTTPBasicAuthHandler class >> in order to authenticate with a http server (Zope in this case). >> I don't know why but it doesn't work, while authenticating with >> direct headers manipulation works fine! >> > ... >> port':'8080','path':'manage','realm':'Zope'} >> url = '%(prot)s://%(host)s:%(port)s/%(path)s' % data > ... > > Are you certain that the realm on the server matches 'Zope'? > > HTTPBasicAuthHandler uses the realm to look for the password, if the > realm the server provides is different, urllib2 will respond as if it > does not have a user/password. > > If you are only doing one request, it isn't that big a deal; if you > are doing many requests or want urllib2 to handle the response for > other reseans, you can use a default realm, see the bottom of this > example: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305288 > > (The advantage of using a default rather than making sure the realm is > correct is that it can change and you won't have to do anything) > > > > max > From toreriks at hotmail.com Thu Jan 25 05:16:31 2007 From: toreriks at hotmail.com (Tor Erik Soenvisen) Date: Thu, 25 Jan 2007 10:16:31 +0000 (UTC) Subject: str and __setitem__ Message-ID: <Xns98C372B2DD26Btoreriknpolarno@129.242.5.222> Hi, What do I need to do to make the code below work as expected: class str2(str): def __setitem__(self, i, y): assert type(y) is str assert type(i) is int assert i < len(self) self = self[:i] + y + self[1+i:] a = str2('123') a[1] = '1' print a 123 The print statement should return 113 Regards tores From snewman18 at gmail.com Wed Jan 10 12:38:43 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: 10 Jan 2007 09:38:43 -0800 Subject: Universal Feed Parser - How do I keep attributes? Message-ID: <1168450723.340213.235690@o58g2000hsb.googlegroups.com> I'm trying to use FeedParser to parse out Yahoo's Weather Data. I need to capture some attribute values, but it looks like FeedParser strips them out. Is there any way to keep them? XML Snippet: ... <yweather:location city="Sunnyvale" region="CA" country="US" /> ... When I try to get the value, it's empty: >>> d = feedparser.parse('http://weather.yahooapis.com/forecastrss?p=94089') >>> d.feed.yweather_location u'' From wangshuhao at sina.com Wed Jan 24 02:58:02 2007 From: wangshuhao at sina.com (Wang Shuhao) Date: Wed, 24 Jan 2007 15:58:02 +0800 Subject: sys.path issue in cygwin Message-ID: <001501c73f8d$63edb590$14fd0179@WANGSHUHAO> I successfully built and installed Python 2.2.3 in cygwin. But there is something wrong in the sys.path. I use following statments for a test. >>> import sys >>> print sys.path ['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', 'C/lib/python2.2/lib-tk' , '\\Python24/lib/python2.2/lib-dynload'] >>> To keep the question simple, I've set PATH= in cygwin.bat to avoid python initialze sys.path from Windows' PATH environment. Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is installed in /usr/local/lib/python2.2.3. The result of the issue is that when you run a program python can't find the module. So what I really want to know is where these path came from and how to fix it. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070124/835eba3d/attachment.html> From http Thu Jan 25 16:16:59 2007 From: http (Paul Rubin) Date: 25 Jan 2007 13:16:59 -0800 Subject: The reliability of python threads References: <mailman.3092.1169657938.32031.python-list@python.org> <ep841j$anu$1@gemini.csx.cam.ac.uk> <mailman.3095.1169659417.32031.python-list@python.org> <ep883i$iom$1@gemini.csx.cam.ac.uk> <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <mailman.3105.1169664198.32031.python-list@python.org> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <ep9t4g$uf$1@gemini.csx.cam.ac.uk> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> <epb0s7$g2s$1@gemini.csx.cam.ac.uk> <1169754601.992058.205640@q2g2000cwa.googlegroups.com> <7xsldy7u6f.fsf@ruckus.brouhaha.com> <1169758010.223732.272340@k78g2000cwa.googlegroups.com> Message-ID: <7xveiu4xis.fsf@ruckus.brouhaha.com> "Paddy" <paddy3118 at netscape.net> writes: > > But you're proposing cargo cult programming. > i don't know that term. http://en.wikipedia.org/wiki/Cargo_cult_programming > What I'm proposing is that if, for example, a process stops running > three times in a year at roughly three to four months intervals , > and it should have stayed up; then restart the server sooner, at aa > time of your choosing, What makes you think that restarting the server will make it less likely to fail? It sounds to me like there's zero evidence of that, since you say "roughly three or four month intervals" and talk about threading and race conditions. If it's failing every 3 months, 15 days and 2.43 hours like clockwork, that's different, sure, restart it every three months. But the description I see so far sounds like a random failure caused by some events occurring with low enough probability that they only happen on average every few months of operation. That kind of thing is very common and is often best diagnosed by instrumenting the hell out of the code. > > There is no reason whatsoever to expect that restarting the server > > now and then will help the problem in the slightest. > Thats where we most likely differ. Do you think there is a reason to expect that restarting the server will help the problem in the slightest? I realize you seem to expect that, but you have not given a REASON. That's what I mean by cargo cult programming. > Whilst you sit agreeing on how many fairys can dance on the end of a > pin or not Your company could be loosing customers. You and Nick seem > to be saying it *must* be Poisson, therefore we can't do... I dunno about Nick, I'm saying it's best to assume that it's Poisson and do whatever is necessary to diagnose and fix the bug, and that the voodoo measure you're proposing is not all that likely to help and it will take years to find out whether it helps or not (i.e. restarting after 3 months and going another 3 months without a failure proves nothing). > I'm sorry, but your argument reminds me of when Western statistical > quality control first met with the Japanese Zero defects methodologies. > We had argued ourselves into accepting a certain amount of defective > cars getting out to customers as the result of our theories. The > Japanese practices emphasized *no* defects were acceptable at the > customer, and they seemed to deliver better made cars. I don't see your point. You're the one who wants to keep operating defective software instead of fixing it. > "at random" - "every few months" > Me thinking it happens "every few months" allows me to search for a > fix. If thinking it happens "at random" leads you to a brick wall, > then switch! But you need evidence before you can say it happens every few months. Do you have, say, a graph of the exact dates and times of failure, the number of requests processed so far, etc.? If it happened at some exact or almost exact uniform time interval or precisely once every 1.273 million requests or whatever, that tells you something. But the earlier description didn't sound like that. Restarting the server is not much better than carrying a lucky rabbit's foot. From robert.kern at gmail.com Fri Jan 5 01:19:31 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 05 Jan 2007 00:19:31 -0600 Subject: What is proper way to require a method to be overridden? In-Reply-To: <103909CE-118D-428A-B865-46896785A30E@cs.hmc.edu> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> <459DCC77.2030708@gmx.net> <103909CE-118D-428A-B865-46896785A30E@cs.hmc.edu> Message-ID: <enkqln$sp4$1@sea.gmane.org> belinda thom wrote: > I imagine the NotImplementedError is actually a defined object, but I > really don't know. It is. > So, back to my question: is a catalog of standard python errors > available? I've looked on the python site but had no success. http://docs.python.org/lib/module-exceptions.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From the_pakage_4u at yahoo.com Sat Jan 13 15:28:28 2007 From: the_pakage_4u at yahoo.com (GGG Promo) Date: Sat, 13 Jan 2007 20:28:28 GMT Subject: ^*^*^^ Free Girls Gone Wild Videos ^*^*^*^ Message-ID: <Mhbqh.623445$1T2.14028@pd7urf2no> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070113/6fdd863c/attachment.html> From gagsl-py at yahoo.com.ar Wed Jan 3 19:02:37 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Jan 2007 21:02:37 -0300 Subject: type classobj not defined? In-Reply-To: <eec9f8ee0701030857o6218f87bpc40f63c62575098d@mail.gmail.co m> References: <eec9f8ee0701030857o6218f87bpc40f63c62575098d@mail.gmail.com> Message-ID: <7.0.1.0.0.20070103204620.05595be8@yahoo.com.ar> At Wednesday 3/1/2007 13:57, Wesley Brooks wrote: > >type(b) ><type 'classobj'> > >But the following fails: > > >type(b) == classobj >Traceback (most recent call last): > File "<stdin>", line 1, in ? >NameError: name 'classobj' is not defined Do you want to test if you got a `b` class, or just for any class? See inspect.isclass for the latter. >For the time being I'll use b.__name__ == b to ensure I'm getting the >right class. Is there a reason why the other types such as bool are >defined but classobj isn't? Usually, Python code doesn't care if you pass the exact class designed. If a function writes some text to a file that it gets as an argument, it doesn't care whether it gets a file object or some other kind of object, as far as it has a suitable write() method. If you positively have to check for the class, checking types with == is not a good idea. Use isinstance or issubclass instead, they check for derived classes too. A derived class can (or could) always be used wherever a base class is suitable. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From stuart at bmsi.com Thu Jan 25 21:12:40 2007 From: stuart at bmsi.com (Stuart D. Gathman) Date: Thu, 25 Jan 2007 21:12:40 -0500 Subject: doctest problem with null byte Message-ID: <pan.2007.01.26.02.12.39.635773@bmsi.com> I am trying to create a doctest test case for the following: def quote_value(s): """Quote the value for a key-value pair in Received-SPF header field if needed. No quoting needed for a dot-atom value. >>> quote_value(r'abc\def') '"abc\\\\\\\\def"' >>> quote_value('abc..def') '"abc..def"' >>> quote_value('') '""' >>> quote_value('-all\x00') '"-all\\\\\\\\x00"' ... However, doctest does *not* like the null byte in the example (yes, this happens with real life input): ********************************************************************** File "/home/stuart/pyspf/spf.py", line 1453, in spf.quote_value Failed example: quote_value('-all') Exception raised: Traceback (most recent call last): File "/var/tmp/python2.4-2.4.4c1-root/usr/lib/python2.4/doctest.py", line 1248, in __run compileflags, 1) in test.globs TypeError: compile() expected string without null bytes ********************************************************************** How can I construct a test cast for this? -- Stuart D. Gathman <stuart at bmsi.com> Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From rpdooling at gmail.com Fri Jan 12 16:37:15 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 12 Jan 2007 13:37:15 -0800 Subject: What is a perl hash in python In-Reply-To: <mailman.2674.1168636455.32031.python-list@python.org> References: <fPQph.10106$yx6.6344@newsread2.news.pas.earthlink.net> <8301441.post@talk.nabble.com> <mailman.2653.1168622715.32031.python-list@python.org> <mailman.2674.1168636455.32031.python-list@python.org> Message-ID: <1168637835.447276.21620@v45g2000cwv.googlegroups.com> Karyn Williams wrote: > > For future reference, why is direct use of the string module frowned upon, > and what does one use instead ? > Karyn, http://docs.python.org/lib/node42.html rd From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 12:26:20 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 18:26:20 +0100 Subject: Books,resources.. References: <entoit$d5b$1@aioe.org> Message-ID: <50fd5sF1fki7dU1@mid.individual.net> Tarique wrote: > so can you please suggest some standard references for python > considering that i have some programming experience I like "Learning Python" by Mark Lutz and David Ascher. They refer to C/C++ many times. Also try "Dive into Python" for a more fast-paced introduction and "Python in a Nutshell" for a good reference. Regards, Bj?rn -- BOFH excuse #380: Operators killed when huge stack of backup tapes fell over. From jgodoy at gmail.com Sat Jan 13 08:22:00 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 13 Jan 2007 11:22:00 -0200 Subject: Barcode recognition in Python References: <1168676514.115592.181620@v45g2000cwv.googlegroups.com> Message-ID: <87zm8n6ozr.fsf@gmail.com> "PaoloB" <pibizza at gmail.com> writes: > Hi everyone, > > I am searching for a python library for barcode recognition. We have > developed a rather complex application for document tracking and > document management in python/Zope, called PAFlow (www.paflow.it: > sorry, most of the information is in Italian...). > > As our project is completely free software, we will need a library that > is free software too. > > Is there something like this in python ? Sorry, but what do you mean by "barcode recognition"? A barcode reader already decodes the barcode and sends the decoded output. If it is one plugged in a keyboard port, for example, reading the barcode or typing the "message" is exactly the same thing. Or are you willing some kind of OCR to process the barcodes without a barcode reader (why having barcodes then?)? -- Jorge Godoy <jgodoy at gmail.com> From sean at datafly.net Thu Jan 25 20:08:48 2007 From: sean at datafly.net (Sean Schertell) Date: Fri, 26 Jan 2007 10:08:48 +0900 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: <ep8ucs$g4a$1@sea.gmane.org> References: <ep60jp$63v$1@aioe.org> <45b72b0d$0$5107$ba4acef3@news.orange.fr> <e75321bd0701241533ie528b15p42a0a75bd0666c2d@mail.gmail.com> <49E1CCC0-D22F-4411-B192-429E42045578@datafly.net> <ep8ucs$g4a$1@sea.gmane.org> Message-ID: <0680E0C6-89DC-47F0-9010-2230C916951E@datafly.net> That's really exciting! Thanks for the tip. Sean On Jan 25, 2007, at 9:42 AM, Robert Kern wrote: > Sean Schertell wrote: >> Not to totally hijack the thread -- but since you're all talking >> about best GUI frameworks. Any thoughts on the best looking framework >> for OS X only? Is there any way to write little Python apps that will >> launch in OS X using OS X widgets? > > Use PyObjC. You have full access to the Cocoa framework. > > http://pyobjc.sourceforge.net/ > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a > harmless enigma > that is made terrible by our own mad attempt to interpret it as > though it had > an underlying truth." > -- Umberto Eco > > -- > http://mail.python.org/mailman/listinfo/python-list :::: DataFly.Net :::: Complete Web Services http://www.datafly.net From scott at crybabymaternity.com Sun Jan 7 13:33:50 2007 From: scott at crybabymaternity.com (scott at crybabymaternity.com) Date: 7 Jan 2007 10:33:50 -0800 Subject: Newbie XML SAX Parsing: How do I ignore an invalid token? In-Reply-To: <459f5e14$0$17107$9b622d9e@news.freenet.de> References: <1168033818.692201.183790@11g2000cwr.googlegroups.com> <mailman.2354.1168037149.32031.python-list@python.org> <1168054226.290465.325910@s34g2000cwa.googlegroups.com> <459f5e14$0$17107$9b622d9e@news.freenet.de> Message-ID: <1168194830.741912.300290@51g2000cwl.googlegroups.com> Thanks, I'll work with the file on the file system, then parse it with SAX. Is there a Pythonic way to read the file and identify any illegal XML characters so I can strip them out? this would keep my program more flexible - if the vendor is going to allow one illegal character in their document, there's no way of knowing if another one will pop up later. Thanks! Martin v. L?wis wrote: > scott at crybabymaternity.com schrieb: > > My original posting has a funky line break character (it appears as an > > ascii square) that blows up my program, but it may or may not show up > > when you view my message. > > Looking at your document, it seems that this "funky line break > character" is character \x1E, which, in latin-1, means "record > separator". It's indeed ill-formed to use it in XML. > > > Is there a way to account for the invalid token in the error handler? > > Not with a standard XML parser, no. The error you describe is a "fatal > error", and that's not something parsing can recover from. I recommend > that you filter this character out before passing it to the XML parser. > You can use the IncrementalParser interface to do so. > > Regards, > Martin From practicalperl at gmail.com Sat Jan 20 06:00:09 2007 From: practicalperl at gmail.com (Jm lists) Date: Sat, 20 Jan 2007 19:00:09 +0800 Subject: Does eval has the same features as Perl's? In-Reply-To: <pan.2007.01.20.10.45.31.333567@REMOVE.THIS.cybersource.com.au> References: <mailman.2937.1169285428.32031.python-list@python.org> <pan.2007.01.20.10.45.31.333567@REMOVE.THIS.cybersource.com.au> Message-ID: <fbe35f750701200300kf758edftcd2f9888d396d4a8@mail.gmail.com> Thank you.I'm just learning Python and want to make something clear to me.:) 2007/1/20, Steven D'Aprano <steve at remove.this.cybersource.com.au>: > On Sat, 20 Jan 2007 17:30:24 +0800, Jm lists wrote: > > > Hello members, > > > > I want to know does the "eval" in python have the same features as in > > Perl (capture errors)? > > > > For example,in perl I can wrote: > > > > $re = eval { 1 / 0 }; > > > > Though 1/0 is a fatal error but since it's in "eval" block so the perl > > interpreter doesn't get exit. > > How hard would it be to actually try it? > > >>> eval("1/0") > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<string>", line 1, in <module> > ZeroDivisionError: integer division or modulo by zero > > It took about three seconds to actually test it. > > eval has many security risks -- as a rule, you should never pass strings > you've got from the user to eval, unless you want the user to p0wn your > computer. It is harder than you might think to make eval safe -- you > should seriously consider it an advanced tool, not a basic tool. As a > newbie, you should work under the following rule: > > "If I think I need to use eval, I'm probably wrong." > > I've been using Python for seven or eight years, and I don't think I've > ever used eval in serious code. > > Now, suppose you find yourself wanting to use eval. You've considered the > above rule carefully, and decided that it doesn't apply in this case. > You've been careful to use it only on safe strings, not arbitrary strings > from users. How do you use eval so it captures errors? > > try: > eval("1/0") > except ZeroDivisionError: # capture only one error > pass > > > or something like this: > > try: > eval("something or other goes here") > except Exception: # capture any error > pass > > > > -- > Steven. > > -- > http://mail.python.org/mailman/listinfo/python-list > From stj911 at rock.com Tue Jan 30 16:52:35 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 30 Jan 2007 13:52:35 -0800 Subject: Secret Technology of THERMATE and 911 Crime In-Reply-To: <1170127646.046184.213690@k78g2000cwa.googlegroups.com> References: <1170127646.046184.213690@k78g2000cwa.googlegroups.com> Message-ID: <1170193955.284265.13850@a75g2000cwd.googlegroups.com> Thanks for this great link On Jan 29, 7:27 pm, therm... at india.com wrote: > Excellent Technology, and photos: > > http://stj911.org/jones/focus_on_goal.html > > As scientists, we look at the evidence, perform experiments, and apply > the Scientific Method. The Greek method was to look at the evidence > (superficially) and then try to explain things through logic and > debate. The Greeks came up with various ideas in this way -- such as > the geocentric theory in which the Earth was at the center of the > universe, and all the stars and planets revolved around the earth. > There were problems with this geocentric explanation, but Plato > insisted that they must "save the hypothesis," and plausible > explanations were found to account for anomalies -- i such as the > retrograde motion of Mars. The philosophical debates and discussions > were seemingly endless; the Dark Ages ensued. > > Along came Copernicus, Galileo, Newton and others with their > experiments and observations, and the centuries-old Greek philosophy- > based notions began to crumble. Galileo observed through a telescope > that Jupiter had moons -- which revolved around Jupiter (not the > Earth). He was threatened with torture if he did not recant his > explanation (that the Earth was not at the center). He suffered house > arrest but not torture as he quietly continued his experiments. > > In the lifetime of Newton, another experimenter who challenged the > Greek approach, the scientific community worked out a system whereby > scientific studies would be published after review by peers -- > qualified experts who could judge the quality of the research. Peer- > reviewed technical journals arose and the peer-review process brought > order to the relative chaos of work up to that time. Now experiments > could be done and written up, then peer-reviewed and published. Peer- > reviewed papers would draw the attention of others. To give an example > of using the modern scientific method, a few colleagues and I are > doing experiments and making observations in a scientific approach to > what really happened at the World Trade Center. It is NOT merely a > plausible explanation or debates about "possibilities" that we seek. > Rather, having seen strong indications of foul play (see > journalof911studies.com/Intersecting_facts_and_Theories_on_911.pdf ) > we are looking for hard evidence that would clearly verify an > intentional crime beyond that of 19 hijackers. Ours is a forensic > investigation, looking for a "smoking gun," which would then lead to a > serious criminal investigation. > > I do not plan to make a career out of 9/11 research, and I am not > making money from my investigations anyway. We need a formal, solid > investigation of the 9/11 crimes committed, not a long-term study > which endlessly debates all alternatives. I seek such solid evidence > of an insider crime (beyond a reasonable doubt) that some of us will > successfully demand a criminal investigation to confront key > individuals who may have insider information -- within one year, if > possible-- not many. > > So what evidence is likely to lead to such a criminal investigation? > > As identified in my talk at the University of California at Berkeley, > there are four areas of 9/11 research that are so compelling that they > may quickly lead to the goal of a solid investigation of 9/11 as an un- > solved crime scene. These four areas are: > > 1. Fall time for WTC 7. > 2. Fall times for the Towers. > 3. Challenging the NIST report and Fact Sheet. > 4. Evidence for use of Thermate reactions: What the WTC dust and > solidified metal reveal. > > * Please note that I do not focus only on the thermate-hypothesis, > and I do research in all four areas above. Details are given in my > talk, available here:www.911blogger.com/node/4622Also: > video.google.com/videoplay?docid=9210704017463126290 ) > > There are other lines that may compel a criminal investigation even > before one of the above "hard science" research lines bears fruit: > > 5. Whistleblower statements -- including some individuals yet to > emerge. > 6. Who made the stock-market "put-option" trades on American and > United Air Lines in the week before 9/11, indicating clear > foreknowledge of the attacks coupled with greed? > 7. The fact that the WTC dust was declared quite safe by the EPA/ > National Security Council when it fact scientists had proven it to be > toxic, and the many people now clamoring for justice after being hurt > and misled. > 8. Calls for impeachment for war issues, e.g., from a state > legislature or Congress, which scrutinizes the "Bush Doctrine," then > opens the 9/11 question. > 9. Pressure from 9/11 Family members, firemen and others for > answers. > 10. Direct appeals to Senators and Congresspersons -- who are > charged with an oversight role. I initiated a Petition to this effect, > demanding release of government-held information related to 9/11, > which has since been signed by over 10,000 people. And I am in contact > now with the Congressman from my state, seeking information and > remedy. > > We have found evidence for thermates in the molten metal seen pouring > from the South Tower minutes before its collapse, in the sulfidation > and high-temperature corrosion of WTC steel, and in the residues found > in the WTC dust. (Our sample originated from an apartment at 113 Cedar > Street across from the WTC; chain of custody direct from the collector > J. MacKinlay to Dr. Steven Jones). Many other details are given in the > peer-reviewed paper here: journalof911studies.com/volume/200609/ > WhyIndeedDidtheWorldTradeCenterBuildingsCompletelyCollapse.pdf . Other > cutter-charges such as HMX and RDX may have also been used; but again, > solid evidence for just one type of incendiary or explosive would be > sufficient to compel a criminal investigation. > > Experiments continue, as shown in the photos below, and the results > are consistent with thermate having been used in on 9/11/2001. We have > a series of experiments planned, along with analyses. This research > takes time. > Above: In a fraction of a second, thermate cuts horizontally through a > steel cup. Notice the high-temperature corrosion which occurred. > > Right: 1999: "Invention offers a thermite based apparatus and method > for cutting target material [eg, steel] of a substantial thickness ... > linear.. cutting action ..." A prototype has been used to cut through > a steel I-beam. > > Below: Proof of Concept. The photograph below shows the one-hole proto- > type device I built to produce a thermate-jet. Thermate is the red > powder in the steel base. The prototype worked well, and the thermate- > jet cut through a piece of structural steel in a fraction of a second. From gagsl-py at yahoo.com.ar Sun Jan 14 11:51:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Jan 2007 13:51:58 -0300 Subject: Decorators inside of class and decorator parameters References: <1168728983.541526.202320@l53g2000cwa.googlegroups.com><mailman.2703.1168747644.32031.python-list@python.org> <1168763727.677028.149640@51g2000cwl.googlegroups.com> Message-ID: <eodn3c$3pc$1@sea.gmane.org> "Michele Simionato" <michele.simionato at gmail.com> escribi? en el mensaje news:1168763727.677028.149640 at 51g2000cwl.googlegroups.com... > Gabriel Genellina wrote: >> see this article by M. Simoniato >> http://www.phyast.pitt.edu/~micheles/python/documentation.html for a >> better >> way using its decorator factory. > > Actually the name is Simionato ;) Oh, sorry! I think I've written it wrong in another place too :( -- Gabriel Genellina From Jeff.Demel at JavelinDirect.com Thu Jan 11 10:22:49 2007 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Thu, 11 Jan 2007 09:22:49 -0600 Subject: Learning Python book, new edition? Message-ID: <136ED738BD4F1545B97E4AC06FF6370734C186@DMSP-MSG-EVS01.mail.pvt> Does anyone know if there's a plan in the works for a new edition of Learning Python? The current edition (2nd) is a few years old and looks like it only covers Python 2.3. Anyone on the list have Lutz's ear? -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From __peter__ at web.de Wed Jan 17 08:46:03 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Jan 2007 14:46:03 +0100 Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: <eol9ac$v3l$02$1@news.t-online.com> Will McGugan wrote: > I'd like a generator that takes a sequence and yields tuples containing > n items of the sqeuence, but ignoring the 'odd' items. For example > > take_group(range(9), 3) -> (0,1,2) (3,4,5) (6,7,8) I like >>> items = range(9) >>> N = 3 >>> zip(*[iter(items)]*N) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] Peter From practicalperl at gmail.com Fri Jan 19 22:51:45 2007 From: practicalperl at gmail.com (Jm lists) Date: Sat, 20 Jan 2007 11:51:45 +0800 Subject: **argv can't work In-Reply-To: <9d6d3deb0701191944k604a6ff8u3cea7c88cbe45f04@mail.gmail.com> References: <fbe35f750701191920g4c28e44bjee5789ff346223b7@mail.gmail.com> <9d6d3deb0701191944k604a6ff8u3cea7c88cbe45f04@mail.gmail.com> Message-ID: <fbe35f750701191951h2dc07237nc96af186793b853e@mail.gmail.com> Thanks for all the kind helps! 2007/1/20, Parthan SR <python.technofreak at gmail.com>: > > > On 1/20/07, Jm lists <practicalperl at gmail.com> wrote: > > hello members, > > > > See my script piece below: > > > > def testB(shift,**argv): > > print "first argument is %s" %shift > > print "all other arguments are:",argv > > > > testB('mails','Jen',' Jen at att.com','Joe','Joe at aol.com') > > > > It can't work at all.please help tell me the reasons.thanks. > > > > > > It works for me, check this one : > > >>> def argtst(x, **y): > ... print "first arument is %s" % x > ... print "other arguments are", y > ... > >>> argtst(x=10,a=1,b=2,c=3) > first arument is 10 > other arguments are {'a': 1, 'c': 3, 'b': 2} > > > (!) : Do not use the name 'argv' for the second argument. > > -- > With Regards, > > TechnoFreak > > From steve at REMOVEME.cybersource.com.au Wed Jan 31 22:11:32 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 01 Feb 2007 14:11:32 +1100 Subject: division by 7 efficiently ??? References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: <pan.2007.02.01.03.11.32.214726@REMOVEME.cybersource.com.au> On Wed, 31 Jan 2007 18:42:54 -0800, krypto.wizard wrote: > How to divide a number by 7 efficiently without using - or / operator. > We can use the bit operators. I was thinking about bit shift operator > but I don't know the correct answer. I'd be surprised if there was a trick for dividing by seven efficiently... it is one of the "difficult" cases. See: http://www.bitwisemag.com/copy/wilf/wilf5.html for a discussion. But even if there is some nifty algorithm for efficiently dividing by seven using bit operators, I don't expect it will work efficiently in Python. The overhead of using objects will probably outweigh any saving you might get by using magic tricks, so you should just use division. It is like using the XOR trick for swapping integers: there's just no point in doing it in Python except as a trick, because it is slower than just swapping them: >>> timeit.Timer("x = x^y; y = x^y; x= x^y", "x, y = 1, 2").repeat() [0.88827300071716309, 0.85192012786865234, 0.81278204917907715] >>> timeit.Timer("x, y = y, x", "x, y = 1, 2").repeat() [0.71292495727539062, 0.65545105934143066, 0.68413901329040527] -- Steven D'Aprano From gagsl-py at yahoo.com.ar Thu Jan 18 10:12:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 12:12:52 -0300 Subject: Asyncore select statement problem References: <1169075120.491855.103200@q2g2000cwa.googlegroups.com> Message-ID: <eoo2pm$rl$1@sea.gmane.org> "JamesHoward" <James.w.Howard at gmail.com> escribi? en el mensaje news:1169075120.491855.103200 at q2g2000cwa.googlegroups.com... >I have a problem with python's asyncore module throwing a bad file > descriptor error. The code might be difficult to copy here, but the > problem is essentially: > > The server wants to sever the connection of an open Asyncore socket. > Calling the socket.close() nor the socket.shutdown(2) calls seem to > work. The only way I can close the connection without creating the > error below is to have the client close the connection. You have to use the dispatcher's close() method, else, the asyncore map won't be updated, keeping a reference to the closed socket. -- Gabriel Genellina From ptmcg at austin.rr.com Wed Jan 24 15:24:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Jan 2007 12:24:31 -0800 Subject: Simple Matrix class In-Reply-To: <mailman.3108.1169668074.32031.python-list@python.org> References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <mailman.3049.1169600368.32031.python-list@python.org> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <mailman.3051.1169604934.32031.python-list@python.org> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> <mailman.3094.1169659321.32031.python-list@python.org> <1169664540.120687.211350@s48g2000cws.googlegroups.com> <mailman.3108.1169668074.32031.python-list@python.org> Message-ID: <1169670271.547292.141110@l53g2000cwa.googlegroups.com> On Jan 24, 1:47 pm, Robert Kern <robert.k... at gmail.com> wrote: > Paul McGuire wrote: > > And the purpose/motivation for "reimplementing it better" would be > > what, exactly? So I can charge double for it? > > So you can have accurate results, and you get a good linear solver out of the > process. The method you use is bad in terms of accuracy as well as efficiency. > Dang, I thought I was testing the results sufficiently! What is the accuracy problem? In my test cases, I've randomly created test matrices, inverted, then multiplied, then compared to the identity matrix, with the only failures being when I start with a singular matrix, which shouldn't invert anyway. One of the main reasons I wrote this was as a simple linear solver for small order problems, so I would like this to at least be able to do _that_. Efficiency aside, I thought I was at least getting the right answer... -- Paul From theller at ctypes.org Tue Jan 2 11:59:38 2007 From: theller at ctypes.org (Thomas Heller) Date: Tue, 02 Jan 2007 17:59:38 +0100 Subject: Python Wrapper for C# Com Object In-Reply-To: <1167313715.296081.133170@n51g2000cwc.googlegroups.com> References: <1167297178.937748.91790@79g2000cws.googlegroups.com> <1167313715.296081.133170@n51g2000cwc.googlegroups.com> Message-ID: <459A8F7A.60405@ctypes.org> bg_ie at yahoo.com schrieb: > bg_ie at yahoo.com skrev: > >> Hi, >> >> I wish to write a Python wrapper for my C# COM object but am unsure >> where to start. I have a dll and a tlb file, and I can use this object >> in C via the following code - >> >> // ConsolApp.cpp : Defines the entry point for the console application. >> // >> #include "stdafx.h" >> #include "windows.h" >> #include "stdio.h" >> #import "C:\Documents and Settings\X\Mina dokument\Visual Studio >> 2005\Projects\X_COMObject\X_COMObject\bin\Debug\X_COMObject.tlb" >> using namespace X_COMObject; >> >> int _tmain(int argc, _TCHAR* argv[]) >> { >> CoInitialize(NULL); >> >> X_COMObject::XCOM_InterfacePtr p(__uuidof(X_COMObject::XCOM_Class)); >> XCOM_Interface *X_com_ptr ; >> X_com_ptr = p ; >> X_com_ptr->SetID(10); >> int x = X_com_ptr->GetID(); >> printf("%d",x); >> getchar(); >> >> return 0; >> } >> >> Can anyone offer me some tips as to how to do this in Python? >> >> Thanks very much for your help, >> >> Barry. > > This is what I've done so far, but I know I'm not doing this correctly. > Can anyone help me out? > > #import pythoncom > #pythoncom.CoInitialize() The above is unneeded if you use comtypes as below (and is unneeded when using pythoncom, as well). > from comtypes.client import GetModule, CreateObject > > module = GetModule("C:\\Documents and Settings\\X\\Mina > dokument\\Visual Studio > 2005\\Projects\\X_COMObject\\X_COMObject\\bin\\Debug\\X_COMObject.tlb") > You don't intantiate the interface, you have to instantiate the COM object. Something like CreateObject("XCOM_Class") but of course you have to use the correct argument in the call - the progid of the COM object. Alternatively you can use the CoClass from the typelibrary, look into the generated module in the comtypes\gen directory for a class derived from comtypes.CoClass. InternetExplorer, for example, can be started in these ways: # using the progid: ie = CreateObject("InternetExplorer.Application") # using the clsid: ie = CreateObject("{0002DF01-0000-0000-C000-000000000046}") # using the coclass from the generated module: mod = GetModule("shdocvw.dll") ie = CreateObject(mod.InternetExplorer) Thomas From nagle at animats.com Fri Jan 12 02:09:29 2007 From: nagle at animats.com (John Nagle) Date: Thu, 11 Jan 2007 23:09:29 -0800 Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error In-Reply-To: <CoFph.33142$Gr2.8155@newssvr21.news.prodigy.net> References: <YK%oh.17173$sR.6972@newssvr29.news.prodigy.net> <ovWdnZTGuYL38jjYnZ2dnUVZ_rqdnZ2d@comcast.com> <1168543799.097737.127930@i56g2000hsf.googlegroups.com> <ZsednYtgeIfeVTvYnZ2dnUVZ_hydnZ2d@comcast.com> <CoFph.33142$Gr2.8155@newssvr21.news.prodigy.net> Message-ID: <N3Gph.15737$Gw4.6586@newssvr23.news.prodigy.net> OK, I have a one-line fix. To Connection.py of M2Crypto: def connect(self, addr): self.socket.connect(addr) self.addr = addr self.socket.settimeout(None) # Back to normal timeout (NEW) self.setup_ssl() self.set_connect_state() ret = self.connect_ssl() check = getattr(self, 'postConnectionCheck', self.clientPostConnectionCheck) if check is not None: if not check(self.get_peer_cert(), self.addr[0]): raise Checker.SSLVerificationError, 'post connection check failed' return ret After the socket is connected, we turn its timeout off. The effect is that if the caller sets socket.setdefaulttimeout(timeoutsecs) before creating the Connection object, that will set the connection timeout. The socket will be created as non-blocking, but before any reads or writes are done, we clear the timeout, making it blocking again. So the connection will time out as requested, but we won't get errors because the socket is non-blocking and is being used by code that expects it to block. Gets usable connection timeouts, and prevents bogus "peer did not return certificate" errors. John Nagle Animats From rmcore at gmail.com Fri Jan 26 08:23:14 2007 From: rmcore at gmail.com (Michael Bentley) Date: Fri, 26 Jan 2007 07:23:14 -0600 Subject: Mounting shares with python In-Reply-To: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> References: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> Message-ID: <184B9B55-2101-4BD4-B344-736E18A377D6@gmail.com> On Jan 26, 2007, at 6:40 AM, Marcpp wrote: > Hi, when i mount a share with python... > > os.system ("mount -t smbfs -o username=nobody ...") > > the problem is that I'll to be root. > Have a comand to send a root password...? > I've tried > > os.system ("su") > os.system ("the password") > > but it doesn't works. Each call to os.system() spawns a new shell, so that approach wouldn't work. If you have sudo configured such that you don't need a password, you can use os.system ("sudo mount -t smbfs -o username=nobody ..."). Otherwise (if you must use a password for sudo -- or if you don't have sudo), you can use popen2 module <http:// docs.python.org/lib/module-popen2.html> to spawn a process you can interact with. -michael From joel.hedlund at gmail.com Wed Jan 10 10:01:06 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 10 Jan 2007 16:01:06 +0100 Subject: Need startup suggestions for writing a MSA viewer GUI in python Message-ID: <eo2uhr$ffn$1@news.lysator.liu.se> Hi! I've been thinking about writing a good multiple sequence alignment (MSA) viewer in python. Sort of like ClustalX, only with better zoom and pan tools. I've been using python in my work for a couple of years, but this is my first shot at making a GUI so I'd very much appreciate some ideas from you people to get me going in the right direction. Despite my GUI n00b-ness I need to get it good and usable with an intuitive look and feel. What do you think I should do? What packages should I use? For you non-bioinformatic guys out there, an MSA is basically a big matrix (~1000 cols x ~100 rows) of letters, where each row represents a biological sequence (gene, protein, etc...). Each sequence has an ID that is usually shorter than 40 characters (typically, 8-12). Usually, msa visualizers color the letters and their backgrouds according to chemical properties. I want the look and feel to be pretty much like a modern midi sequencer (like cubase, nuendo, reason etc...). This means the GUI should have least three panes; one to the left to hold the IDs, one in the bottom to hold graphs and plots (e.g: user configurable tracks), and the main one that holds the actual MSA and occupies most of the space. The left and bottom panes should be resizable and foldable. I would like to be able to zoom and pan x and y axes independently to view different portions of the MSA, and the left and bottom panes should follow the main pane. I would also like to be able to use drag'n'drop on IDs for reordering sequences, and possibly also on the MSA itself to shift sequences left and right. Furthermore, I would like to be able to select sequences and positions (individually, in ranges or sparsely). I would like to have a context sensitive menu on the right mouse button, possibly with submenus. Finally, I'd like to be able to export printable figures (eps?) of regions and whole MSAs. I'm thinking all three panes may have to be rendered using some sort of scalable graphics because of the coloring and since I'd like to be able to zoom freely. I'll also need to draw graphs and plots for the tracks. Is pygame good for this, or is there a better way of doing it? I want my viewer to behave and look like any other program, so I'm thinking maybe I should use some standard GUI toolkit instead, say PyQT or PyGTK? Would they still allow me to render the MSA nicely? Does this seem like a humongous project? Thanks for taking the time! /Joel Hedlund From syedamjad_a at yahoo.com Fri Jan 12 11:28:16 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 12 Jan 2007 08:28:16 -0800 Subject: getting the name of hyperlinks in a file Message-ID: <1168619296.006209.298990@s34g2000cwa.googlegroups.com> folks, I am trying to write a script that would open a download server and download all the files and store them in a list for example Download server is http://download.fedora.redhat.com/pub/fedora/linux/core/updates/5/SRPMS/ is there any way this can be done in python?? From gagsl-py at yahoo.com.ar Tue Jan 16 22:22:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Jan 2007 00:22:43 -0300 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: <8ab5f$45ad5c12$d443bb3a$7243@news.speedlinq.nl> References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> <1168904865.253014.210140@m58g2000cwm.googlegroups.com> <8ab5f$45ad5c12$d443bb3a$7243@news.speedlinq.nl> Message-ID: <7.0.1.0.0.20070117000457.0467fc50@yahoo.com.ar> At Tuesday 16/1/2007 20:13, Stef Mientki wrote: >Ok, here's my current solution, >probably not very Pythonian, (so suggestions are welcome) >but it works. It appears that you're a number crunching guy - you absolutely ignore all types except numeric ones! :) >(Too bad I can get the name of the var into a function ;-) I don't understand this, but if you are saying that you can't get the name of the variable you're showing - just pass the name to the function: def pm(V, name) > # count the occurances of the different types > N_int,N_float,N_complex,N_list,N_tuple,N_array,N_unknown = >0,0,0,0,0,0,0 Ouch, seven counters... your guts should be saying that this is candidate for a more structured type... what about a dictionary indexed by the element type? count = {} > for i in range(len(V)): You're going to iterate along all the items in V, not along its indices... > if type(V[i]) == int: N_int += 1 > elif type(V[i]) == float: N_float += 1 > elif ... Using a dict: for item in V: t = type(item) try: count[t] = count[t]+1 except IndexError: count[t] = 1 (That is: if the type is found in the dictionary, increment the count; if not, this is the first time: set the count to 1) > # print the occurances of the different types > # and count the number of types that can easily be displayed > if type(V)==list: line = 'list:' > else: line = 'tuple:' > N = 0 > if N_int > 0: line = line + ' N_Int=' + str(N_int) ; N >+= 1 > if N_float > 0: line = line + ' N_Float=' + str(N_float) ; N >+= 1 We'll replace all of this with: for key,value in count: line += ' %s=%d' % (key, value) > if N == 1: line += ' == Homogeneous ==' if len(count)==1: line += ' == Homogeneous ==' > print line -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From pwatson at redlinepy.com Tue Jan 2 17:35:52 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 02 Jan 2007 16:35:52 -0600 Subject: A question about unicode() function In-Reply-To: <1167648187.190860.123680@k21g2000cwa.googlegroups.com> References: <1167571210.084436.311610@48g2000cwx.googlegroups.com> <1167648187.190860.123680@k21g2000cwa.googlegroups.com> Message-ID: <459ADE48.4000004@redlinepy.com> JTree wrote: > Thanks everyone! > > Sorry for my ambiguous question. > I changed the codes and now it works fine. > > > > JTree wrote: >> Hi,all >> I encountered a problem when using unicode() function to fetch a >> webpage, I don't know why this happenned. >> My codes and error messages are: >> >> >> Code: >> #!/usr/bin/python >> #Filename: test.py >> #Modified: 2006-12-31 >> >> import cPickle as p >> import urllib >> import htmllib >> import re >> import sys >> >> def funUrlFetch(url): >> lambda url:urllib.urlopen(url).read() >> >> objUrl = raw_input('Enter the Url:') >> content = funUrlFetch(objUrl) >> content = unicode(content,"gbk") >> print content >> content.close() >> >> >> error message: >> >> C:\WINDOWS\system32\cmd.exe /c python test.py >> Enter the Url:http://www.msn.com >> Traceback (most recent call last): >> File "test.py", line 16, in ? >> content = unicode(content,"gbk") >> TypeError: coercing to Unicode: need string or buffer, NoneType found >> shell returned 1 >> Hit any key to close this window... >> >> Any suggestions would be appreciated! >> >> Thanks! So... How about posting the brief working code? From harry.g.george at boeing.com Wed Jan 24 01:24:37 2007 From: harry.g.george at boeing.com (Harry George) Date: Wed, 24 Jan 2007 06:24:37 GMT Subject: Python does not play well with others References: <NXyth.51860$wc5.6792@newssvr25.news.prodigy.net> Message-ID: <xqxirex3psq.fsf@cola3.ca.boeing.com> John Nagle <nagle at animats.com> writes: > The major complaint I have about Python is that the packages > which connect it to other software components all seem to have > serious problems. As long as you don't need to talk to anything > outside the Python world, you're fine. But once you do, things > go downhill. MySQLdb has version and platform compatibility > problems. So does M2Crypto. The built-in SSL support is weak. > Even basic sockets don't quite work right; the socket module > encapsulates the timeout mechanism but doesn't get it right. > > In the Perl, Java, PHP, and C/C++ worlds, the equivalent > functions just work. That's because, in those worlds, either the > development team for the language or the development team > for the subsystem takes responsibility for making them work. > Only Python doesn't do that. > > Python has been around long enough that this should have > been fixed by now. > > John Nagle You experience isn't shared by everyone. Some of us find Python the most functional and portable of the candidates you mention. Perl - excellent modules and bindings for just about everything you can think of, but the whole thing is painful to watch. Once you've done a few code reviews on 10,000 line perl packages where even the authors have no idea what the code is doing, you tend to look elesewhere. Java - a world of its own. They reinvent the wheel instead of linking to existing libraries. In the process you get libraries upon libraries upon libraries. Even if there isn't a performance hit, you (as a human) can get lost. And the language is just too verbose to live with. PHP - are we talking web scripts or serious programs? Are you doing numerical analysis, NLP, computational chemistry, or bit twiddling in PHP? C - the portable assembler. Solid, trusted, tunable performance, bindings for everything. Of course memory bugs can stop your project in its tracks for indeterminant periods. C++ - objects tacked onto C; but that didn't work so invent a whole world of templates and rewrite everything again, but now trickier than C to bind to other languages. Good work can be done in C++, but that is a testimony to the programmers and not to the language. Python - it just works. Same scripts run on every platform. Bindings available to every C/C++/FORTRAN library I've needed so far. Often the bindings are not complete, but oddly enough the binding developers have chosen to do just the functions I need, so who cares. A clean architecture for adding more function bindings if I'm so inclined. -- Harry George PLM Engineering Architecture From spedrosa at gmail.com Fri Jan 5 13:55:20 2007 From: spedrosa at gmail.com (Stephen Eilert) Date: 5 Jan 2007 10:55:20 -0800 Subject: program deployment In-Reply-To: <1168013279.634426.84110@s80g2000cwa.googlegroups.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> <1168012877.398078.59120@s80g2000cwa.googlegroups.com> <1168013279.634426.84110@s80g2000cwa.googlegroups.com> Message-ID: <1168023319.644237.273240@v33g2000cwv.googlegroups.com> king kikapu wrote: > Ok, i got the point...Things are a little bit different on the other > way of the fence (Microsoft way...) and so many of Python's elements > are a little (at least) strange at first... > > But hey, thank you all! Not really! Of course you do not distribute .cs (or .vb) files when deploying your application, but decompilers for .NET are plenty. Same for Java. For C and the like, it is a little trickier, but the "decompiler" can and will produce equivalent code. Better yet, just disassemble it. What is done nowadays to make people's life harder (as in, they cannot just copy and paste code) is to use an obfuscator. Are there any for Python? This is completely and utterly useless for passwords, though. If you need to protect something, encrypt it. If it is on a server, you can control access to the file via filesystem permissions. Do not expect to keep the password secret if you are distributing it, though :) I've cracked C programs, Clipper and Java almost effortlessly. They were all custom programs where the sole developer would put a password for administrative functions, just to be able to charge money long after it was deployed. Stephen From mc at uga.edu Wed Jan 10 16:39:10 2007 From: mc at uga.edu (mc) Date: 10 Jan 2007 13:39:10 -0800 Subject: Python - C# interoperability In-Reply-To: <1168401054.044692.187040@77g2000hsv.googlegroups.com> References: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> <1168401054.044692.187040@77g2000hsv.googlegroups.com> Message-ID: <1168465150.082226.326660@i56g2000hsf.googlegroups.com> Thanks to all who responded. It appears that there may be a solution as follows: use jythonc to turn Python program into Java bytecode use Microsoft's jbimp to turn Java bytecode into .NET DLL It sounds roundabout, but I am investigating. From kylotan at gmail.com Wed Jan 3 12:13:30 2007 From: kylotan at gmail.com (Ben Sizer) Date: 3 Jan 2007 09:13:30 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <mailman.2225.1167773658.32031.python-list@python.org> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <mailman.2211.1167756187.32031.python-list@python.org> <1167757721.883547.70530@42g2000cwt.googlegroups.com> <mailman.2225.1167773658.32031.python-list@python.org> Message-ID: <1167844409.956690.50500@n51g2000cwc.googlegroups.com> Chris Lambacher wrote: > On Tue, Jan 02, 2007 at 09:08:41AM -0800, Ben Sizer wrote: > > Chris Lambacher wrote: > > > The python part of the 'python setup.py install' idiom needs to be omitted on > > > Windows, but that does not mean that the solution is to automatically add it > > > to PATH. > > > > Firstly, that solution only works for actual Python scripts; it doesn't > > solve the utility scripts that are often installed to the /scripts > > directory. It's a shame that many responses on this thread don't > > address that half of the issue. Am I the only person who installs > > packages that add scripts (not all of which are Python ones)? > > Nope, but just adding the scripts directory to the PATH does not solve the > problem. You also need to either create an executable launcher (.bat or > .exe) for the script or mess with environment variables to tell Windows to > treat .py files a executable. This issue is solved in Unix by toggling the > executable bit on the file in the file system. Many of the scripts that are installed come as batch files or other executables. They just assume the directory is in your PATH already, which they aren't, until you set it that way. > > Secondly, it's still a significant difference from the Unix-based > > installs. > > Its not really. Unix installs default to being installed to the prefix /usr, > which just happens to put the executable in your path. It does not modify the > user's path in any way. I was talking more in terms of the end-user experience. I don't know of any binary package on the distros I've used (Mandriva/Mandrake, Fedora Core, and Kubuntu) that install Python without it going into your path, nor of any that allow you to avoid that while using their standard package managers. It may be incidental in some meaning of the term, but it's expected and apparently intended. -- Ben Sizer From google at mrabarnett.plus.com Wed Jan 3 13:39:16 2007 From: google at mrabarnett.plus.com (MRAB) Date: 3 Jan 2007 10:39:16 -0800 Subject: list/dictionary as case statement ? In-Reply-To: <501r8sF1dp76aU1@mid.individual.net> References: <d59f3$459ad7cf$d443bb3a$14116@news.speedlinq.nl> <mailman.2232.1167806595.32031.python-list@python.org> <71pmp2tq1klma5urhkfiv8bpq6u8sgtj06@4ax.com> <501r8sF1dp76aU1@mid.individual.net> Message-ID: <1167849556.429532.100990@48g2000cwx.googlegroups.com> Bjoern Schliessmann wrote: > Tom Plunket wrote: > > > Often (always?) RISC architectures' instruction+operand lengths > > are fixed to the word size of the machine. E.g. the MIPS 3000 and > > 4000 were 32 bits for every instruction, and PC was always a > ^^ > > multiple of four. > > Intels aren't RISC, are they? > I think that "PC" referred to the CPU's Program Counter. The x86 CPUs if typical Windows PCs aren't RISC but Intel also manufacture X-Scale (ARM core) processors which are. > But for PowerPC it's the same, every instruction has 32 bit. > As are those of ARM processors like X-Scale (although some ARM processors support the Thumb instruction set). From gandalf at designaproduct.biz Tue Jan 23 09:38:47 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 23 Jan 2007 15:38:47 +0100 Subject: urllib2 question Message-ID: <45B61DF7.9070808@designaproduct.biz> Hi All, I would like to save a URL into a file. I need to manage cookies and use my own HTTP headers so I'm using urllib2 and a custom openerdirector. Here is a code fragment: while True: data = openerdirector.read(1024) fd.write(data) if not data: break The main reason for doing this is that the URL can contain big amounts of data, and I do not want to store it in memory. The other way would be: fd.write(openerdirector.read()) My question is that am I doing this the right way? I used the openerdirector as a file here, but I'm not sure if it works like a file. A file object should block when read() is called, and then return at most 1024 bytes of data when available. It will return with an empty string only after EOF reached. But is the same true for the openerdirector instance? I did not find useful documentation in the python docs about this. The documentation says: *class OpenerDirector*( ) The OpenerDirector class opens URLs via BaseHandlers chained together. It manages the chaining of handlers, and recovery from errors. But I'm not sure if it can be used as a file or not. Thanks, Laszlo From steve at REMOVEME.cybersource.com.au Wed Jan 31 20:30:54 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 01 Feb 2007 12:30:54 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <mailman.3297.1170139632.32031.python-list@python.org> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> <pan.2007.01.31.07.24.21.793319@REMOVEME.cybersource.com.au> <mailman.3341.1170234961.32031.python-list@python.org> Message-ID: <pan.2007.02.01.01.30.53.805880@REMOVEME.cybersource.com.au> On Wed, 31 Jan 2007 20:15:44 +1100, Ben Finney wrote: > "Steven D'Aprano" <steve at REMOVEME.cybersource.com.au> writes: > >> > def _accumulate_properties(self, properties): >> > self.properties = [] >> >> Probably better to put that in the __init__ method, otherwise if >> somebody runs instance._accumulate_properties(...) again, it will >> have the side-effect of throwing away whatever was already in >> instance.properties. > > That's the point of naming it with a leading underscore. You've > already explained that this is convention for "Private, don't use". "Somebody" could easily be the class designer. This is a method that, as written, will break the instance if it is run twice. That's not good. >> Some people might argue that if someone runs a private method like >> _accumulate_properties, they deserve whatever bad things happen to >> them. But I say, well, sure, but why *design* your method to break >> things when called twice? > > Exactly the same could be said for calling the __init__ method twice. __init__ isn't a "private" method, it is a public method. A very special public method, designed to initialise the instance, that is to set the instance to a brand new pristine state. Calling instance.__init__ *should* initialise the instance and throw away whatever data was already there. (Why you would want to do this is another question.) What else would you expect it to do? If you called __init__ and it *didn't* initialise the instance, that would surely be a bug. But _accumulate_properties as written is sort of half-man-half-duck sort of thing: it would be useful for accumulating properties to the instance, except that when you do so it throws away whatever properties you have previously accumulated. Or rather, it doesn't even do that -- it simply throws away the list of properties, but leaves the actual properties behind. That can't possibly be good design! An inconsistent internal state like that is a bug waiting to happen. >> Who knows, maybe you'll decide you want to call it twice yourself. > > Right. In which case, it's good that it's already in a separate, > clearly-named, single-purpose method. It isn't either clearly-named or single-purpose. The name is misleading, for two reasons. First, "properties" has a technical meaning in Python, and this method doesn't have anything to do with that meaning. Secondly, even if it did, it doesn't accumulate them, it resets the list to a new state, throwing away whatever was there before. Nor is it single-purpose: while it *sets* a list of attribute names to a new list of values, it *adds* those new attributes to the instance __dict__. There are some methods that, in principle, should be run once and once only. There's nothing inherently about accumulating attributes/properties to an instance can only be done once. But the way the method is written, it will break things if you try to accumulate attributes twice -- not because of any inherent badness in doing so, but because the method breaks the consistency between self.properties (a list) and the actual attributes accumulated. > Make the code easy to understand, not idiot-proof. I'm not arguing that the entire method should be moved into __init__. *Initialising* self.properties list to [] is not logically part of *accumulating* properties, and should be moved out of that method. That tiny change will fix all of the problems I describe except for the misleading name. -- Steven D'Aprano From ziga.seilnacht at gmail.com Mon Jan 8 12:36:38 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 8 Jan 2007 09:36:38 -0800 Subject: Bizarre floating-point output References: <enthjb$p0l$1@gemini.csx.cam.ac.uk><entj5d$o4$1@south.jnrs.ja.net> <entkru$2vs$1@gemini.csx.cam.ac.uk> <50f5snF1fb5uqU2@mid.individual.net> <entpo0$d0g$1@gemini.csx.cam.ac.uk> <mailman.2425.1168272626.32031.python-list@python.org> <enttq6$lj2$1@gemini.csx.cam.ac.uk> Message-ID: <1168277798.302236.184180@s34g2000cwa.googlegroups.com> Nick Maclaren wrote: > I think that you should. Where does it say that tuple's __str__ is > the same as its __repr__? > > The obvious interpretation of the documentation is that a sequence > type's __str__ would call __str__ on each sub-object, and its __repr__ > would call __repr__. How would you distinguish ['3', '2', '1'] from [3, 2, 1] in that case? Ziga From http Thu Jan 25 18:01:27 2007 From: http (Paul Rubin) Date: 25 Jan 2007 15:01:27 -0800 Subject: stop script w/o exiting interpreter References: <Lyauh.8689$QE6.2176@trnddc02> Message-ID: <7x7ivaiud4.fsf@ruckus.brouhaha.com> "Alan Isaac" <aisaac at american.edu> writes: > I'm fairly new to Python and I've lately been running a script at > the interpreter while working on it. Sometimes I only want to > run the first quarter or half etc. What is the "good" way to do this? If it's single threaded then just call sys.exit(). If you don't know what single threaded means, your program is definitely single threaded. From gagsl-py at yahoo.com.ar Wed Jan 24 00:23:41 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 02:23:41 -0300 Subject: Overloading assignment operator References: <2BBAEE949D384D40A2B851287ADB6A4304595AA4@eugsrv400.psc.pscnet.com> Message-ID: <ep6qgl$2gn$1@sea.gmane.org> "Carroll, Barry" <Barry.Carroll at psc.com> escribi? en el mensaje news:2BBAEE949D384D40A2B851287ADB6A4304595AA4 at eugsrv400.psc.pscnet.com... > * ... the assignment operator is used to assign an > * object to a name in the current namespace... IOW, you cannot "overload > * the assignment operator." > (wesley chun) This is the key concept, if you want to be able to "see" assignments, you should work with a namespace (a dictionary is enough...) > * result = property(get_result, set_ result, doc='result of operations') > > I have tested this using the admittedly simple-minded code snipped > below. > >>>>>>>>>>> > @BCARROLL[Python]|3> class Aclass: > |.> def __init__(self): > |.> __result = None > |.> def get_result(self): > |.> return self.__result > |.> def set_result (self, result): > |.> self.__result = result > |.> result = property(get_result, set_result, > doc='result of expression') > |.> > @BCARROLL[Python]|5> A = Aclass() > @BCARROLL[Python]|7> a.result = 2*3 > @BCARROLL[Python]|8> a.result > <8> 6 > @BCARROLL[Python]|9> a.result = 25.0 * 5.25 > @BCARROLL[Python]|10> a.result > <10> 131.25 > @BCARROLL[Python]|11> >>>>>>>>>>> Notice that you can delete ALL those lines of code, leaving a bare: class Aclass: passs and you will get EXACTLY the same results. In this case -and this are not my words- properties are a waste of programmer time, processor time and disk space. Of course properties are very useful, but when you need to do something "more" than just storing and retrieving a single value. -- Gabriel Genellina From no-spam at no-spam-no-spam.invalid Thu Jan 4 15:09:20 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 04 Jan 2007 21:09:20 +0100 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167735173.884444.250750@k21g2000cwa.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <enavfb$1gn$1@news.albasani.net> <1167735173.884444.250750@k21g2000cwa.googlegroups.com> Message-ID: <enjmth$ru3$1@news.albasani.net> Ben Sizer wrote: > robert wrote: >> Ben Sizer wrote: >>> My opinion is that this is not as big a problem as some may feel that >>> it is. Unlike Unix systems, the PATH variable is rarely used. >> It is a big problem. >> >> It is not less than the majority of Python users (at least those who do things on the command line) who deal with multiple Python versions. > > So you think most Python users have more than one version of Python > installed? I disagree - but even if it is true, how come this isn't a > big problem on Unix? Can you name a single distribution that doesn't > install Python to the path? As said - yes they install the 'pythonx.y' binary or just 'python' default link _into_ the path (/usr/local/bin or /usr/bin). Yet they don't manipulate any PATH. >> This would create funny PATH variables - almost a "psychic behavior with history". > > It is quite trivial to see if Python is already on the path, and act > differently based on that. When you run an installer you first lookup the PATH and according to your look you hit or not-hit the (future) checkbox in the installer and/or edit the PATH later to only have one python main folder in it? You could as well edit the PATH at all yourself as one can do it now. >> Windows is at all less a multi user system. I don't even know a case where two (Python) Programmers use _one_ box and then also want separate Python's - just know home mates (parasites) who occasionally share the web browser or so... > > So... that's another reason why there's rarely a problem in setting > that PATH variable. mix-up with PATH is already there for a single user. I named a most negative example (Borland) and would not use such checkbox in a Python installer which would allow to manipulate the PATH in hardly predictable manner. >> Linking also a default python.exe into the system32 upon a (non-default) checkbox mark in the installer should be simple, clear and do everything what 99.9% want - and most "compatible" to *nix. > > No, it doesn't : the /scripts directory is also important for many > Python packages and that isn't addressed by shifting python.exe into > system32. Now you want also the scripts directory on the PATH? I don't even see this stuff on linux py's nor PATH's. But as somebody said, we could have 3 or 4 options in the installer. Just who will supply MvL with the patch, which is truely not trivial. Most cheap and consistent is: Create pythonXY.exe always next to the pythonXY.dll auto. This is the same as having usr/local/pythonX.Y on linux. (Personally I anyway like to call exactly the python i want.) Then a future option 2 - as I'd favor it next to the current "do nothing" - would probably also most simple for system installations: If checkbox "copy python.exe into System Folder" then copy/overwrite python.exe into System Folder. There is not much magic and not much precedence worries about it and every developer knows clearly what happens. If multi-pythons, one knows that this would create the new default "python" on the command line unless one has custom things in front on the PATH. Then there could be advanced options 3, 4, .. for PATHs: With questions: Replacing in User- and/or System-PATH?, prepending-to-User/System-PATH?, appending-to-User/System-PATH, the same for the Script-folders and all fancy things and side-effects etc. - if consistent patches will ever be supplied ... I'd not use these options a lot anyway because I like Python to answer my questions - not reverse :-) Robert From eastera at gmail.com Mon Jan 1 02:07:08 2007 From: eastera at gmail.com (JTree) Date: 31 Dec 2006 23:07:08 -0800 Subject: A question about unicode() function In-Reply-To: <mailman.2173.1167571846.32031.python-list@python.org> References: <1167571210.084436.311610@48g2000cwx.googlegroups.com> <mailman.2173.1167571846.32031.python-list@python.org> Message-ID: <1167635228.725060.39110@42g2000cwt.googlegroups.com> Hi, I changed my codes to: #!/usr/bin/python #Filename: test.py #Modified: 2007-01-01 import cPickle as p import urllib import htmllib import re import sys funUrlFetch = lambda url:urllib.urlopen(url).read() objUrl = raw_input('Enter the Url:') content = funUrlFetch(objUrl) content = content.encode('gb2312','ignore') print content content.close() I used "ignore" to deal with the data lose, but it still caused a error: C:\WINDOWS\system32\cmd.exe /c python tianya.py Enter the Url:http://www.tianya.cn Traceback (most recent call last): File "tianya.py", line 17, in ? content = content.encode('gb2312','ignore') UnicodeDecodeError: 'ascii' codec can't decode byte 0xbb in position 88: ordinal not in range(128) shell returned 1 Hit any key to close this window... My python version is 2.4, Does it have some problems with asian encoding support? Thanks! On Dec 31 2006, 9:30 pm, "Felipe Almeida Lessa" <felipe.le... at gmail.com> wrote: > On 31 Dec 2006 05:20:10 -0800, JTree <east... at gmail.com> wrote: > > > def funUrlFetch(url): > > lambda url:urllib.urlopen(url).read()This function only creates a lambda function (that is not used or > assigned anywhere), nothing more, nothing less. Thus, it returns None > (sort of "void") no matter what is its argument. Probably you meant > something like > > def funUrlFetch(url): > return urllib.urlopen(url).read() > > or > > funUrlFetch = lambda url:urllib.urlopen(url).read() > > > objUrl = raw_input('Enter the Url:') > > content = funUrlFetch(objUrl)content gets assigned None. Try putting "print content" before the unicode line. > > > content = unicode(content,"gbk")This, equivalent to unicode(None, "gbk"), leads to > > > TypeError: coercing to Unicode: need string or buffer, NoneType foundNone's are not strings nor buffers, so unicode() complains. > > See ya, > > -- > Felipe. From nogradi at gmail.com Wed Jan 31 11:02:39 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 31 Jan 2007 17:02:39 +0100 Subject: subway Message-ID: <5f56302b0701310802y7e45c98fmaaebe090e34d410@mail.gmail.com> Does anyone know what has happened to the codebase of the subway project? It seems the whole project has been shut down leaving no trace of the code on net but I would be very happy to see it, apparently it had some cool features that would be fun to look at. Does anyone have access to the code and/or is willing to make it publically available? From sean at datafly.net Wed Jan 17 20:35:30 2007 From: sean at datafly.net (Sean Schertell) Date: Thu, 18 Jan 2007 10:35:30 +0900 Subject: PyMeld for html templates? Message-ID: <8793EED7-D320-417B-8C8B-7BBB7572C025@datafly.net> I'm trying to decide which template system to get married to. I think I've narrowed it down to PyMeld, Cheetah, or Jinja but leaning heavily toward PyMeld because I love the idea that your templates are *totally* clean and that get manipulated from behind the scenes. This seems to be elegantly inline with the Sacred Creed of separation of logic from presentation. Of course I'm going to try them all but I wonder if anyone has any thoughts on PyMeld as a template system for churning out general websites? One important consideration is that even though PyMeld itself doesn't support template inheritance so far as I know, I'll need to accomplish that somehow. I want for a URI request to mysite.com/info to pull in a layout.html template which will in turn be populated by the info.html template. I've already got the URI mapping stuff sorted. But how about PyMeld, any ideas on how to do it or whether it will even work as I've described? Thanks! Sean :::: DataFly.Net :::: Complete Web Services http://www.datafly.net From john.pye at gmail.com Wed Jan 24 04:05:20 2007 From: john.pye at gmail.com (John Pye) Date: 24 Jan 2007 01:05:20 -0800 Subject: Overloading assignment operator In-Reply-To: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1169629520.195576.214460@q2g2000cwa.googlegroups.com> Hi thre, On Jan 24, 5:24 am, Achim Domma <d... at procoders.net> wrote: > I want to use Python to script some formulas in my application. Depending on what you're trying to do, you might possibly find it useful to lake a look at the approach used by PyGINAC, which is a symbolic algebra system (in C++) wrapped with some clever python bindings: http://pyginac.sourceforge.net/ Hope that helps, JP From martin at v.loewis.de Wed Jan 3 14:12:16 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 20:12:16 +0100 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167844551.332740.320760@s34g2000cwa.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <mailman.2211.1167756187.32031.python-list@python.org> <1167757721.883547.70530@42g2000cwt.googlegroups.com> <459BCE85.5070707@v.loewis.de> <1167844551.332740.320760@s34g2000cwa.googlegroups.com> Message-ID: <459C0010.60801@v.loewis.de> Ben Sizer schrieb: >> Those packages should install .bat files into /scripts on Windows. > > Which still need their location to be be fully qualified, due to > /scripts not being in the path. This is not my experience with Linux > installations of the same packages. Ah, so you not only want the directory that contains Python added to the path, but also /scripts. That's again a new requirement, and I think it is the first time that somebody requests it. Regards, Martin From bborcic at gmail.com Thu Jan 25 05:55:54 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 25 Jan 2007 11:55:54 +0100 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <4866bea60701240736v837d246w187ecb1ccb90eefd@mail.gmail.com> References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> <ep7qoe$jdg$1@sea.gmane.org> <4866bea60701240736v837d246w187ecb1ccb90eefd@mail.gmail.com> Message-ID: <epa2dh$jl3$1@sea.gmane.org> Chris Mellon wrote: > On 1/24/07, Boris Borcic <bborcic at gmail.com> wrote: >> Chris Mellon wrote: >>> Using either win32 or wxPython you will be able to produce bitmaps >>> directly, without needing to create a visible window. >>> >>> >>> Some quick & dirty wxPython code >>> >>> def getTextBitmap(text, font, fgcolor, bgcolor): >>> dc = wx.MemoryDC() >>> dc.SetFont(font) >>> width, height= dc.GetTextExtent(text) >>> bmp = wx.EmptyBitmap(width, height) >>> dc.SelectObject(bmp) >>> dc.SetBackground(wx.Brush(bgcolor)) >>> dc.Clear() >>> dc.SetTextBackground(bgcolor) >>> dc.SetTextForeground(fgcolor) >>> dc.DrawText(text, 0, 0) >>> dc.SelectObject(wx.NullBitmap) >>> return bmp >>> >>> >>> Raw win32 code will look similar but will be much more verbose. >> Thx again for this base. >> >> Quickly testing this, it appears that the result is rendered half a pixel off in >> the x-direction. Does this make sense ? Is it possible to position text with >> subpixel accuracy ? >> > > The GDI text api, which is what wx is wrapping here, only provides > pixel accuracy. You are probably seeing a kerning effect from your > chosen font and perhaps the effects of ClearType. I am not. Turning antialiasing off (as a desktop setting) changes the rendering but wx._gdi_ still insists that horizontal coordinates are between pixels (to the contrary of vertical coordinates). This means thin black vertical lines are rendered by two pixel columns, the left one red, the right one cyan. Non-aliased, 90-degree rotated text is still smeared likewise left-to-right on the screen what becomes top-to-bottom relative to the text. Setting the scales at 0.5 and drawing the text one pixel off (to express a half-pixel shift) doesn't work. A long almost vertical thin black line that's one pixel off top-to-bottom results in two parallel vertical uniformly colored red and cyan pixel columns, broken in the middle. In short, wx._gdi_ fights quite hard to enforce what I am trying to avoid :( I might admire its consistency if it extended to treating both axes similarly... Regards, Boris Borcic From ptmcg at austin.rr._bogus_.com Sun Jan 7 06:34:57 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 7 Jan 2007 05:34:57 -0600 Subject: How to write code to get focuse the application which is open from server References: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> Message-ID: <45a0dae2$0$8948$4c368faf@roadrunner.com> "vinthan" <svithi at gmail.com> wrote in message news:1168143871.536432.252010 at v33g2000cwv.googlegroups.com... > hi, > I am new to python. I have to write test cases in python. An > application is open in the desk top ( application writen in .Net) I > have to write code to get focuse the application and click on the link > which in the one side and it will load the map on the other and I have > to check map is loaded. Any one tell me how do I use Dispatch or any > other method to write a code. > If you are running on Windows, look into pywinauto (http://www.openqa.org/pywinauto/). I have successfully used it to interact with a Flash animation running within an IE browser. I also had to inspect the graphics displayed by the Flash animation, for this I used PIL (http://www.pythonware.com/products/pil/). Good luck, -- Paul From michael at mustun.ch Mon Jan 8 08:43:01 2007 From: michael at mustun.ch (Michael M.) Date: Mon, 08 Jan 2007 14:43:01 +0100 Subject: where is python on linux? In-Reply-To: <mailman.2410.1168255722.32031.python-list@python.org> References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com><45a157a0$0$289$426a74cc@news.free.fr> <Xns98B1B092FD1ADrzantowgmailcom@208.49.80.253> <mailman.2410.1168255722.32031.python-list@python.org> Message-ID: <iTroh.101$FA3.57@nntpserver.swip.net> $ whoami cannibal ;-) Hendrik van Rooyen wrote: > "rzed" <rzantow at gmail.com> wrote: > > > >>mmmmmmm... sloppy joes .... >> >>-- >>rzed >> >>"A sandwich is a sandwich, but a Manwich is a meal." > > > You eat people? > > - Hendrik > > From gagsl-py at yahoo.com.ar Wed Jan 31 03:08:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Jan 2007 05:08:36 -0300 Subject: Unicode error handler References: <epdmae$qps$1@sea.gmane.org> <mailman.3314.1170174675.32031.python-list@python.org> <1170217309.125918.214060@v33g2000cwv.googlegroups.com> Message-ID: <op.tm0d8mdosd1mbx@gabriel2.softlabbsas.com.ar> En Wed, 31 Jan 2007 01:21:49 -0300, Hieu.D.Hoang at gmail.com <Hieu.D.Hoang at gmail.com> escribi?: > I don't understand what %r and r are and where they are from. The man > 3 printf page doesn't have %r formatting. Perhaps you should look into the Python docs instead? -- Gabriel Genellina From redefined.horizons at gmail.com Fri Jan 5 23:34:57 2007 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 5 Jan 2007 20:34:57 -0800 Subject: Pausing for Python Interpreter error messages... Message-ID: <1168058097.855006.229820@s80g2000cwa.googlegroups.com> I've written a few classes that I have been testing in IDLE. However, every time I make a change to the classes based on the testing I have to walk through all he steps of preparing the classes for testing again. So I wrote a script that does all the set-up work for me. The only problem is when I run this script using the Python interpreter I can't get the command prompt to stay up long enough for me to read the message. How do I get the command prompt to stay up? Is there a way to run my script and view the error message in IDLE? Thanks for the help. Scott Huey P.S. - I'm using Windows XP with the latest Python 2.3. From bearophileHUGS at lycos.com Mon Jan 8 13:23:36 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Jan 2007 10:23:36 -0800 Subject: recursive function In-Reply-To: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> References: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> Message-ID: <1168280616.813713.317370@v33g2000cwv.googlegroups.com> First possible solution: def rloop(seqin, comb): # xcross product recipe 302478 by David Klaffenbach if seqin: for item in seqin[0]: newcomb = comb + [item] for item in rloop(seqin[1:], newcomb): yield item else: yield comb data = {1: [(3, 4), (5, 8)], 2: [(5, 4), (21, 3), (19, 2)], 3: [(16, 1), (0, 2), (1, 2), (3, 4)]} print [sol for sol in rloop(data.values(), []) if 24==sum(el[0] for el in sol)] Bye, bearophile From eric_brunel at despammed.com Mon Jan 29 03:33:11 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 29 Jan 2007 09:33:11 +0100 Subject: Resizing widgets in text windows References: <1169847315.631951.295830@a75g2000cwd.googlegroups.com> Message-ID: <op.tmwp1letrqur0o@eb.pragmadev> On Fri, 26 Jan 2007 22:35:20 +0100, <deacon.sweeney at gmail.com> wrote: > Hi, I've been searching for a .resize()-like function to overload much > like can be done for the delete window protocol as follows: > > toplevel.protocol("WM_DELETE_WINDOW", callback) > > I realize that the pack manager usually handles all of the resize > stuff, but I've found an arrangement that the pack manager fails for. > That is, if one embeds a canvas into a window created inside a text > widget, then resize the text widget (via its container), the canvas and > its container windows do not resize. Supposing you call "embedding" inserting a widget in the text via the window_create method, why should they? Embedding a window in a Text is used to put some arbitrary widget in the middle of the text it contains. So the embedded widget has no reason to grow or shrink with the parent Text widget: it just moves with the text. > So I need to resize the window > that the canvas is embedded in. The most obvious way of doing this > would be as above, but there does not seem to be an equivalent to the > "WM_DELETE_WINDOW" protocol for resizing. As James said, the <Configure> event is your friend. But I'm not sure I understand your use case... HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From zebra05 at gmail.com Wed Jan 17 10:34:31 2007 From: zebra05 at gmail.com (Shortash) Date: 17 Jan 2007 07:34:31 -0800 Subject: Python Web Frameworks Message-ID: <1169048071.353887.279160@q2g2000cwa.googlegroups.com> Hi Gurus, I want to build a Python web app but im not sure which one to go for. I prefer something like asp.Net , which would allow me to fully seperate the presentation layer from the logic. Please advise? thanks, "Shortash' From aahz at pythoncraft.com Fri Jan 19 18:29:18 2007 From: aahz at pythoncraft.com (Aahz) Date: 19 Jan 2007 15:29:18 -0800 Subject: OT Annoying Habits (Was: when format strings attack) References: <mailman.2917.1169243036.32031.python-list@python.org> Message-ID: <eork8e$kv5$1@panix3.panix.com> In article <mailman.2917.1169243036.32031.python-list at python.org>, Carroll, Barry <Barry.Carroll at psc.com> wrote: > >Secondly, can someone point me to the Standard Usenet Convention that >mandates against top-posting. This is not sarcasm; I would really like >to see it. You see, I recently returned to Usenet after a LONG absence. >When I was last a regular Usenet citizen the Internet was new, GUI >interfaces were experimental and the World Wide Web didn't exist yet. >Newsreader software was text-based. Top-posting was the common >practice, because it was the most convenient: you didn't have to page >through an arbitrarily large number of messages, most of which you'd >already read umpteen times, to get to the new stuff you were interested >in. =20 Funny, I've been on Usenet for more than fifteen years, continuously (and long-windedly -- but that's another matter) and I've never seen a Usenet group where top-posting was standard. Anyway, here's a good resource: http://www.xs4all.nl/%7ewijnands/nnq/nquote.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From gandalf at designaproduct.biz Mon Jan 22 15:20:46 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 22 Jan 2007 21:20:46 +0100 Subject: mmap caching In-Reply-To: <1169496803.518305.275750@s34g2000cwa.googlegroups.com> References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <slrner7h27.d8g.nick@irishsea.home.craig-wood.com> <1169415139.515834.233700@a75g2000cwd.googlegroups.com> <4X7th.13145$pQ3.5671@newsread4.news.pas.earthlink.net> <1169496803.518305.275750@s34g2000cwa.googlegroups.com> Message-ID: <45B51C9E.5050505@designaproduct.biz> > It's around 400MB. As I said, I cannot reproduce the MemoryError > locally since I have 1GB physical space but IIRC the user who reported > it had less. Actually I am less concerned about whether a MemoryError > is raised or not in this case and more about the fact that even if > there's no exception, the program may suffer from severe thrashing due > to constant swapping. That's an issue with the specific > program/algorithm rather with Python or the OS. > Well, if the same program runs when you have 1GB physical memory then probably the problem is not that you ran out of virtual address space. It would help to provide the related code from your program. Laszlo From fdu.xiaojf at gmail.com Mon Jan 8 10:23:58 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 08 Jan 2007 23:23:58 +0800 Subject: Maybe a little bug of ipython 0.7.3 ? Message-ID: <45A2620E.70103@gmail.com> I'm new to ipython, and i found it a very cool product. $ ipython Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.7.3 -- An enhanced Interactive Python. <snip> In [8]: a = range(1000) In [9]: a? Type: list Base Class: <type 'list'> String Form: [0, 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, 26 <...> 0, 981, 98 2, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999] Namespace: Interactive Length: 1000 Docstring: list() -> new list list(sequence) -> new list initialized from sequence's items *Please note that there is an extra "0" after "**26 <...>", which doesn't appear for the followling cases:* In [10]: b = range(100) In [11]: b? Type: list Base Class: <type 'list'> String Form: [0, 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, 26 <...> , 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] <snip> In [12]: c = range(10000) In [13]: c? Type: list Base Class: <type 'list'> String Form: [0, 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, 26 <...> , 9984, 99 85, 9986, 9987, 9988, 9989, 9990, 9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999] <snip> From horpner at yahoo.com Thu Jan 18 14:40:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 18 Jan 2007 19:40:28 GMT Subject: How can I create a linked list in Python? References: <eoj6rr$90bt$1@netnews.upenn.edu> <mailman.2791.1168975031.32031.python-list@python.org> <eojb9v$92rq$1@netnews.upenn.edu> <45ad5104$0$393$426a74cc@news.free.fr> <1169009882.408482.43360@q2g2000cwa.googlegroups.com> <45ae8950$0$31033$426a74cc@news.free.fr> <1169074382.702857.313010@11g2000cwr.googlegroups.com> <7xps9dl04y.fsf@ruckus.brouhaha.com> <1169147440.211108.137940@s34g2000cwa.googlegroups.com> Message-ID: <slrneqvmjf.fg.horpner@FIAD06.norwich.edu> On 2007-01-18, sturlamolden <sturlamolden at yahoo.no> wrote: > > Paul Rubin wrote: > >> But that's what Lisp does too. > > Ok, I may have to reread Paul Graham's book on ANSI Common Lisp > then. Here's something silly I whipped up to play with. r""" Lisp style singly-linked lists called llist. """ def consp(o): return isinstance(o, Cons) def car(c): """ Return the car of a lisp-list. Undefined for nil. """ if null(c): raise AttributeError("nil has no cdr") return c.car def cdr(c): """ Return the cdr of a lisp=list. """ if null(c): return nil return c.cdr def cons(o, c): """ Build a new cons cell from an object and a Cons. """ return Cons(o, c) def null(c): return c is nil def rplaca(c, o): c.car = o return c def rplacd(c, o): c.cdr = o return c def llist(li): """ Build a llist from a list. """ c = nil for a in reversed(li): if isinstance(a, list): c = cons(llist(a), c) else: c = cons(a, c) return c class Cons(object): def __init__(self, car, cdr): self.car = car self.cdr = cdr def __repr__(self): def helper(li, s): if null(li): return s + ")" else: return helper(cdr(li), s + " %s" % repr(car(li))) return helper(self.cdr, "(" + repr(self.car)) class Nil(Cons): def __init__(self): Cons.__init__(self, None, None) def __repr__(self): return '()' nil = Nil() print cons(5, nil) print cons(5, cons(3, nil)) print cons(cons(5, (cons(7, nil))), cons(cons(5, cons(3, nil)), nil)) print nil print llist([1, ['a', 'b', 'c'], 2, 3]) There's lots more more stuff to add, but the fun wore out. I'd like if it the cdr of nil could actually be nil, instead of None with a special case in cdr, but I couldn't figure out a neat way to do it. -- Neil Cerutti I've had a wonderful evening, but this wasn't it. --Groucho Marx -- Posted via a free Usenet account from http://www.teranews.com From martin at v.loewis.de Sun Jan 21 13:55:24 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Jan 2007 19:55:24 +0100 Subject: A solution to the MSVCRT vs MSVCR71 problem? In-Reply-To: <1169404921.709667.192280@38g2000cwa.googlegroups.com> References: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> <mailman.2958.1169368253.32031.python-list@python.org> <1169404921.709667.192280@38g2000cwa.googlegroups.com> Message-ID: <45B3B71C.7090709@v.loewis.de> sturlamolden schrieb: >> This would only work, if runtime dll's were compatibles between them, >> and they are not. > > It is standard C, defined by ANSI and ISO. ANSI and ISO don't define the ABI, though. For example, the definition of the FILE type might (and does) vary across compilers, even if all these compilers implement C99. Regards, Martin From nmm1 at cus.cam.ac.uk Thu Jan 25 04:26:40 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 25 Jan 2007 09:26:40 GMT Subject: The reliability of python threads References: <mailman.3092.1169657938.32031.python-list@python.org> <ep841j$anu$1@gemini.csx.cam.ac.uk> <mailman.3095.1169659417.32031.python-list@python.org> <ep883i$iom$1@gemini.csx.cam.ac.uk> <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <mailman.3105.1169664198.32031.python-list@python.org> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> Message-ID: <ep9t4g$uf$1@gemini.csx.cam.ac.uk> In article <1169675599.502726.5070 at a34g2000cwb.googlegroups.com>, "Paddy" <paddy3118 at netscape.net> writes: |> |> Three to four months before `strange errors`? I'd spend some time |> correlating logs; not just for your program, but for everything running |> on the server. Then I'd expect to cut my losses and arrange to safely |> re-start the program every TWO months. |> (I'd arrange the re-start after collecting logs but before their |> analysis. Life is too short). Forget it. That strategy is fine in general, but is a waste of time where threading issues are involved (or signal handling, or some types of communication problem, for that matter). There are three unrelated killer facts that interact: Such failures are usually probabilistic ("Poisson process"), and so have no "history". The expected number is usually proportional to the square of the activity, sometimes a higher power. Virtually nothing involved does any routine logging, or even has options to log relevant events. The first means that the strategy of restarting doesn't help. All three mean that current logs are almost never any use. Regards, Nick Maclaren. From rw at smsnet.pl Sun Jan 28 12:18:39 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 28 Jan 2007 18:18:39 +0100 Subject: howto redirect and extend help content ? References: <1fc1a$45bcc7f4$d443bb3a$8806@news.speedlinq.nl> Message-ID: <87d54z9ij4.fsf@smsnet.pl> Stef Mientki <S.Mientki-nospam at mailbox.kun.nl> writes: > I'm making special versions of existing functions, > and now I want the help-text of the newly created function to exists of > 1. an extra line from my new function > 2. all the help text from the old function > > # the old function > def triang(M,sym=1): > """The M-point triangular window. <== old help text > """ > .... > > # the new function > def chunked_triang(M): > """ Chunked version of "triang" <== the extra line > """ > > >>> help(chunked_triang) > # should give something like > > chunked_triang(M) <== the new definition > Chunked version of "triang" <== the extra line > The M-point triangular window. <== old help text > > Is that possible ? You can take advantage of the decorator syntax: >>> def triang(M,sym=1): ... """The M-point triangular window. ... """ ... return "triang" ... >>> help(triang) Help on function triang in module __main__: triang(M, sym=1) The M-point triangular window. >>> def add_doc(f): ... def wrap(g): ... g.__doc__="chunked version of %s\n%s" % (f.__name__,f.__doc__) ... return g ... return wrap ... >>> @add_doc(triang) ... def chunked_triang(M): ... return "chunked triang" ... >>> help(chunked_triang) Help on function chunked_triang in module __main__: chunked_triang(M) chunked version of triang The M-point triangular window. -- HTH, Rob From no-spam at no-spam-no-spam.invalid Thu Jan 18 04:00:02 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 18 Jan 2007 10:00:02 +0100 Subject: predefined empty base class ?? In-Reply-To: <mailman.2853.1169070963.32031.python-list@python.org> References: <1169053011.399278.290980@a75g2000cwd.googlegroups.com> <2%trh.15631$X72.7347@newsread3.news.pas.earthlink.net> <mailman.2853.1169070963.32031.python-list@python.org> Message-ID: <eonct8$ncu$1@news.albasani.net> Gabriel Genellina wrote: > At Wednesday 17/1/2007 15:34, Dennis Lee Bieber wrote: > >> > is there an predefined empty base class >> > which I can instanziate to have an >> > container i can copy attributes in? >> >> I think that's a two-liner... >> >> >>> class EmptyBase(object): >> ... pass > > Do you want a one liner? > > class EmptyBase(object): pass > > :) Isn't "predefined" a zero liner :-; From gherron at islandtraining.com Fri Jan 12 04:43:42 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 12 Jan 2007 01:43:42 -0800 Subject: How to run external program? In-Reply-To: <1168594577.397453.320380@a75g2000cwd.googlegroups.com> References: <1168594577.397453.320380@a75g2000cwd.googlegroups.com> Message-ID: <45A7584E.2080105@islandtraining.com> Lad wrote: > How can I run external program from Python? > I use Python with XP > Thank you for help > LB > > The subprocess module is what you want for this. It's got ways of running external executables as separate subprocesses, and interacting with the subprocess and both its input and output. Gary Herron From S.Mientki-nospam at mailbox.kun.nl Wed Jan 17 17:29:38 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 17 Jan 2007 23:29:38 +0100 Subject: Would a Dutch speaker please check this wiki page please? In-Reply-To: <mailman.2852.1169070591.32031.python-list@python.org> References: <mailman.2852.1169070591.32031.python-list@python.org> Message-ID: <a9dd0$45aea341$d443bb3a$10472@news.speedlinq.nl> skip at pobox.com wrote: > Got a note about a new page on the Python Wiki: > >>>>>> "Wade" == Wade McDaniel <wmcdaniel at wolfgangsvault.com> writes: > > http://wiki.python.org/moin/Selcuk_Altun > > I suspect it's junk since it doesn't seem to mention Python and the website > it mentions doesn't seem to exist. Still, just in case... The only (incorrect) Dutch sentence on the whole site is: "Welkom op me site www.keriwar.nl", which should have been "Welkom op mijn site www.keriwar.nl" but that could be explained, while his name "Selcuk Altun" is not orginated from the Netherlands. I just expect that he is trying to setup a wiki, but that's too soon to give it a judgement. cheers, Stef Mientki > > Thx, > > Skip From michele.simionato at gmail.com Tue Jan 16 00:21:06 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jan 2007 21:21:06 -0800 Subject: Watch log In-Reply-To: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> References: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> Message-ID: <1168924866.691081.251880@q2g2000cwa.googlegroups.com> Salvatore Di Fazio wrote: > Hi guys, > I've an application that writes a log file. > I need to write an application with python that will read this file. You may begin from this: $ cat showlog.py import sys from ScrolledText import ScrolledText interval =50 # ms def displayfile(f, textwidget): textwidget.insert('end', f.readline()) textwidget.after(interval, displayfile, f, textwidget) if __name__ == '__main__': st = ScrolledText() st.pack() displayfile(sys.stdin, st) st.mainloop() $ python showlog.py < mylogfile.log HTH, Michele Simionato From j.ersatz at nowhere.invalid Wed Jan 10 03:28:03 2007 From: j.ersatz at nowhere.invalid (John Ersatznom) Date: Wed, 10 Jan 2007 03:28:03 -0500 Subject: Xah's Edu Corner: Introduction to 3D Graphics Programing References: <1166836083.084101.25870@73g2000cwn.googlegroups.com> <458d7899$0$8725$ed2619ec@ptn-nntp-reader02.plus.net> <1167208399.089326.213540@a3g2000cwd.googlegroups.com> <1167230356.551596.193550@73g2000cwn.googlegroups.com> <1167255574.202660.176530@48g2000cwx.googlegroups.com> <1168270858.969940.282070@42g2000cwt.googlegroups.com> Message-ID: <eo27v6$cbf$1@aioe.org> ajsiegel at optonline.com wrote: > And the core folks around the project are either science educators or > Python folks - there is little C++ expertise currently involved with > the project. > > The project is looking for help. > > Anyone willing to jump in should perhaps reply here or at: [snip address] I see lots of mentions of C++ and Python, but not Java, so suggesting that anyone reply "here" (i.e. comp.lang.java.programmer) seems questionable to me. And what the hell is wrong with my goddam newsserver? Again it complained that a header was missing (which either should have been there to start with or not been an error) and then when I added it that the message was a duplicate (it was a duplicate only if the previous try had succeeded, but it claimed the previous try had failed). I'm thinking of ditching aioe. Anyone know of any other public, free newsservers that permit posting as well as reading? A whole lot of Web research has failed to turn up any besides aioe. Mind you, I found a lot of high quality free ones that permit reading only (some with binaries! not that I need 'em) and at least one that calls itself "free" and says it permits posting but actually charges an "account setup fee" -- where are truth in advertising laws when you need them? "Free" doesn't mean "No monthly payments" or "No recurring payments", it means FREE, as in NO PAYMENTS AT ALL, MORONS ... :P From danb_83 at yahoo.com Tue Jan 16 23:05:36 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 16 Jan 2007 20:05:36 -0800 Subject: How can I write code using FP In-Reply-To: <1169003899.592015.300290@s34g2000cwa.googlegroups.com> References: <1169003899.592015.300290@s34g2000cwa.googlegroups.com> Message-ID: <1169006736.225375.7140@51g2000cwl.googlegroups.com> On Jan 16, 9:18 pm, "kernel1983" <kernel1... at gmail.com> wrote: > In Function Program?Language can use like this: > > define a function: > f = lambda x,y:x,y > > then we use f to define another function: > f2 = f(1) > the f2 should equal to: > f2=lambda y:1,y > > we should be able call f2 with one parameter:f2(2) > just return 1,2 > > but how can I implement the characteristic in Python??I think it could > do like this but HOW-TO? > > thanks~~~ > I'm a English beginner! > I wish somebody understand my meaning If I understand correctly, you can do: f = lambda x, y: (x, y) f2 = lambda y: f(1, y) From nszabolcs at gmail.com Tue Jan 30 08:26:44 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 30 Jan 2007 05:26:44 -0800 Subject: Is any python like linux shell? In-Reply-To: <mailman.3301.1170153234.32031.python-list@python.org> References: <mailman.3301.1170153234.32031.python-list@python.org> Message-ID: <1170163604.787488.194690@m58g2000cwm.googlegroups.com> Brian Visel wrote: > ipython is probably what you're looking for. or http://sourceforge.net/projects/pyshell From ggrp1.20.martineau at dfgh.net Wed Jan 10 10:33:56 2007 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 10 Jan 2007 07:33:56 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> <1168048620.409190.85870@v33g2000cwv.googlegroups.com> <1168130960.670978.111850@s34g2000cwa.googlegroups.com> <1168209637.965967.23790@s34g2000cwa.googlegroups.com> Message-ID: <1168443236.166170.265770@77g2000hsv.googlegroups.com> Carl Banks wrote: > Martin Miller wrote: > > Carl Banks wrote: > > > > > Martin Miller wrote: > > > > ### non-redundant example ### > > > > import sys > > > > > > > > class Pin: > > > > def __init__(self, name, namespace=None): > > > > self.name = name > > > > if namespace == None: > > > > # default to caller's globals > > > > namespace = sys._getframe(1).f_globals > > > > namespace[name] = self > > > > > > > > Pin('aap') # create a Pin object named 'aap' > > > > Pin('aap2') # create a Pin object named 'aap2' > > > > print aap.name > > > > print aap2.name > > > > > > The problem with this is that it only works for global namespaces, > > > while failing silently and subtly if used in a local namespace: > > > > Oh, contrair. It would work fine with local namespaces simply by > > overriding the default value of the optional 'namepace' parameter (see > > below). > > Did you try it? Yes, but I misinterpreted the results which seemed to support my claim. Therefore I must retract what I wrote and now have to agree with what you said about it not working in a local namespace -- specifically in the sense that it is unable to bind the instance the name in the caller's local namespace. I'm not sure that this is a critical flaw in the sense that it may not matter for some usages. For example I've seen it used to define (yet another) Enum class which facilitated the creation of names bound to a range or sequence of values. The fact that these couldn't be defined local to code block wasn't apparently a big issue. > > > def fun(): > > > Pin('aap') > > > aap1 = aap > > > fun2() > > > aap2 = aap > > > print aap1 is aap2 > > > > > > def fun2(): > > > Pin('aap') > > > > > > If it's your deliberate intention to do it with the global namespace, > > > you might as well just use globals() and do it explicitly, rather than > > > mucking around with Python frame internals. (And it doesn't make the > > > class unusable for more straightforward uses.) > > > > You could be more explicit by just passing 'globals()' as a second > > parameter to the __init__ constructor (which is unnecessary, since > > that's effectively the default). > > > > It's not clear to me how the example provided shows the technique > > "failing silently and subtly if used in a local namespace" because what > > happens is exactly what I would expect if the constructor is called > > twice with the same string and defaulted namespace -- namely create > > another object and make the existing name refer to it. If one didn't > > want the call to Pin in fun2 to do this, just change fun2 to this: > > Because the usage deceptively suggests that it defines a name in the > local namespace. Failing may be too strong a word, but I've come to > expect a consistent behavior w.r.t. namespaces, which this violates, so > I think it qualifies as a failure. I don't see how the usage deceptively suggests this at all. In this case -- your sample code for fun() and fun2() -- all were simply Pin('aap'). Since no additional namespace argument was supplied, the same name was bound in the defaulted global namespace each time but to different objects. In other words the 'print aap1 is aap2' statement produced 'false' because the call to fun2() changed the (global) object to which 'aap' was previously bound. > > > def fun2(): > > Pin('aap', locals()) > > Did you actually try this? ... As I said, yes, I did, and the addition of the 'locals()' parameter does make the 'print aap1 is aap2' statement in fun() output 'true'. This lead me to take for granted that it had bound the name in the local namespace. However this assumption was incorrect, but that wasn't obvious since there were no further statements in fun2(). The problem is that there fundamentally doesn't seem to be a way to create local variables except directly by using an assignment statement within the block of a function or method. Modifying the mapping returned from locals() does not accomplish this -- normally anyway, although interestingly, it will currently if there's an exec statement anywhere in the function, even a dummy one, but this is not a documented feature and from what I've read just side-effect of the way code optimization is be done to support the exec statement. > ... Better yet, try this function. Make sure > aap isn't defined as a global: > > def fun3(): > Pin('aap',locals()) > print aap > > (I get NameError.) I do, too, if I run it by itself or first unbind the global left over from fun() with a 'del aap' statement. > > This way the "print aap1 is aap2" statement in fun() would output > > "true" since the nested call to Pin would now (explicitly) cause the > > name of the new object to be put into fun2's local namespace leaving > > the global one created by the call in fun() alone. > > Did you try it? Yes -- explained above. > > Obviously, this was not an objection I anticipated. An important one I > > would think is the fact that the current documentation says that > > f_globals is a special *read-only* attribute of a frame object implying > > that it shouldn't be changed (even though doing so 'works' as my > > example illustrates). > > That means it can't be rebound. It doesn't mean you can't modify the > object. Nevertheless, frame objects are an internal feature of Python, > not guaranteed to work for other incarnations of Python (it doesn't > even exist in IronPython, for example), and subject to change. And > what you want to do is easily done in a platform generic way without > using sys._getframe. Since '_getframe' starts with an underscore, by convention it's something private, likely an implementation detail, and therefore not guaranteed not to change in future. Similarily the documentation says it "should be used for internal and specialized purposes only". Guess I should have mentioned that this was also an expected complaint when I warned the OP that some people would oppose the use of the technique. My own philosophy is that it's simply a judgment call that depends on what you're doing and what are the alternatives. Not all code is mission-critical and even with that which is, it may perhaps be worth the risk of possible issues later in future in order to have something now that works in your present environment. > > I think other valid arguments against this practice might include > > whether it's an example of good OOP, or a good programming practice at > > all, since it involves possibly subtle side-effects, the use of global > > variables, and/or is 'unpythonic'. > > I think programmatically creating variables is fine; I just recommend > you not use sys._getframe, nor the automagical namespace self-insertion > class, to do it. You've explained some of your worries about sys._getframe. It would be interesting to hear specifically what it is you don't like about the idea of namespace self-insertion -- mainly because of the local namespace limitation? > > Certainly the approach is not without caveats. Despite them, I believe > > it can be useful in some contexts, as long as what is going on is > > clearly understood. The point of my reply to the OP was mainly just to > > illustrate the power and flexibility of Python to the newbie. I guess > > to that I should have also added that it gives you "enough rope to > > shoot yourself" as Allen Holub said regarding C++. > > > > Cheers, > > -Martin > > Carl Banks Regards, -Martin From nogradi at gmail.com Sat Jan 13 06:49:32 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 13 Jan 2007 12:49:32 +0100 Subject: Barcode recognition in Python In-Reply-To: <1168676514.115592.181620@v45g2000cwv.googlegroups.com> References: <1168676514.115592.181620@v45g2000cwv.googlegroups.com> Message-ID: <5f56302b0701130349t317f375av10713d489577c74e@mail.gmail.com> > I am searching for a python library for barcode recognition. We have > developed a rather complex application for document tracking and > document management in python/Zope, called PAFlow (www.paflow.it: > sorry, most of the information is in Italian...). > > As our project is completely free software, we will need a library that > is free software too. > > Is there something like this in python ? http://www.google.com/search?q=barcode+recognition+python From rpdooling at gmail.com Sat Jan 13 22:59:17 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 Jan 2007 19:59:17 -0800 Subject: indentation in python In-Reply-To: <1168742956.828457.287610@m58g2000cwm.googlegroups.com> References: <1168742956.828457.287610@m58g2000cwm.googlegroups.com> Message-ID: <1168747148.932238.51880@51g2000cwl.googlegroups.com> lee wrote: > Can anyone tell me the basics about indentation in python......how we > use it in loops and constructs..etc.... http://docs.python.org/tut/node5.html#SECTION005200000000000000000 From S.Mientki-nospam at mailbox.kun.nl Mon Jan 22 14:44:42 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 22 Jan 2007 20:44:42 +0100 Subject: Python Windows Editors In-Reply-To: <ep33ul$6cr$1@atlantis.news.tpi.pl> References: <p5Qsh.51413$wc5.6534@newssvr25.news.prodigy.net> <ep33ul$6cr$1@atlantis.news.tpi.pl> Message-ID: <ea71a$45b5141c$d443bb3a$3908@news.speedlinq.nl> Any text editor is only as good as the > programmer who uses it. ;) > Yes but an IDE is different ;-) cheers, Stef Mientki From jon at ffconsultancy.com Mon Jan 1 13:56:47 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 01 Jan 2007 18:56:47 +0000 Subject: Writing more efficient code References: <mailman.2185.1167676577.32031.python-list@python.org> Message-ID: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> gonzlobo wrote: > I picked up Python a few weeks ago, and have been able to parse large > files and process data pretty easily, but I believe my code isn't too > efficient. I'm hoping dictionaries will help out, but I'm not sure the > best way to implement them. > > I've been using a bunch of nested if/elif/else statements to select > slices (0317 & 03de) from a file, then parse the data (aa, hh, bb, > d2-d9) into parameters (a = airspeed, h = heading) & flags. > > #sample file contents > 0000007d 03 0317 aa aa aa aa aa hh hh hh bb bb > 0000007e 06 03de d2 d3 d4 d5 d6 d7 d8 d9 10 11 > > # some pseudo code > if PID == '03de': > flapsCmd = int(d3, 16) > if flapsCmd == 0xc0: > <flaps up code> > elif flapsCmd == 0x03: > <flaps down code> > if PID == '0317': > airspeed == 'combine aa for airspeed & multiply by 0.1' > heading == 'combine hh for heading' > mach == 'combine bb for mach & multiply by 0.01' > > Might dictionaries help in this case... say Label0317(parameterName, > slice (d3), scaleFactor(0.1))... I'd like to use them if they'll > replace the dozens of nested conditionals. Sounds like you want pattern matching over lists: | 0x03 :: 0xde :: 0xc0 :: t -> <flaps up code> | 0x03 :: 0xde :: 0x03 :: t -> <flaps down code> | 0x03 :: 0x17 :: t -> ... That's OCaml code which finds patterns in sequences of bytes, just like the ones you're searching for. > I have roughly 75 > different parameters to decode from a file containing ~2.5 million > lines of data. > > I know my pseudo code lacks details, but hopefully I'm getting my > point across... > > (I suppose switch/select/case statements would help a bit, but python > doesn't seem to use them... not to start a religious war or anything). Pattern matching is "switch" on steroids. OCaml's pattern matcher is very sophisticated and very fast. You'll probably shrink your code by several fold whilst also having it run a few orders of magnitude faster and having it statically checked, so it will be more reliable. You might want to look at any language with pattern matching: OCaml, SML, Haskell, F#, Mathematica etc. If you're running Windows then F# is a .NET language... -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet From deets at nospam.web.de Fri Jan 5 03:11:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Jan 2007 09:11:28 +0100 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: <sA2nh.13518$yC5.6094@newssvr27.news.prodigy.net> References: <G3Qmh.94$9v1.124@nntpserver.swip.net> <1167839629.435980.311750@k21g2000cwa.googlegroups.com> <mailman.2245.1167841661.32031.python-list@python.org> <5034u9F1dg9r9U1@mid.uni-berlin.de> <sA2nh.13518$yC5.6094@newssvr27.news.prodigy.net> Message-ID: <506fhgF1efoisU1@mid.uni-berlin.de> >> It is definitely _not_ possible. There are so many design decisions >> that are differing based on what a language offers - e.g. generators, >> garbage collection, precise control over memory layout and so on. > > Inter-language translators have been written. There's usually > a performance penalty, which can be severe when the idioms of > the languages are quite different. The point discussed here was not the feasibility of language-translators per se. These are certainly possible, yet I doubt that e.g. C++2Python would really come to existence. Thomas expressed his belief that a _idiomatic_ translator was possible. And that certainly isn't the case. Diez From sebastien.thur at laposte.net Wed Jan 17 03:08:52 2007 From: sebastien.thur at laposte.net (seb) Date: 17 Jan 2007 00:08:52 -0800 Subject: connection to server not accepted (but no error) only after several hours In-Reply-To: <Ip8rh.15194$X72.12298@newsread3.news.pas.earthlink.net> References: <1168961973.099821.318920@l53g2000cwa.googlegroups.com> <Ip8rh.15194$X72.12298@newsread3.news.pas.earthlink.net> Message-ID: <1169021332.523258.192510@s34g2000cwa.googlegroups.com> Hi Dennis, I am using indeed using python logging in the appel_log2 module. But I wanted to keep it extremly simple while accepting connection from different processes or thread. Regarding my main problem, I did some more testing : 1) I have enabled one time server that can be run as a service (R C C time server) and this service is responding correctly, when at the same time (before I kill it ) the python time server is not responding. 2) I have also tried two python time server downloaded from effbot site. Both are not responding after the "non response from the time server I rn" even for the first interrogation once they are started. (Of course I have killed my time server when I run a new one). Same behaviour no response given but no error neither. 3) If I try to start the R c c time server when the python time server is running there is an error (from the rcc service) The python time server program is really bound to port 37. if we look at the previous tests : 4) The same python program runned on port 38 aftter the blocking is working properly from the start. 5) There is no exception on the python time server whether it is responding or not. -------------------------- partial conclusion ------------------------- It is only python programs that are listening from the port 37 that are blocked at a certain time. How is it possible (without firewall enabled) ? Thanks . Sebastien. Dennis Lee Bieber a ?crit : > On 16 Jan 2007 07:39:35 -0800, "seb" <sebastien.thur at laposte.net> > declaimed the following in comp.lang.python: > > > > > Once it is blocked, I killes it, wait for about 15 minutes without > > running the server and then started again but this gives me the same > > behaviour (no response). > > > Can't help with the lock-up problem... but... > > > > import socket > > import struct, time > > import threading > > import os > > import appel_log2 as appel_log > > import sys > > > > > > class TimeServer(threading.Thread) : > > def __init__(self): > > nom_function_actuelle= str(sys._getframe().f_code.co_filename) > > +"___"+str(sys._getframe().f_code.co_name) > > try : > > threading.Thread.__init__(self) > > self.log_file="timeserverlog.txt" > > self.PORT=37 > > self.TIME1970=2208988800L > > self._continue=1 > > self.time_shift=0 > > message=nom_function_actuelle+"\t "+"STARTED OK " > > appel_log.write_log("info",message) > > Have you considered using Python's logging module? > > while 1==1 : > > Redundant test... > > In all historical versions of Python > > while 1: > > sufficed, and newer versions have > > while True: > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From sebastien.thur at laposte.net Tue Jan 16 10:39:35 2007 From: sebastien.thur at laposte.net (seb) Date: 16 Jan 2007 07:39:35 -0800 Subject: connection to server not accepted (but no error) only after several hours Message-ID: <1168961973.099821.318920@l53g2000cwa.googlegroups.com> Hi, this simple server (time protocol) does not respond after a few hours, even when it is restarted. The behaviour looks to me like a firewall blocking but I have desabled the firewall. Using Netstat - a I find the server listed when it is running and not listed when I stop it. The server starts whith no error. But after about 6-8 hours there is no way to make it respond again (even when it is restarted). Once it is blocked, I killes it, wait for about 15 minutes without running the server and then started again but this gives me the same behaviour (no response). The solution at this time is to reboot windows !!! I have also tried to run it twice in order to get the exception that the port is already used and an exeption is raised. I have tried from another computer to connect to mine but it does not manage. When I change the port in the server it responds immediatly. I am running winXP SP2, python 2.4. Do you have any clues ? Thanks in advance. Seb. PS : I am calling this server from another program and make it run in a thread. Below is the standalone version (wich is adpated from effbot site). import socket import struct, time import threading import os import appel_log2 as appel_log import sys class TimeServer(threading.Thread) : def __init__(self): nom_function_actuelle= str(sys._getframe().f_code.co_filename) +"___"+str(sys._getframe().f_code.co_name) try : threading.Thread.__init__(self) self.log_file="timeserverlog.txt" self.PORT=37 self.TIME1970=2208988800L self._continue=1 self.time_shift=0 message=nom_function_actuelle+"\t "+"STARTED OK " appel_log.write_log("info",message) except Exception, e : message=nom_function_actuelle+"\t "+"PB:::"+str(e) print message appel_log.write_log("warning",message) def set_log_file(self, file): nom_function_actuelle= str(sys._getframe().f_code.co_filename) +"___"+str(sys._getframe().f_code.co_name) if os.path.exists(file): pass else : f=open(file,"w") f.close() self.log_file=file print "log file ",self.log_file self.log_file=file def reset_log_file(self): nom_function_actuelle= str(sys._getframe().f_code.co_filename) +"___"+str(sys._getframe().f_code.co_name) print "resetting log file " if os.path.exists(self.log_file): f=open(self.log_file,"w") f.close() def set_time_shift(self,time_shift): self.time_shift=time_shift def run(self): nom_function_actuelle= str(sys._getframe().f_code.co_filename) +"___"+str(sys._getframe().f_code.co_name) socket.timeout(1) service=socket.socket(socket.AF_INET, socket.SOCK_STREAM) service.bind(("", self.PORT)) service.listen(1) print "listening on port", self.PORT while self._continue==1 : channel, info = service.accept() print "connection from", info message=str(time.time())+"\t"+str(time.asctime())+"\t"+str(info)+"\n" g=open(self.log_file,"a") g.write(message) g.close() t = int(time.time()) + self.TIME1970 + self.time_shift t = struct.pack("!I", t) channel.send(t) # send timestamp channel.close() # disco m=nom_function_actuelle+" response OK "+str(info) appel_log.write_log("info",m) #print "apres m " print "time server self_continue=0" appel_log.write_log("warning",nom_function_actuelle+"\t self._continue ="+str(self._continue)) print "sortie du thread" def main() : a=TimeServer() a.start() a.set_log_file("log_nw.txt") a.reset_log_file() while 1==1 : time.sleep(10) #a._continue=0 pass time.sleep(2) main() From deets at nospam.web.de Wed Jan 3 10:31:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Jan 2007 16:31:50 +0100 Subject: code optimization (calc PI) References: <hOPmh.82$9v1.124@nntpserver.swip.net> Message-ID: <5020j6F1du59cU1@mid.uni-berlin.de> mm wrote: > (Yes, I konw whats an object is...) > BTW. I did a translation of a pi callculation programm in C to Python. > (Do it by your own... ;-) Is that a question on how to optimize code you won't show us? If yes, I'm sorry to tell you that crystal balls are short these days. Too much new-year-outlooks. Diez From ramashish.lists at gmail.com Mon Jan 22 01:12:26 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 21 Jan 2007 22:12:26 -0800 Subject: Accessing class variables in staticmethods. References: <1169412557.737589.105120@a75g2000cwd.googlegroups.com> <mailman.2960.1169413216.32031.python-list@python.org> Message-ID: <1169446346.871829.76500@a75g2000cwd.googlegroups.com> Sam wrote: > On 21 Jan 2007 12:49:17 -0800, Ramashish Baranwal > <ramashish.lists at gmail.com> wrote: > > class Base: > > staticvar = 'Base' > > > > @staticmethod > > def printname(): > > # this doesn't work > > # print staticvar > > # this does work but derived classes wouldn't behave as I want > > print Base.staticvar > > > > class Derived(Base): > > staticvar = 'Derived' > > > > Base.printname() # should print 'Base' > > Derived.printname() # should print 'Derived' > > > > Any idea on how to go about this? Also from a staticmethod how can I > > find out other attributes of the class (not objects)? Do static methods > > get some classinfo via some implicit argument(s)? > > No, staticmethods get told nothing about the class they're being > defined in. What you want is a classmethod, which gets passed the > class to work with. > > Using classmethods, your code becomes: > > #untested, bear in mind > class Base: > staticvar = 'Base' > > @classmethod > def printname(cls): > print cls.staticvar > > class Derived(Base): > staticvar = 'Derived' > > Base.printname() #prints 'Base' > Derived.printname() #prints 'Derived' > > Incidentally, you can also use cls.__name__ for this purpose, but I > guess that your actual motivation for this is more complicated than > class names. Thanks Sam, using classmethod works. You guessed it correctly, my actual motivation is more complicated but on the same line. -Ram From emin.shopper at gmail.com Wed Jan 17 11:08:53 2007 From: emin.shopper at gmail.com (Emin) Date: 17 Jan 2007 08:08:53 -0800 Subject: question about module resolution Message-ID: <1169050133.438101.90030@a75g2000cwd.googlegroups.com> Dear Experts, I often find myself wanting to have a child module get some parameters defined in a parent module. For example, imagine I have the following directory structure and want something in baz.py to look at a value in config.py. I end up putting in things like import sys; sys.path.append('../..'). Is there a better way? foo/ __init__.py config.py bar/ __init__.py baz.py From istvan.albert at gmail.com Wed Jan 10 15:04:44 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 10 Jan 2007 12:04:44 -0800 Subject: Announcement -- ZestyParser References: <1168407920.281020.147680@k58g2000hse.googlegroups.com> <mailman.2542.1168453354.32031.python-list@python.org> Message-ID: <1168459484.164931.65460@k58g2000hse.googlegroups.com> Terry Reedy wrote: > I would like to look at the examples online (along with the doc file) > before downloading this and setuptools and installing, so I can see what > it actually looks like in use. Yes, I second that. I poked around for a little while but could not find a single example. Then I gave up as I'm not going to install something before knowing what it is. i. From smusnmrNOSPAM at yahoo.com Thu Jan 4 08:12:17 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Thu, 4 Jan 2007 14:12:17 +0100 Subject: pow() works but sqrt() not!? References: <enicv3$cmoq$1@zam602.zam.kfa-juelich.de><1167899693.759071.51450@31g2000cwt.googlegroups.com><enig9a$cncb$1@zam602.zam.kfa-juelich.de> <mailman.2282.1167913096.32031.python-list@python.org> Message-ID: <eniuf8$cq4v$1@zam602.zam.kfa-juelich.de> Thanks for the explanation. I am astonished what an interpreted language is able to do! "Fredrik Lundh" <fredrik at pythonware.com> schrieb im Newsbeitrag news:mailman.2282.1167913096.32031.python-list at python.org... > "siggi" wrote: > >> Nope, I did not! But I used sqrt(9), and not math.sqrt(9). The latter >> works >> excellent, thank you! From now on, I will use "import math" and >> "math.fuction()" for EVERY mathematical function, even for pow() etc. >> just >> to be on the safe side! > > pow and math.pow are two slightly different things, though. pow() works > on > any type that supports power-of operations (via the __pow__ hook), while > math.pow treats everything as a 64-bit float: > >>>> math.pow(2, 200) > 1.6069380442589903e+060 > >>>> pow(2, 200) > 1606938044258990275541962092341162602522202993782792835301376L > > pow also takes a third modulo argument (pow(x,y,z) is equivalent to > pow(x,y) % z, > but can be implemented more efficiently for certain data types). > > </F> > > From jordan.taylor2 at gmail.com Thu Jan 25 13:02:29 2007 From: jordan.taylor2 at gmail.com (Jordan) Date: 25 Jan 2007 10:02:29 -0800 Subject: running applications in python In-Reply-To: <1169746124.376610.139420@13g2000cwe.googlegroups.com> References: <1169746124.376610.139420@13g2000cwe.googlegroups.com> Message-ID: <1169748148.918473.37840@k78g2000cwa.googlegroups.com> os.system, os.spawn, the process module, os.popen[1,2,3,4], this is a pretty basic thing, not trying to be mean, but you should look in the python docs, this is definitely in there. Also, the subprocess module is meant to replace all of those but i haven't looked too closely at it yet, so the following might not be perfect. import subprocess as sp sp.call(['wmplayer.exe', 'some_args_probably_a_movie_name']) you'll probably need to use the full path for media player, and the call() function is a simplified command within the subprocess module, useful if you don't really need to redirect input/output/errors or other aspects of the opened application. Also, you'll probably want something more like: retcode = sp.call(...), so that you can check the return code to see if it was successful. Check out the subprocess module. Cheers, Jordan On Jan 25, 12:28 pm, "lee" <libi... at gmail.com> wrote: > how can i run or open a windows application from the python prompt?for > e.g.mediaplayer opening,folder acess etc From brent.chambers at gmail.com Tue Jan 2 14:33:23 2007 From: brent.chambers at gmail.com (brent.chambers at gmail.com) Date: 2 Jan 2007 11:33:23 -0800 Subject: Python embedded interpreter: how to initialize the interpreter ? In-Reply-To: <mailman.2206.1167752577.32031.python-list@python.org> References: <1167573333.723607.199480@v33g2000cwv.googlegroups.com> <mailman.2206.1167752577.32031.python-list@python.org> Message-ID: <1167766403.470097.71890@i12g2000cwa.googlegroups.com> > >the interpreter emits an error: tkinter module not defined Capitalize the 't', in Tkinter, its case sensitive. From bdesth.quelquechose at free.quelquepart.fr Tue Jan 16 17:54:00 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 Jan 2007 23:54:00 +0100 Subject: How can I create a linked list in Python? In-Reply-To: <eojb9v$92rq$1@netnews.upenn.edu> References: <eoj6rr$90bt$1@netnews.upenn.edu> <mailman.2791.1168975031.32031.python-list@python.org> <eojb9v$92rq$1@netnews.upenn.edu> Message-ID: <45ad5104$0$393$426a74cc@news.free.fr> Dongsheng Ruan a ?crit : > Thanks for your kindly help. > I am new CS student taking datat structure and algorithms with AHO's book > with the same title. > > The book is done in Pascal, which might be an outdated language. Yes, somehow - but note, that linked lists are the central data structure of Lisp, which is probably the older programming language still in use... Implementing linked lists in Python is not a great deal - it just doesn't make much sens. It's IMHO much more interesting to learn this kind of stuff with a low-level language like C or Pascal. > However, my instructor probably wants us to understand the list ADT better > by not using the built in list in Python. Indeed !-) From fumanchu at amor.org Mon Jan 15 19:02:03 2007 From: fumanchu at amor.org (fumanchu) Date: 15 Jan 2007 16:02:03 -0800 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <pan.2007.01.15.03.43.54.630644@REMOVEME.cybersource.com.au> <pan.2007.01.15.04.00.13.948798@REMOVEME.cybersource.com.au> Message-ID: <1168905723.452739.8600@a75g2000cwd.googlegroups.com> Steven D'Aprano wrote: > > class Rational(object): > > def __init__(self, numerator, denominator): > > print "lots of heavy processing here..." > > # processing ints, floats, strings, special case arguments, > > # blah blah blah... > > self.numerator = numerator > > self.denominator = denominator > > def __copy__(self): > > cls = self.__class__ > > obj = cls.__new__(cls) > > obj.numerator = self.numerator > > obj.denominator = self.denominator > > return obj > > def __neg__(self): > > obj = self.__copy__() > > obj.numerator *= -1 > > return obj > > > Here's a variation on that which is perhaps better suited for objects with > lots of attributes: > > def __copy__(self): > cls = self.__class__ > obj = cls.__new__(cls) > obj.__dict__.update(self.__dict__) # copy everything quickly > return obj I recently had to do something similar for my ORM, where a user-instantiated object gets expensive default values, but the back end just overwrites those defaults when "resurrecting" objects, so it shouldn't pay the price. However (and this is the tricky part), I also wanted to allow subclasses to extend the __init__ method, so just using cls.__new__(cls) didn't quite go far enough. Here's what I ended up with [1]: def __init__(self, **kwargs): self.sandbox = None cls = self.__class__ if self._zombie: # This is pretty tricky, and deserves some detailed explanation. # When normal code creates an instance of this class, then the # expensive setting of defaults below is performed automatically. # However, when a DB recalls a Unit, we have its entire properties # dict already and should skip defaults in the interest of speed. # Therefore, a DB which recalls a Unit can write: # unit = UnitSubClass.__new__(UnitSubClass) # unit._zombie = True # unit.__init__() # unit._properties = {...} # instead of: # unit = UnitSubClass() # unit._properties = {...} # If done this way, the caller must make CERTAIN that all of # the values in _properties are set, and must call cleanse(). self._properties = dict.fromkeys(cls.properties, None) else: # Copy the class properties into self._properties, # setting each value to the UnitProperty.default. self._properties = dict([(k, getattr(cls, k).default) for k in cls.properties]) # Make sure we cleanse before assigning properties from kwargs, # or the new unit won't get saved if there are no further changes. self.cleanse() for k, v in kwargs.iteritems(): setattr(self, k, v) The _zombie argument is therefore a flag which allows you to keep the initialization code inside __init__ (rather than repeating it inside every method). Robert Brewer System Architect Amor Ministries fumanchu at amor.org [1] http://projects.amor.org/dejavu/browser/trunk/units.py#l552 From basti.wiesner at gmx.net Sun Jan 7 13:16:49 2007 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sun, 07 Jan 2007 19:16:49 +0100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <mailman.2394.1168189690.32031.python-list@python.org> Message-ID: <enrdeh$utj$01$1@news.t-online.com> [ Thomas Ploch <Thomas.Ploch at gmx.net> ] > sturlamolden schrieb: >> time.swift at gmail.com wrote: >>> Coming from a C++ / C# background, the lack of emphasis on private >>> data seems weird to me. I've often found wrapping private data >>> useful to prevent bugs and enforce error checking.. >>> >>> It appears to me (perhaps wrongly) that Python prefers to leave >>> class >>> data public. What is the logic behind that choice? >> >> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think >> that if an object's 'internal' variables or states cannot be kept >> private, programmers get an irresistible temptation to mess with them >> in malicious ways. But if you are that stupid, should you be >> programming in any language? The most widely used language is still >> C, and there is no concept of private data in C either, nor is it >> needed. > > There is a kind of this concept in C with 'static' declarations. > >> As mentioned in other replies, it is not rocket science to access a >> class private data. In C++ you can cast to void*, in Java and C# you >> can use reflection. C++ is said to be an "unsafe" language because >> programmers can, using a few tricks, mess with the vtables. But how >> many really do that? > > Exactly, if they were available, a lot more would do that. I think > this is the point. Programmers who can do that normally are sensible > towards that people who have designed this or that knew what they were > doing. But there are enough people that don't have a clue and _will_ > fiddle around and then flame all kind of mailing lists with requests > for help cause they did it wrong. Those people deserve to fail for being just extraordinary stupid... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From rkmr.em at gmail.com Mon Jan 29 21:45:40 2007 From: rkmr.em at gmail.com (mark) Date: Mon, 29 Jan 2007 18:45:40 -0800 Subject: creating a dictionary Message-ID: <e04d2e90701291845v46f56c7eged842e7a7b6d99e@mail.gmail.com> i have few variables and i want to create a dictionary with these variables such that the keys are the variable names and the corresponding values are the variable values.how do i do this easily? for ex: var1='mark' var2=['1','2','3'] my_dict = create_my_dictionary(var1, var2) and my_dict is {'var1':'mark', 'var2':['1','2','3']} is there a function for create_my_dictionary? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070129/5f0be9eb/attachment.html> From yinxianglong at gmail.com Sat Jan 20 01:57:30 2007 From: yinxianglong at gmail.com (=?GB2312?B?0vzP6cH6?=) Date: Sat, 20 Jan 2007 14:57:30 +0800 Subject: How to implement recording scripts of operating IE as loadrunner? Message-ID: <977252d80701192257n5d3fd0f2n904fff09d2846135@mail.gmail.com> hello all. I intend to implement recording scripts of operating IE as the function of loadrunner. How can I implement in python. Any suggestions would be appreciated. XiangLong -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070120/9129e2f9/attachment.html> From steven.bethard at gmail.com Sun Jan 28 01:37:13 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 27 Jan 2007 23:37:13 -0700 Subject: distutils, sdist and tests In-Reply-To: <mailman.3240.1169963498.32031.python-list@python.org> References: <Jaudna0fMYmIBCbYnZ2dnUVZ_sKunZ2d@comcast.com> <mailman.3235.1169934632.32031.python-list@python.org> <udOdnWW5l4N-jCHYnZ2dnUVZ_v-tnZ2d@comcast.com> <mailman.3237.1169954787.32031.python-list@python.org> <Ka6dnVhMa4-CqyHYnZ2dnUVZ_syunZ2d@comcast.com> <mailman.3240.1169963498.32031.python-list@python.org> Message-ID: <4a6dnWtvro0L2SHYnZ2dnUVZ_vzinZ2d@comcast.com> Robert Kern wrote: > Steven Bethard wrote: >> Robert Kern wrote: > >>> Are you sure that you don't have changes left over in your setup.py when you >>> tested that? >> Yep. (Though I still cleared everything out and tried it again.) >> Here's what I got using an unmodified setup.py and the MANIFEST.in you >> suggested. Note that the "bdist" version is putting test_argparse.py >> into site-packages. > >> > python setup.py bdist_dumb >> running bdist_dumb >> running build >> running build_py >> installing to build\bdist.win32\dumb >> running install >> running install_lib > > Are you sure that you removed the build/ directory? Ahh thanks. Sorry I thought I was supposed to remove the old stuff from dist/ not from build/. Yes, I get the same behavior as you do when I remove build/. Sorry for the confusion! Steve From Barry.Carroll at psc.com Wed Jan 17 15:44:20 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 17 Jan 2007 12:44:20 -0800 Subject: OT: Apology Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A84@eugsrv400.psc.pscnet.com> Greetings: I've been trying to get the contributors to this thread to move their discussion to a more appropriate forum, but the unintended result has been more spam on this forum. My apologies to the regular readers of this newsgroup. This will be my last public post on this subject. I just hope the other posters will follow suit. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: st911 at rock.com [mailto:st911 at rock.com] > Sent: Wednesday, January 17, 2007 12:24 PM > To: python-list at python.org > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > > David Bostwick wrote: > > In article <1169061116.677288.213840 at 38g2000cwa.googlegroups.com>, > st911 at rock.com wrote: > > > > > >David Bostwick wrote: > > > > [...] > > > > >Indeed, the 19 hijacker theory is a fairy tale based on illogical > > >forensic investigation. > > >As for dissent, Bush is on video record to utter, "Lets not tolerate > > >any conspiracy theories." > > >The video is floating on the internet for you to see if you had the IQ > > >to search for it. > > > > > > > No, I think I'm smart enough to find it. I just don't care to waste > time on > > crackpot theories. Good ad hominem, though - "You disagree with me, so > you > > must be an idiot." Judging from where you posted this, you're the > clueless > > one. > > You dont have to waste any time. google seach is very fast. I already > posted links for you. These are even videos so if you are challenged > to read english prose, that wont be a handicap. > From lakshmikarri at gmail.com Wed Jan 24 11:02:14 2007 From: lakshmikarri at gmail.com (lucky) Date: 24 Jan 2007 08:02:14 -0800 Subject: The blog on Pc trouble shooting skills,Networking,Linux Message-ID: <1169654534.808621.309100@13g2000cwe.googlegroups.com> HI Friends This blog is very useful to all sections of people. For Pc trouble shooting skills,Linux,Html Webdesigning,Free softwares,Networking skills,Gaming news and For Tips visit the blog: http://technodata.blogspot.com From tjreedy at udel.edu Mon Jan 29 02:24:24 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Jan 2007 02:24:24 -0500 Subject: Data structure and algorithms References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> Message-ID: <epk7f5$6ha$1@sea.gmane.org> "azrael" <jura.grozni at gmail.com> wrote in message news:1170024965.321036.206010 at m58g2000cwm.googlegroups.com... | Hy, i am a student and in 2 days I am writing a test in data | structures and algorithms. I've done my homework and understood all | the implementations and structures. My profesor was so kind to allow | us to use any programing language we want, and I'd like to use | pythhon. At the first look it looked great, but we are not allowed to | use the built in functions like append(), so i have to write my own. | I tried it like this: | | class Node: | def __init__(self, cargo=None, next=None): | self.cargo = cargo | self.next = next | | def __str__(self): | return str(self.cargo) | | | then | | >>> node1 = Node(1) | >>> node2 = Node(2) | >>> node3 = Node(3) | | >>> node1.next = node2 | >>> node2.next = node3 This is the standard idiom in Python for linked lists and other linked structures and perhaps what you should be doing. | | but this was not dinamicly enough for me (or my prof.) so dynamic? I have no idea what you mean by 'not dynamic enough'. Python is not C or C++. It does not have pointers. Trying to program in C in Python does not work too well. Terry Jan Reedy From steven.bethard at gmail.com Wed Jan 31 23:23:26 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 31 Jan 2007 21:23:26 -0700 Subject: How to sort using hash's key? In-Reply-To: <mailman.3381.1170289483.32031.python-list@python.org> References: <mailman.3375.1170284622.32031.python-list@python.org> <wt-dnXMFALATslzYnZ2dnUVZ_qXinZ2d@comcast.com> <mailman.3381.1170289483.32031.python-list@python.org> Message-ID: <HPmdnbBJ44qr9lzYnZ2dnUVZ_vbinZ2d@comcast.com> Ben Finney wrote: > Steven Bethard <steven.bethard at gmail.com> writes: > >> JoJo wrote: >>> I want to sort a dict via its key,but I have no idea on how to do >>> it. >>>>> d = dict(a=2, b=1) >>>>> for key in sorted(d): >> ... print key, d[key] >> ... >> a 2 >> b 1 > > That's not a solution to "sort the dict"; that's getting a particular > representation of the dict. It's likely the original poster wants the > equivalent to list.sort() instead of a one-time output of the > contents. Yes, but as others have pointed out, you can't get that with a standard Python dict. 99% of the time when a poster asks about how to sort a dict, their problem can be solved by simply sorting the dict keys or values. STeVe From cesar.ortiz at gmail.com Fri Jan 5 06:09:30 2007 From: cesar.ortiz at gmail.com (cesar.ortiz at gmail.com) Date: 5 Jan 2007 03:09:30 -0800 Subject: Using sax libxml2 html parser Message-ID: <1167995370.789361.43410@v33g2000cwv.googlegroups.com> Hi all, I have created an example using libxml2 based in the code that appears in http://xmlsoft.org/python.html. My example processes an enough amount of html files to see that the memory consumption rises till the process ends (I check it with the 'top' command). I don?t know if I am forgetting something in the code, as I have not been able to find any example on the web. Thanks in advance, Cesar Note: I have also tried to put the cleanup functions inside the 'for' loop. ****************************************] The Code [**************************************** #!/usr/bin/python -u import libxml2 #------------------------------------------------------------------------------ # Memory debug specific libxml2.debugMemory(1) #------------------------------------------------------------------------------ class callback: def startDocument(self): print "." def endDocument(self): pass def startElement(self, tag, attrs): pass def endElement(self, tag): pass def characters(self, data): pass def warning(self, msg): pass def error(self, msg): pass def fatalError(self, msg): pass #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ import os import sys programName = os.path.basename(sys.argv[0]) if len(sys.argv) != 2: print "Use: %s <dir html files>" % programName sys.exit(1) inputPath = sys.argv[1] if not os.path.exists (inputPath): print "Error: directory does not exist" sys.exit(1) inputFileNames = [] dirContent = os.listdir(inputPath) for fichero in dirContent: extension1=fichero.rfind(".htm") extension2=fichero.rfind(".html") dot = fichero.rfind(".") extension = max(extension1,extension2) if extension != -1 and extension == dot: inputFileNames.append (fichero) if len(inputFileNames) == 0: print "Error: no input files" sys.exit(1) handler = callback() NUM_ITERS = 5 for i in range(NUM_ITERS): for inputFileName in inputFileNames: print inputFileName inputFilePath = inputPath + inputFileName f = open(inputFilePath) data = f.read() f.close() ctxt = libxml2.htmlCreatePushParser(handler, "", 0, inputFileName) ctxt.htmlParseChunk(data, len(data), 1) ctxt = None # Memory debug specific libxml2.cleanupParser() if libxml2.debugMemory(1) == 0: print "OK" else: print "Memory leak %d bytes" % (libxml2.debugMemory(1)) libxml2.dumpMemory() # Other cleanup functions #libxml2.cleanupCharEncodingHandlers() #libxml2.cleanupEncodingAliases() #libxml2.cleanupGlobals() #libxml2.cleanupInputCallbacks() #libxml2.cleanupOutputCallbacks() #libxml2.cleanupPredefinedEntities() From tennessee at tennessee.id.au Sun Jan 7 19:45:43 2007 From: tennessee at tennessee.id.au (Tennessee Leeuwenburg) Date: Mon, 8 Jan 2007 11:45:43 +1100 Subject: Python Papers: Submission Deadline Imminent for Volume 2 Message-ID: <43c8685c0701071645ia621e36u47b4ee1fdeb6ff27@mail.gmail.com> Submission Deadline Imminent <http://pythonpapers.cgpublisher.com/diary/11> To those who have submitted content for The Python Papers, we salute you. To the rest, we will be accepting zero-hour submissions up until the time of publication. However, the closer the deadline gets, the less likely it is that submissions will be processed in time. Submissions may be kept for the next edition, however. This edition will also be aimed to complement the upcoming PyCon 2007. As we offer peer-review for academic publications, we hope to offer an opportunity to participants who might regard this as an advantage. We would still like to hear from anyone participating in any Python User's Group to be a spokesperson. We will feature a series of articles covering PUGs from around the world, and it would be fantastic to show people just how diverse, wide-ranging and interesting the Python community really is. Cheers, -T (Editor-In-Chief) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070108/2f0f0c6d/attachment.html> From millball54 at yahoo.com Sat Jan 27 08:37:07 2007 From: millball54 at yahoo.com (millball54 at yahoo.com) Date: 27 Jan 2007 05:37:07 -0800 Subject: Hi, I'm new to python Message-ID: <1169905027.776723.194140@a75g2000cwd.googlegroups.com> Hey Everyone Let me tell you all a little bit about my programming background so you can get an idea of my capability, or lack of, dealing with p.l; so far i've learned some visual basic when i was doing my a-levels.... and thats about it lol. Basically i like the sound of python and its ease of use and would like to know in depth more about it and its range of useage. Please do tell me all you know, keeping in mind i am a n00b, so do be gentle. :) Thanks Millball54 From fredrik at pythonware.com Thu Jan 4 13:59:40 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Jan 2007 19:59:40 +0100 Subject: Using External Libraries with python? In-Reply-To: <459D2577.70503@mailshack.com> References: <459D2577.70503@mailshack.com> Message-ID: <enjiqr$pkt$2@sea.gmane.org> Ognjen Bezanov wrote: > I have some external C libraries I would like to use with python. > > I have been searching on the internet and found many such > modules/bindings for libraries (e.g. Py-Lame) but have not yet > come across any information of how to actually go about creating such > bindings, so I was wondering if anybody here could point me in the right > direction? in addition to the tools that have already been mentioned, the relevant FAQ articles also provide useful information: http://effbot.org/pyfaq/extending-index.htm </F> From paddy3118 at netscape.net Fri Jan 5 03:06:43 2007 From: paddy3118 at netscape.net (Paddy) Date: 5 Jan 2007 00:06:43 -0800 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: <G3Qmh.94$9v1.124@nntpserver.swip.net> References: <G3Qmh.94$9v1.124@nntpserver.swip.net> Message-ID: <1167984402.943797.94940@q40g2000cwq.googlegroups.com> mm wrote: > Is there a Perl to Python converter? > Or in general: a XY to Python converter? > > Is see, that Python is much better then Perl anyway. > But for beginners, they whant to konw how is this done with Python etc. > > Sure, there are some docus out there in the internet. But a converter? Try this page: http://wiki.python.org/moin/PerlPhrasebook - Paddy. From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 12:43:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 18:43:34 +0100 Subject: [OT] (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <1168130960.670978.111850@s34g2000cwa.googlegroups.com> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> <1168048620.409190.85870@v33g2000cwv.googlegroups.com> <1168130960.670978.111850@s34g2000cwa.googlegroups.com> Message-ID: <45a12b07$0$300$426a74cc@news.free.fr> Martin Miller a ?crit : (snip) > > Oh, contrair. I guess you mean "au contraire" ?-) (snip) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 12:31:21 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 18:31:21 +0100 Subject: Bizarre floating-point output References: <enthjb$p0l$1@gemini.csx.cam.ac.uk> <entj5d$o4$1@south.jnrs.ja.net> <entkru$2vs$1@gemini.csx.cam.ac.uk> <50f5snF1fb5uqU2@mid.individual.net> <entpo0$d0g$1@gemini.csx.cam.ac.uk> Message-ID: <50fdf9F1fki7dU3@mid.individual.net> Nick Maclaren wrote: > The use of different precisions for the two cases is not, however, > and it is that I was and am referring to. You mistake "precision" with "display". Regards, Bj?rn -- BOFH excuse #12: dry joints on cable plug From istvan.albert at gmail.com Thu Jan 11 09:06:46 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 11 Jan 2007 06:06:46 -0800 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> <9ihph.72$fo1.64@newsfe03.lga> <1168518426.111465.290430@o58g2000hsb.googlegroups.com> Message-ID: <1168524406.571443.217190@p59g2000hsd.googlegroups.com> Sean Davis wrote: > at the same time that the data is coming in? So, I am actually looking > for a solution to this problem that doesn't require an intermediate > file and allows simultaneous reading and writing, with the caveat that > the data cannot all be read into memory simultaneously, so will need to > be buffered. IMO the problem that you need to solve is not well suited for the python DBAPI as this API is meant to support programming and interacting with the database not streaming large quantities from one database into another. I agree with another opinion in this thread. All you need is a simple way to pipe the output from Oracle into Postgresql. Just run the oracle client and start dumping to the standard output. Pipe it through sed (or a python program) to reformat the output for whatever minor fixes (you might not even need this step) then continue piping it right into psql. i. From oyekomova at hotmail.com Tue Jan 9 15:08:00 2007 From: oyekomova at hotmail.com (oyekomova) Date: 9 Jan 2007 12:08:00 -0800 Subject: Newbie - converting csv files to arrays in NumPy Message-ID: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> I would like to know how to convert a csv file with a header row into a floating point array without the header row. From t.liesner at creativ-consulting.de Mon Jan 8 11:59:35 2007 From: t.liesner at creativ-consulting.de (Thomas Liesner) Date: Mon, 08 Jan 2007 16:59:35 GMT Subject: xmlrpc an auth-diget Message-ID: <XLuoh.216$TO.6992@se2-cb104-9.zrh1.ch.colt.net> Hi all, this may have been asked before, but as a newbie with xmlrpc i can't find any suitable info on that. Sorry. I am trying to write a simple xmlrpc-client in python and the server i am trying to receive data from requires http auth digest. The info on xmlrpclib covers auth basic thrugh url econding such as "user:pass at server", but no auth digest. Is there any other library i could use for that or can i write some sort of wrapper around this using a differnt library like urllib? TIA, Tom From bj_666 at gmx.net Tue Jan 2 03:08:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 02 Jan 2007 09:08:07 +0100 Subject: how to move files based on file-ending from dirs and subdirs to specific dir? References: <mailman.2194.1167722106.32031.python-list@python.org> Message-ID: <pan.2007.01.02.08.08.03.707994@gmx.net> In <mailman.2194.1167722106.32031.python-list at python.org>, Evan Carmi wrote: > top = 'f:\\test\\mail' > > [?] > > indexdest = [] Here you bind the name `indexdest` to an empty list but replace it in the very next line with another list. So this line is unnecessary. > indexdest = ['%s\\..\\..\\%s\\%s\\%s' % (x , time.strftime('%Y%m%d%H%M%S'), > os.path.basename(os.path.normpath(x+'\\..')), os.path.basename(x)) for x in ind > ex] This line is quite complicated and I don't really grasp what it's doing. Maybe some comments, possible with examples, are needed here. And maybe then you'll see why it doesn't work as wanted!? If these are the destination paths and they should be at the same level as `top`, where is `top` here? Shouldn't that be a prefix of all destination paths? Ciao, Marc 'BlackJack' Rintsch From paul at boddie.org.uk Thu Jan 25 07:07:22 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 25 Jan 2007 04:07:22 -0800 Subject: Python does not play well with others In-Reply-To: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> References: <NXyth.51860$wc5.6792@newssvr25.news.prodigy.net> <1169722875.237123.98680@v45g2000cwv.googlegroups.com> Message-ID: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> On 25 Jan, 12:01, "Ben Sizer" <kylo... at gmail.com> wrote: > > Python is quite capable in many areas, such that the people in the > community with the expertise to extend the language and libraries, are > usually the ones who've been happily using the polished features for > years and have found they need nothing more. And the ones who need > those features probably got bored of waiting for progress long ago. You > get the responses you do from years of natural selection in the > community. I think that is why many of the SIGs are stagnant, why the > standard library has so much fluff yet still lacks in key areas such as > multimedia and web development, etc. I think this is also a good insight into why things are as they are within the core development section of the community, although one can wonder what some people actively developing the language are actually doing with it if they are satisfied with the state of some of the standard library solutions. However, there are lots of factors which motivate people and the proliferation (or otherwise) of solutions to common problems: whether one develops one's own solutions as separate projects and/or tries to push for a consensus, whether one cares about other people using such solutions, whether one aspires to contributing to the standard library. Over the years, people have tended towards building their own communities around their projects rather than attempting to engage the wider Python community, and I think a motivation behind that has been the intractability of improving parts of the standard library. For example, how would one update the cgi module? Since lots of code including various Web frameworks makes use of the cgi module, it can't just go away or have its APIs changed radically, but this doesn't exactly make for a pretty "out of the box" solution for Web programming. Someone else was complaining recently about URL handling and the required combination of urllib, cgi and urlparse (or perhaps some other combination, depending on what one's needs are). Presented with the problem of rationalising all this, the chosen solution (as adopted by the Web-SIG) is, as it is frequently, to ignore the problem and to work on other things instead. > People can say, "if you want it done, why aren't you doing it?", and is > a fair question, but it doesn't alter the fact of Python's deficiencies > in certain areas when compared with other languages. True. It also doesn't address the issue of development priorities and their role in defining the platform's own standards. We all know that the Python language has issues (or "warts" as they are popularly called), although some of the most notable ones don't seem to have been addressed as yet in the plans for Python 3000 (eg. default argument evaluation), but some of the most awkward aspects of using Python involve libraries, not some deficiency of the language. However, reforming the standard library is a topic which has arisen in all seriousness only recently in the Python 3000 process (PEP 3108), and the scope of the related activity is highly restricted - it's almost an afterthought. Where the "why aren't you doing it?" part comes in involves the observation that even if someone is motivated enough to take something like this and to move forward in their own direction [1], unless such initiatives are embraced by the core developers they will remain peripheral, non-standard extensions that will at best only become mainstream much later on. I do wonder whether the interests of language/runtime project developers eventually become completely aligned with the needs of such projects, making things like "multimedia and web development" seem irrelevant, uninteresting or tangential. This has worrying implications for the perceived relevance of Python with regard to certain kinds of solutions, despite the wealth of independently produced libraries available for the language. Paul [1] http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/RestructuredStandardLibrary From kirby.urner at gmail.com Sat Jan 27 23:39:34 2007 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: 27 Jan 2007 20:39:34 -0800 Subject: More Python screencasts (Google videos) Message-ID: <1169959174.477911.105890@k78g2000cwa.googlegroups.com> Here're three sample 3-6 min videos showing off Python to math teachers thinking about using a computer language instead of just calculators: http://controlroom.blogspot.com/2007/01/python-for-math-teachers.html Higher resolution versions are available to teachers enrolling in our program. Kirby From breroger at cisco.com Tue Jan 2 12:45:34 2007 From: breroger at cisco.com (Brent Rogers -X (breroger - Spherion at Cisco)) Date: Tue, 2 Jan 2007 09:45:34 -0800 Subject: Python Guru needed in San Jose! Message-ID: <239192DA61E5DE44A10CD25046A07EEC0359E5A1@xmb-sjc-213.amer.cisco.com> Start the New Year off with a new Python job! Cisco Systems <http://www.cisco.com/> (San Jose, CA) Posted 16-Nov-2006 Technical Leader I (759661) Description We are looking for a Software Development Engineer who will work in development of a new Cisco product. Architect and develop high performance Linux embedded drivers and software. Product implements networked services delivery including streaming and other real time protocols. Candidate must have demonstrated deep understanding of Linux OS and developed networking software on Linux. Work in a startup environment inside a corporate company. * Proven track record of major contributions to successful commercial Linux Real Time software development efforts. * Strong Linux/Unix background (System Administration background helpful) * Ability to write scripts in some administrative language (TCL, Perl, Python, a shell) * A self starter able to work with a minimal supervision * Uses acquired professional knowledge to determine method for issue resolution. * Uses expertise and creativity for innovative product recommendation and solutions Typically requires BSEE/CS or equivalent with 10+ years relevant experience in internetworking technologies and applications. * Contact: Brent Rogers, Recruiter * Email: breroger at cisco.com * Phone: 469-255-0254 Brent Rogers Recruiter Talent Acquisition and Management breroger at cisco.com Phone :469-255-0254 Mobile :469-223-2085 Cisco Systems. Inc. 2200 E. President George Bush Richardson, TX, 75082 United States www.cisco.com/jobs This e-mail may contain confidential and privileged material for the sole use of the intended recipient. Any review, use, distribution or disclosure by others is strictly prohibited. If you are not the intended recipient (or authorized to receive for the recipient), please contact the sender by reply e-mail and delete all copies of this message. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070102/79fbc52b/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: spacer.gif Type: image/gif Size: 55 bytes Desc: spacer.gif URL: <http://mail.python.org/pipermail/python-list/attachments/20070102/79fbc52b/attachment.gif> -------------- next part -------------- A non-text attachment was scrubbed... Name: footerHead.gif Type: image/gif Size: 68 bytes Desc: footerHead.gif URL: <http://mail.python.org/pipermail/python-list/attachments/20070102/79fbc52b/attachment-0001.gif> -------------- next part -------------- A non-text attachment was scrubbed... Name: footer.gif Type: image/gif Size: 347 bytes Desc: footer.gif URL: <http://mail.python.org/pipermail/python-list/attachments/20070102/79fbc52b/attachment-0002.gif> From hg at nospam.org Mon Jan 22 10:12:50 2007 From: hg at nospam.org (hg) Date: Mon, 22 Jan 2007 16:12:50 +0100 Subject: beep or sound playing under linux Message-ID: <pFath.50034$oA1.40310@newsfe19.lga> Hi, Is there a way to do that ? Regards, hg From steven.bethard at gmail.com Tue Jan 16 12:43:18 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 16 Jan 2007 10:43:18 -0700 Subject: A note on heapq module In-Reply-To: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> Message-ID: <ALadnSBgXPQykzDYnZ2dnUVZ_oernZ2d@comcast.com> bearophileHUGS at lycos.com wrote: > some time ago I have written a bug > into small program that uses the functions of the heapq module, because > I have added an item to the head of the heap using a normal list > method, breaking the heap invariant. I know I've had similar bugs in my code before. > from heapq import heapify, heappush, heappop, heapreplace > > class Heap(object): [snip implementation] +1 for adding a Heap object like this to the collections module. If you can make a little time to add some tests (you could probably steal a lot of what you need from test_heapq.py) you should definitely submit it as a patch for 2.6. STeVe From Sardaukary at gmail.com Fri Jan 5 15:39:08 2007 From: Sardaukary at gmail.com (Sardaukary at gmail.com) Date: 5 Jan 2007 12:39:08 -0800 Subject: strange for loop construct Message-ID: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> I was googling for an example of the classic word frequency program in Python as I'm just learning the language, and wanted to see how other people implemented it. I found this blog post http://digitalhistory.uwo.ca/dhh/index.php/2006/08/20/easy-pieces-in-python-word-frequencies/ (with a much more concise version than I managed) but I can't seem to find any mention in various Python documentation of the following construct wordfreq = [wordlist.count(p) for p in wordlist] I would expect for p in wordlist: wordfreq.append(wordlist.count(p)) I didn't know you could have an expression in the same line. From nono at hotmail.com Tue Jan 2 08:34:54 2007 From: nono at hotmail.com (Osiris) Date: Tue, 02 Jan 2007 14:34:54 +0100 Subject: How to get BOOST working on XP and Visual C++ 2005 Message-ID: <25nkp259o92ed0njqe7k03abohokdfepnh@4ax.com> My experiences with BOOST on Windows XP and Visual C++ 2005 I'm new to Python. I built software in more than ten other computer languages. I'm not sure if that is not a handicap, when reading documentation of a system like BOOST. However: It took me more than four full working days to get a Python/C/C++ 'hello world!' program to work. There is a lot of documentation, but somehow it did not 'click' with my previous experience. I think the doc was written by very, very capable C++ and Python programmers, who forgot how the world was before they got involved with Python. A teacher/doc writer should never forget that, I think. Mind you: the documentation is all there. Stressing the word ALL. There is a lot of documentation. Which makes it very difficult to choose the right piece. My project is, to use old and tested and stable and error-free C-code in a website built with Zope (www.zope.org) and Plone (www.plone.org). So I think, C-code can be wrapped in some C++ and then, with the help of Boost, be called from Python. Python is important when using Plone. So let me summarize what I found out. BOOST is a system to combine Python and C++. Call C++ compiled code from Python, which is interpreted. In the end, BOOST is a sort of "make" facility like found on Linux (and Windows). In Boost it is called, not 'make.exe', but 'bjam.exe'. You define a list of operations, which bjam executes for you. It runs from the command line (I grew up, IT-wise, in the DOS-era. Hurray), it has no GUI-like Windows front-end. So the first step is to get bjam.exe from the net. There are two ways to get it: 1. download a ready-to-run bjam.exe from http://downloads.sourceforge.net/boost/boost-jam-3.1.13-1-ntx86.zip?modtime=1149717367&big_mirror=0. In the zip you will find the bjam.exe, which you put it in a place where the system can always find it, like in c:\, or somewhere else in the system's PATH. 2. download the sources for bjam.exe and build it yourself: http://downloads.sourceforge.net/boost/boost-jam-3.1.13.zip?modtime=1149717465&big_mirror=0 . I recommend not to do this, if you don't have to. And on Windows XP, you don't have to. You could spend a lot of time to figure out how to set up things before even building bjam.exe. The second step is to get Boost libraries. These are for combining with your C/C++ source, so Python can access the C/C++ code. You download this stuff from Sourceforge: http://downloads.sourceforge.net/boost/boost_1_33_1.zip?modtime=1133816391&big_mirror=0 It is a zip file that you unzip to a convenient location. I unzipped to D:\ so I got a folder named d:\boost_1_31_1 with all the stuff in it. I renamed this folder to d:\boost, to get rid of all the messy version numbers. To build the boost libraries from these sources, you need bjam, and bjam makes use of your C/C++ compiler. In my case that was Microsoft Visual C++ 2005, which has version number 8.0. Now you have to make bjam and Visual C++ acquainted with the location of supporting software. I made a BAT file to do this. This is what is in that .BAT file, named SET.BAT and which I put in D:\boost: d: cd \boost call e:\msvc\vc\vcvarsall.bat set VC80_ROOT=e:\msvc\vc set TOOLS=vc-8_0 set PYTHON_ROOT=c:\python24 set PYTHON_VERSION=2.4 I explain: e:\msvc is where I installed my Visual C++ system. The Microsoft default location would be something like C:\Microsoft Visual C 2005\ etc, but I preferred D:\msvc. Change the SET.BAT file as needed . My IDLE (http://www.python.org/idle/) Python 2.4 is in C:\python24 The value 'vc-8_0' denotes the boost identification of my MS Visual C++ system. If you use an other C++ system, it must be something else (see http://www.boost.org/more/getting_started.html) Now start a DOS box: Click the Start button in the lower left corner, click on "run" and type "cmd". There you switch to D:\ and change directory to \BOOST. Execute the SET.BAT. Then just type "bjam" (the system will find the program bjam itself, because it is in the PATH) Now get a lot of coffee, because the build will take a LONG time, maybe 15 minutes or more. You will see a lot of cpp-compiling and linking going on and some warnings about 'deprecation', which are irrelevant. When finished, keep the DOS box open. You will find BOOST stuff in C:\boost, the default location for the compiling results. Now try out an example. In the DOS box, go to D:\boost\libs\python\example\tutorial, where you find a 'hello' example and a Jamfile. Jamfile's are what a makefile is for make.: a script for bjam to build all the 'hello' stuff needed for python. Type 'bjam' again, and take a smaller amount of coffee. The system will build the 'hello' stuff for you. Do not be alarmed about bjam finding 1200+ 'targets' and rebuilding 40 of them, when only needing to compile hello.cpp . this is normal behaviour. When bjam has finished, you will find 'hello' stuff in the unbelievably deep folder D:\boost\libs\python\example\tutorial\bin\tutorial\hello.pyd\vc-8_0\debug\threading-multi Really. I don't know why this must be so deep. And some Boost stuff in the even more deep folder D:\boost\libs\python\example\tutorial\bin\boost\libs\python\build\boost_python.dll\vc-8_0\debug\threading-multi Find the hello.pyd and boost_python.dll and move them to the folder where yout python.exe is, in my case c:\python24. Now you go to file:///D:/boost/libs/python/doc/tutorial/doc/html/python/hello.html which is part of the Boost download. and read the page. That should get you on your way. Of course, now it might be beneficial to you to start reading the other documentation on http://www.boost.org/more/getting_started.html From Eric_Dexter at msn.com Fri Jan 19 06:51:08 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 19 Jan 2007 03:51:08 -0800 Subject: when format strings attack Message-ID: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN I saw a warning from homeland security about this. I only comment on the because I am trying to use os.system('command1 arg') and it doesn't work but I do see examples with % that is borrowed from the c language. Seems like if I can write a batch file that does something the same behavior should happen in the os module.. From dickinsm at gmail.com Tue Jan 16 10:52:56 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 16 Jan 2007 07:52:56 -0800 Subject: Conflicting needs for __init__ method In-Reply-To: <1168961105.446604.259840@l53g2000cwa.googlegroups.com> References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <mailman.2741.1168898073.32031.python-list@python.org> <1168961105.446604.259840@l53g2000cwa.googlegroups.com> Message-ID: <1168962776.221753.263670@v45g2000cwv.googlegroups.com> On Jan 16, 10:25 am, "Mark Dickinson" <dicki... at gmail.com> wrote: > that is, I was working from the following two assumptions: > > (1) *Every* time a Rational is created, __init__ must eventually be > called, and > (2) The user of the class expects to call Rational() to create > rationals. (with apologies for replying to myself) I'm still not being careful. The assumptions should be these: (1) Any creation of a Rational instance must eventually go through Rational(). (2) A call to Rational() eventually results in a call to __init__. (3) The user of the class expects to call Rational() to create rationals. There you are: three flawed assumptions for the price of two! (1) fails because __new__ provides an alternative, (2) could easily become untrue by changing the metaclass, and (3)---well, who knows what the user expects? Right. Now that I've thoroughly analyzed my own stupidity, things are much clearer. Thank you to all who replied. Mark From sjmachin at lexicon.net Mon Jan 1 03:14:40 2007 From: sjmachin at lexicon.net (John Machin) Date: 1 Jan 2007 00:14:40 -0800 Subject: OO question References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> Message-ID: <1167639280.181587.242490@s34g2000cwa.googlegroups.com> fejkadress at hushmail.com wrote: > I want to make an addressbook and I'm new to OO programming, so I > wonder if this sounds reasonable. > > I think of making a class Address which contains all data about one > person, that class can have UserDict as baseclass so I can access data > like object['name'], etc.. Stop right there. Class Address contains all data about one *person*? Please consider renaming that class Person, and having a separate class Address. Interruption for a reality check: A person may be related to zero, one or many addresses. An address may be related to zero, one or many persons. The relationship may take many forms e.g. "lives at", "once lived at", "has been noticed loitering outside", ... OK, now you can resume your normal programming ;-) BTW, why object['name'] and not object.name? Cheers, John From jzgoda at o2.usun.pl Mon Jan 22 14:39:28 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 22 Jan 2007 20:39:28 +0100 Subject: Python Windows Editors In-Reply-To: <p5Qsh.51413$wc5.6534@newssvr25.news.prodigy.net> References: <p5Qsh.51413$wc5.6534@newssvr25.news.prodigy.net> Message-ID: <ep33ul$6cr$1@atlantis.news.tpi.pl> W. Watson napisa?(a): > I downloaded python-2.5.msi and installed it. I believe its editor is > IDE. I understand there's a Win editor called pythonwin. I believe it's > in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this > exe file has just the editor or all of Python. Comments? If not how do I > get the PythonWin editor by itself? No, there's no "single official Python editor or IDE". You can edit Python code in any editor you want. When I was on Windows, I used to use jEdit (http://www.jedit.org/) or Vim (http://www.vim.org/), but others will give you other advices. Any text editor is only as good as the programmer who uses it. ;) -- Jarek Zgoda http://jpa.berlios.de/ From martin at v.loewis.de Mon Jan 22 16:48:46 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 22 Jan 2007 22:48:46 +0100 Subject: Building extensions with vc8 In-Reply-To: <Xns98C08781BD9E5howardeegsoftwarecom@207.115.17.102> References: <Xns98C08781BD9E5howardeegsoftwarecom@207.115.17.102> Message-ID: <45B5313E.8050308@v.loewis.de> Howard Lightstone schrieb: > Has there been any progress on being able to build extensions with MSVC8 > (aka Visual Studio 2005)? No. No progress will happen throughout the release of Python 2.5. To get the facts straight: it *might* be possible to build an extension with msvc8 (thus linking with msvcr8.dll); this should work as long as the extension doesn't use any API that is forbidden for the mixed-CRT case. Only a source inspection of the extension module can tell whether there is any risky code. > Since the "free" compiler from Microsoft is now VC8, I *assume* this will > be the new method..... Your assumption is wrong; this isn't officially supported. > 2.5 itself rebuilds using PCbuild8, as do tkinter (but using Tcl 8.4.14 and > Tk 8.4.14) however none of the distutils-generated extensions will build. If you built Python 2.5 yourself with VS 2005, you should be able to build extension modules as well with distutils, by setting MSSdk and DISTUTILS_USE_SDK appropriately. Regards, Martin From __peter__ at web.de Mon Jan 8 07:55:40 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Jan 2007 13:55:40 +0100 Subject: how to find the longst element list of lists References: <Vwdoh.223$L06.180@nntpserver.swip.net> <m2mz4ul1tk.fsf@unique.fqdn> <pan.2007.01.08.10.29.29.887201@REMOVE.THIS.cybersource.com.au> Message-ID: <entf0l$fmo$00$1@news.t-online.com> Steven D'Aprano wrote: > On Sun, 07 Jan 2007 20:55:19 -0500, Dan Sommers wrote: > >> On Sun, 07 Jan 2007 22:23:22 +0100, >> "Michael M." <michael at mustun.ch> wrote: >> >>> How to find the longst element list of lists? >>> I think, there should be an easier way then this: >> >>> s1 = ["q", "e", "d"] >>> s2 = ["a", "b"] >>> s3 = ["a", "b", "c", "d"] >> >> [ snip ] >> >> One more thing to think about: if your list of lists grows (i.e., if >> you end up with thousands of lists instead of just three), then sorting >> may not be the way to go. Assuming that list_of_lists is your list of >> lists, then something like this: >> >> longest_list, longest_length = list_of_lists[ 0 ], len( longest_list >> ) for a_list in list_of_lists[ 1 : ]: >> a_length = len( a_list ) >> if a_length > longest_length: >> longest_list, longest_length = a_list, a_length >> >> will run faster than sorting the list just to pick off one element (O(n) >> vs. O(n log n) for all of you Big-Oh notation fans out there; you know >> who you are!). > > But your O(n) code is running in relatively slow Python, while the sort > method, while O(n log n), is some of the fastest, most highly optimized C > code out there. Unless your list is truly gigantic, chances are the sort > version will win. > > Here's my timing code: > > > import timeit > > def getlongest1(list_of_lists): > longest_list = list_of_lists[ 0 ] > longest_length = len( longest_list ) > for a_list in list_of_lists[ 1 : ]: > a_length = len( a_list ) > if a_length > longest_length: > longest_list, longest_length = a_list, a_length > return longest_list > > def getlongest2(list_of_lists): > list_of_lists.sort(key=len) > return list_of_lists[0] > > def make_list_of_lists(length): > return [[None]*i for i in xrange(length)] > > t1 = timeit.Timer("getlongest1(L)", "from __main__ import getlongest1, L") > t2 = timeit.Timer("getlongest2(L)", "from __main__ import getlongest2, L") > > > > Note that my test list_of_lists grows very big quite fast, like O(n**2). > Assuming Python pointers are eight bytes, a mere length=10000 will > require over 760MB just for the pointers. More realistic data may allow > more extensive testing. > > And here are my timing results: > >>>> L = make_list_of_lists(1) >>>> print t1.timeit(1000), t2.timeit(1000) > 0.00209903717041 0.00367403030396 > >>>> L = make_list_of_lists(10) >>>> print t1.timeit(1000), t2.timeit(1000) > 0.00871086120605 0.00775289535522 > >>>> L = make_list_of_lists(100) >>>> print t1.timeit(1000), t2.timeit(1000) > 0.121382951736 0.0518100261688 > >>>> L = make_list_of_lists(1000) >>>> print t1.timeit(1000), t2.timeit(1000) > 0.809508085251 0.508343935013 > >>>> L = make_list_of_lists(10000) >>>> print t1.timeit(100), t2.timeit(100) > 0.906499147415 0.732254981995 > >>>> L = make_list_of_lists(20000) >>>> print t1.timeit(100), t2.timeit(100) > 1.83560800552 1.58732700348 > > For a list of 1 item, sorting is 1.8 times SLOWER; > For a list of 10 items, sorting is 1.1 times FASTER; > For 100 items, sorting is 2.3 times faster; > For 1000 items, sorting is 1.6 times faster; > For 10,000 items, sorting is 1.2 times faster; > For 20,000 items, sorting is 1.1 times faster. > > > The precise results depend on the version of Python you're running, the > amount of memory you have, other processes running, and the details of > what's in the list you are trying to sort. But as my test shows, sort has > some overhead that makes it a trivial amount slower for sufficiently small > lists, but for everything else you're highly unlikely to beat it. Try again with tN.timeit(1) and a second list that is random.shuffle()d and copied to L before each measurement. list.sort() treats already sorted lists specially. Peter From t.liesner at creativ-consulting.de Mon Jan 8 12:08:42 2007 From: t.liesner at creativ-consulting.de (Thomas Liesner) Date: Mon, 08 Jan 2007 17:08:42 GMT Subject: xmlrpc and auth-digest Message-ID: <uUuoh.217$TO.6980@se2-cb104-9.zrh1.ch.colt.net> Hi all, this may have been asked before, but as a newbie with xmlrpc i can't find any suitable info on that. Sorry. I am trying to write a simple xmlrpc-client in python and the server i am trying to receive data from requires http auth digest. The info on xmlrpclib covers auth basic thrugh url econding such as "user:pass at server", but no auth digest. Is there any other library i could use for that or can i write some sort of wrapper around this using a differnt library like urllib? TIA, Tom From cfbolz at gmx.de Mon Jan 22 06:05:07 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Mon, 22 Jan 2007 12:05:07 +0100 Subject: Py 2.5 on Language Shootout In-Reply-To: <624934630701211513t3a3e28a5ua7387c9ee2f5790e@mail.gmail.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> <45B23400.2010906@gmx.de> <mailman.2944.1169309208.32031.python-list@python.org> <1169321686.025356.120340@s34g2000cwa.googlegroups.com> <mailman.2951.1169329048.32031.python-list@python.org> <1169331552.918850.282920@a75g2000cwd.googlegroups.com> <624934630701211513t3a3e28a5ua7387c9ee2f5790e@mail.gmail.com> Message-ID: <45B49A63.9000601@gmx.de> Ramon Diaz-Uriarte wrote: >> In England the corresponding expression is "Counting Angels on a >> Pinhead" >> http://dannyayers.com/2001/misc/angels.htm >> > > Thanks, that is neat. I find the discussion on the sex of the angels, > well, sexier. But we are probably a few hundred years late to start a > catholic-protestant religious war here :-). > NOBODY expects the Spanish Inquisition! Our chief weapon is surprise...surprise and fear...fear and surprise. From maxerickson at gmail.com Tue Jan 16 23:37:11 2007 From: maxerickson at gmail.com (Max Erickson) Date: Wed, 17 Jan 2007 04:37:11 +0000 (UTC) Subject: urllib2 and HTTPBasicAuthHandler References: <45acf775$0$5070$ba4acef3@news.orange.fr> <mailman.2789.1168970662.32031.python-list@python.org> <45ad6309$1$27408$ba4acef3@news.orange.fr> Message-ID: <Xns98BAF044A7527maxericksongmailcom@80.91.229.5> "m.banaouas" <banaouas.medialog at wanadoo.fr> wrote: ... > passman.add_password(None, auth_url, data['user'] , ... The only thing I can come up with is that auth_url can't begin with a protocol, like http:// or whatever. max From cvanarsdall at mvista.com Wed Jan 31 20:19:07 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 31 Jan 2007 17:19:07 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <20070201011029.25807.1696981903.divmod.quotient.5293@ohm> References: <20070201011029.25807.1696981903.divmod.quotient.5293@ohm> Message-ID: <45C1400B.2000204@mvista.com> Jean-Paul Calderone wrote: > On Wed, 31 Jan 2007 15:13:59 -0800, "Carl J. Van Arsdall" <cvanarsdall at mvista.com> wrote: > >> Jean-Paul Calderone wrote: >> >>> [snip] >>> >>>> >>> You're right. Learning new things is bad. My mistake. >>> >>> Jean-Paul >>> >>> >> That isn't what I said at all. You have to look at it from a >> cost/benefit relationship. Its a waste of time/money to learn something >> complex to do something simple. For the simple things, use a simple >> solution. KISS. When he has an application that would require >> something more complex, it would be at that point he should consider >> using it for a project. Unless the OP has a desire to learn this >> technology, then more power to him. I, however, do not believe that >> would be the best approach for a simple problem. >> >> Knowing the appropriate tool for the job is a trait of an good engineer. >> >> > > You are assuming that he already knows how to use threads, and so there > is no investment required for a threaded solution. In my experience, it's > much safer to assume the opposite. _Even_ (often _especially_ when a > threaded solution is explicitly requested. > I have a bit more confidence in python threads, but that takes us back to the age old debate on this list. So we agree to disagree. -c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From jstroud at mbi.ucla.edu Mon Jan 22 01:01:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 21 Jan 2007 22:01:01 -0800 Subject: Is any python like linux shell? In-Reply-To: <1169437900.726137.237650@51g2000cwl.googlegroups.com> References: <1169398326.510530.180860@51g2000cwl.googlegroups.com> <1169400157.075307.31340@l53g2000cwa.googlegroups.com> <1169437900.726137.237650@51g2000cwl.googlegroups.com> Message-ID: <ep1jut$sla$2@daisy.noc.ucla.edu> Paddy wrote: > George Sakkis wrote: > > >>Frank Potter wrote: >> >> >>>I learned some python in windows. >>>And now I've turned to linux. >>>I read a book and it teaches how to write shell script with bash, >>>but I don't feel like the grammar of bash. >>>Since I know about python, >>>I want to get a linux shell which use python grammar. >>>I searched by google and I found pysh, which is not maintained any >>>more. >>>There's another script named pyshell, which is not likely what I'm >>>searching for. >>>So, will somebody please tell me if there are any python like shells >>>for linux? >> >>IPython is actually more than a simple shell. Give it a try: >>http://ipython.scipy.org/. >> >>George > > > Frank, > IPython is great, but it is not a replacement for a shell like bash. If > you have a Linux system then you still need to know the rudiments of > bash Or better yet, csh. ;) James From sschwarzer at sschwarzer.net Fri Jan 26 18:03:28 2007 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 27 Jan 2007 00:03:28 +0100 Subject: [ANN] ftputil 2.2.1 Message-ID: <mailman.3231.1169916877.32031.python-announce-list@python.org> ftputil 2.2.1 is now available from http://ftputil.sschwarzer.net/download . Changes since version 2.2 ------------------------- This bugfix release checks and ignores status code 451 when FTPFiles are closed (thanks go to Alexander Holyapin). Upgrading is recommended. What is ftputil? ---------------- ftputil is a high-level FTP client library for the Python programming language. ftputil implements a virtual file system for accessing FTP servers, that is, it can generate file-like objects for remote files. The library supports many functions similar to those in the os, os.path and shutil modules. ftputil has convenience functions for conditional uploads and downloads, and handles FTP clients and servers in different timezones. Read the documentation at http://ftputil.sschwarzer.net/trac/wiki/Documentation . License ------- ftputil is Open Source software, released under the revised BSD license (see http://www.opensource.org/licenses/bsd-license.php ). Stefan -- Dr.-Ing. Stefan Schwarzer SSchwarzer.com - Softwareentwicklung f?r Technik und Wissenschaft http://sschwarzer.com http://ftputil.sschwarzer.net From jhefferon at smcvt.edu Wed Jan 31 11:01:52 2007 From: jhefferon at smcvt.edu (Jim) Date: 31 Jan 2007 08:01:52 -0800 Subject: error messages containing unicode In-Reply-To: <1170248238.032665.207180@m58g2000cwm.googlegroups.com> References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> <pan.2007.01.30.02.48.10.853852@REMOVEME.cybersource.com.au> <1170160464.576122.62230@h3g2000cwc.googlegroups.com> <pan.2007.01.31.06.39.55.881990@REMOVEME.cybersource.com.au> <1170248238.032665.207180@m58g2000cwm.googlegroups.com> Message-ID: <1170259312.899040.55250@p10g2000cwp.googlegroups.com> Oops, there is a typo in what I wrote above. Sorry. On Jan 31, 7:57 am, "Jim" <jheffe... at smcvt.edu> wrote: > Oh, I agree. If I have a string mesg that is unicode-not-ascii and I > say > try: > raise Exception mesg > except Exception, err: > print "Trouble"+mesg > then I have problems. should say: try: raise Exception mesg except Exception, err: print "Trouble"+str(err) Jim From horpner at yahoo.com Tue Jan 9 08:16:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 9 Jan 2007 14:16:18 +0100 Subject: Colons, indentation and reformatting. References: <1168323145.393149.299540@v33g2000cwv.googlegroups.com> <45a36074$0$15146$4d3efbfe@news.sover.net> Message-ID: <slrneq75ge.1nc.horpner@FIAD06.norwich.edu> On 2007-01-09, Leif K-Brooks <eurleif at ecritters.biz> wrote: > Paddy wrote: >> Thinking about it a little, it seems that a colon followed by >> non-indented code that has just been pasted in could also be >> used by a Python-aware editor as a flag to re-indent the >> pasted code. > > How would it reindent this code? > > if foo: > print "Foo!" > if bar: > print "Bar!" > > Like this? > > if foo: > print "Foo!" > if bar: > print "Bar!" > > Or like this? > > if foo: > print "Foo!" > if bar: > print "Bar!" That's the key issue. The colon gives the editor an easy clue where a block starts, but the there's no simply way to determine where the block is supposed to end. -- Neil Cerutti Remember in prayer the many who are sick of our church and community. --Church Bulletin Blooper From gagsl-py at yahoo.com.ar Thu Jan 25 19:54:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 21:54:49 -0300 Subject: Module for SVG? In-Reply-To: <1169754412.101443.280390@h3g2000cwc.googlegroups.com> References: <mailman.3164.1169751502.32031.python-list@python.org> <1169754412.101443.280390@h3g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20070125215150.047bfd20@yahoo.com.ar> At Thursday 25/1/2007 16:46, Boris.Boutillier at gmail.com wrote: >Depending on the size of your project, the xist library from living >logic is supporting svg xml: >http://www.livinglogic.de/Python/xist/ >http://www.livinglogic.de/Python/xist/ns/svg/ > >We've used it successfully, but later on came back to simply use the >standard dom creation tools in python to reduce dependencies. I ended using a similar approach. You only need a few functions to generate those long string attribute values, the remaining is standard XML. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steven.bethard at gmail.com Tue Jan 9 13:39:59 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 09 Jan 2007 11:39:59 -0700 Subject: Question about using "with" In-Reply-To: <mailman.2487.1168367035.32031.python-list@python.org> References: <mailman.2487.1168367035.32031.python-list@python.org> Message-ID: <nqednbAMHvnqfD7YnZ2dnUVZ_szinZ2d@comcast.com> Steven W. Orr wrote: >> From the tutorial, they said that the following construct will > automatically close a previously open file descriptor: > > ------------------- > #! /usr/bin/python > import sys > > for nn in range ( 1, len(sys.argv ) ): > print "arg ", nn, "value = ", sys.argv[nn] > with open(sys.argv[nn]) as f: > for line in f: > print line, > ------------------ > > but when I run it (with args) I get: > > 591 > ./cat.py cat.py > File "./cat.py", line 6 > with open(sys.argv[nn]) as f: > ^ > SyntaxError: invalid syntax > 592 > > > This example came from http://docs.python.org/tut/node10.html down in > section 8.7 > > Am I missing something? You need to enable the with statement using a __future__ import:: >>> with open('temp.txt', 'w') as f: <stdin>:1: Warning: 'with' will become a reserved keyword in Python 2.6 File "<stdin>", line 1 with open('temp.txt', 'w') as f: ^ SyntaxError: invalid syntax >>> from __future__ import with_statement >>> with open('temp.txt', 'w') as f: ... f.write('hello') ... STeVe From dejan.wirusrodiger at ck.t-com.hr Tue Jan 16 03:08:32 2007 From: dejan.wirusrodiger at ck.t-com.hr (Dejan Rodiger) Date: Tue, 16 Jan 2007 09:08:32 +0100 Subject: Python Threads and C Semaphores In-Reply-To: <eohuov$js1$1@nobel.pacific.net.sg> References: <eohuov$js1$1@nobel.pacific.net.sg> Message-ID: <eoi163$hnc$1@ss408.t-com.hr> Jeremy said the following on 16.1.2007 8:27: > Hello, > > I have a fat C++ extension to a Python 2.3.4 program. In all, I count > five threads. Of these, two are started in Python using > thread.start_new_thread(), and both of these wait on semaphores in the C++ > extension using sem_wait(). There also are two other Python threads and one > thread running wholly in > the extension. > > I notice that when one of the Python threads calls the extension and waits > on a semaphore, all but the C++ thread halt even when not waiting on any > semaphore. How do we get this working right? Check the Global Interpreter Lock -- Dejan Rodiger - PGP ID 0xAC8722DC Delete wirus from e-mail address From bignose+hates-spam at benfinney.id.au Wed Jan 31 04:15:44 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 31 Jan 2007 20:15:44 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <mailman.3297.1170139632.32031.python-list@python.org> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> <pan.2007.01.31.07.24.21.793319@REMOVEME.cybersource.com.au> Message-ID: <87odofv9of.fsf@benfinney.id.au> "Steven D'Aprano" <steve at REMOVEME.cybersource.com.au> writes: > > def _accumulate_properties(self, properties): > > self.properties = [] > > Probably better to put that in the __init__ method, otherwise if > somebody runs instance._accumulate_properties(...) again, it will > have the side-effect of throwing away whatever was already in > instance.properties. That's the point of naming it with a leading underscore. You've already explained that this is convention for "Private, don't use". > Some people might argue that if someone runs a private method like > _accumulate_properties, they deserve whatever bad things happen to > them. But I say, well, sure, but why *design* your method to break > things when called twice? Exactly the same could be said for calling the __init__ method twice. > Who knows, maybe you'll decide you want to call it twice yourself. Right. In which case, it's good that it's already in a separate, clearly-named, single-purpose method. Make the code easy to understand, not idiot-proof. -- \ "One time a cop pulled me over for running a stop sign. He | `\ said, 'Didn't you see the stop sign?' I said, 'Yeah, but I | _o__) don't believe everything I read.'" -- Steven Wright | Ben Finney From steve at REMOVE.THIS.cybersource.com.au Sat Jan 13 01:52:03 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 13 Jan 2007 17:52:03 +1100 Subject: Boilerplate in rich comparison methods Message-ID: <pan.2007.01.13.06.52.02.531589@REMOVE.THIS.cybersource.com.au> I'm writing a class that implements rich comparisons, and I find myself writing a lot of very similar code. If the calculation is short and simple, I do something like this: class Parrot: def __eq__(self, other): return self.plumage() == other.plumage() def __ne__(self, other): return self.plumage() != other.plumage() def __lt__(self, other): return self.plumage() < other.plumage() def __gt__(self, other): return self.plumage() > other.plumage() def __le__(self, other): return self.plumage() <= other.plumage() def __ge__(self, other): return self.plumage() >= other.plumage() If the comparison requires a lot of work, I'll do something like this: class Aardvark: def __le__(self, other): return lots_of_work(self, other) def __gt__(self, other): return not self <= other # etc. But I can't help feeling that there is a better way. What do others do? -- Steven. From tim at tdw.net Wed Jan 24 05:56:28 2007 From: tim at tdw.net (Tim Williams) Date: Wed, 24 Jan 2007 10:56:28 +0000 Subject: smtplib starttls gmail example - comments? In-Reply-To: <W63698683.410.134.1@mxextra> References: <W63698683.410.134.1@mxextra> Message-ID: <9afea2ac0701240256kae247b3s666be6529362c84e@mail.gmail.com> On 24/01/07, py <py at th.on> wrote: > I would love for anybody to comment on this code with regard to redundancy/efficiency/wordiness or whatever else. > for instance, do i understand correctly that i cant have a try: else: without an intervening except:? > -dave > > stdout.write("calling smtp server...") > try: > server = SMTP(msgsmtp) > except: > stdout.write("FAIL.") #using .write to avoid the implied \n with print > else: > server.set_debuglevel(msgdebug) > stdout.write("starting tls...") > server.ehlo(msgfrom) > try: server.starttls() > except: stdout.write("FAIL.") > else: > server.ehlo(msgfrom) #neessary duplication (?) > stdout.write("logging in...") > try: server.login(msgfrom, msgpass) > except: stdout.write("FAIL.") > else: > stdout.write("sending...") > try: server.sendmail(msgfrom, msgto, msgtxt + "\n.\n") > except: stdout.write("FAIL.") > else: > try: > server.quit() > except sslerror: # a known and largely ignored issue with early EOF in ssl protocol > stdout.write("success.") > else: > stdout.write("success.") > -- *** Not tested but should have the same functionality and error handling as your script *** this_host = 'myhostname.mydom1.com' print "calling smtp server...", # the trailing comma removes '\n' try: server = smtplib.SMTP(msgsmtp,local_hostname=this_host) server.set_debuglevel(msgdebug) print "starting tls...", server.starttls() server.ehlo(this_host) # RFC requirement for 2nd EHLO after requesting TLS print "logging in...", server.login(msgfrom, msgpass) print "sending...", failed = server.sendmail(msgfrom, msgto, msgtxt + "\n.\n") try: server.quit() except: pass print "success." except: print "FAIL.", if failed: print "failed:", failed # some recipients, but not all of them, failed From paddy3118 at netscape.net Mon Jan 1 00:57:47 2007 From: paddy3118 at netscape.net (Paddy) Date: 31 Dec 2006 21:57:47 -0800 Subject: OO question In-Reply-To: <1167623232.105052.203550@42g2000cwt.googlegroups.com> References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> Message-ID: <1167631067.933776.146240@n51g2000cwc.googlegroups.com> fejkadress at hushmail.com wrote: > I want to make an addressbook and I'm new to OO programming, so I > wonder if this sounds reasonable. > > I think of making a class Address which contains all data about one > person, that class can have UserDict as baseclass so I can access data In Python 2.4 or 2.5 you can subclass dict. > like object['name'], etc.. > Then maybe I can have a class AddressBook which has a list that > contains all those Address objects. > Does that sound reasonable? Yep. class AdressBook(list): def save(self, filename): import pickle ... > And then the real reason that I posted here is: > If I want to save all addresses to disk, I can have a method, say, > save() of AddressBook. But then what? What is a good object oriented > approach? Should each Address object take care of saving itself to the > file, with a method like writetofile(filename), or should the class > AddressBook take care of the saving and ask each object for its data? If you use the pickle module on the Addressbook then it will automatically save each Address instance. - Paddy. From deets at nospam.web.de Mon Jan 15 04:05:39 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Jan 2007 10:05:39 +0100 Subject: python and MOV or MPEG References: <eoffha$epe2$1@zam602.zam.kfa-juelich.de> Message-ID: <510uf3F1i9oo6U1@mid.uni-berlin.de> siggi wrote: > Hi all, > > does Python support MPEG or MOV videoclips? I couldn't find anything about > it online. Weak in googling today? Must have been a rough weekend. There are several options, including pymedia and pygame. Diez From Shellby at mindspring.com Sun Jan 21 18:19:06 2007 From: Shellby at mindspring.com (Sarah) Date: Sun, 21 Jan 2007 23:19:06 GMT Subject: ~~~~~~~~ Amazing Real Booby Downloads ~~~~~~~` Message-ID: <KxSsh.754630$5R2.400847@pd7urf3no> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070121/a0694017/attachment.html> From citronelu at yahoo.com Mon Jan 8 18:15:54 2007 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 8 Jan 2007 15:15:54 -0800 Subject: Execute binary code In-Reply-To: <50fujcF1g1nplU2@mid.individual.net> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <EOSdneXxmrS6OT_YnZ2dnUVZ_q7inZ2d@comcast.com> <50fujcF1g1nplU2@mid.individual.net> Message-ID: <1168298153.982394.181090@q40g2000cwq.googlegroups.com> Bjoern Schliessmann wrote: > But you could technically achieve this with standard python too > (just write python source and spawn a python process executing it). The code I try to execute is Windows specific and it is binary, not python. Furthermore, it is stored in a variable within the parent python script, not stored on harddisk as a file. From Roberto.Bonvallet at cern.ch Thu Jan 18 05:15:57 2007 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Thu, 18 Jan 2007 10:15:57 +0000 (UTC) Subject: One more regular expressions question References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> Message-ID: <eonhct$77p$1@cernne03.cern.ch> Victor Polukcht wrote: > My actual problem is i can't get how to include space, comma, slash. Post here what you have written already, so we can tell you what the problem is. -- Roberto Bonvallet From piet at cs.uu.nl Thu Jan 4 09:00:49 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 04 Jan 2007 15:00:49 +0100 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <qt5jp2pq4a6a9b4gpha1rvou0cl7ji1gem@4ax.com> <mailman.2191.1167695021.32031.python-list@python.org> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <endrll$gjk$1@news1.carnet.hr> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> <ene0j1$6nk$03$1@news.t-online.com> <m2fyatcddg.fsf@ordesa.cs.uu.nl> <eng5qv$6l4$00$1@news.t-online.com> Message-ID: <m2hcv651ta.fsf@ordesa.cs.uu.nl> >>>>> Sebastian 'lunar' Wiesner <basti.wiesner at gmx.net> (SW) wrote: >SW> I don't see a problem with SUID on scripts. If you restrict write access >SW> to the owner, modification is hardly possible. >SW> However, if you allow world-wide write access to your binaries and >SW> scripts, both can easily be modified... The scenario is as follows: Suppose the script starts with the line: #!/usr/bin/python (using #!/usr/bin/env python would be disastrous because the user could supply his own `python interpreter' in his PATH.) Now a malicious user can make a link to this file in his own directory, e.g. to /Users/eve/myscript1. Because permissions are part of the file (inode), not of the file name, this one is also suid. Now she execs /Users/eve/myscript1. The kernel, when honoring suid scripts, would startup python with effective uid root with the command line: /usr/bin/env /Users/eve/myscript1 Now in another process eve changes the link /Users/eve/myscript1 to point to another script /Users/eve/myscript2. If she manages to change the link between the startup of the python executable and the interpreter opening the file /Users/eve/myscript1, she has her own script running as root. Of course the timing is a bit critical but if you try often enough some time it will succeed. The problem is the time window between starting the executable and opening the script. There is no guarantee that the file will be the same. It can only be made safe if interpreters can be passed inodes or opened files by the kernel, but that is not how most interpreters work. At least not python. -- Piet van Oostrum <piet at cs.uu.nl> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From deets at nospam.web.de Mon Jan 29 10:45:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 Jan 2007 16:45:43 +0100 Subject: HTMLParser's start_tag method never called ? References: <1170084691.837503.10520@j27g2000cwj.googlegroups.com> Message-ID: <526j57F1mn0bdU1@mid.uni-berlin.de> ychaouche wrote: > Hi, python experts. > > <console trace> > chaouche at CAY:~/TEST$ python nettoyageHTML.py > chaouche at CAY:~/TEST$ > </console trace> > > This is the nettoyageHTML.py python script > > <code> > from HTMLParser import HTMLParser > > class ParseurHTML(HTMLParser): > def __init__(self): > HTMLParser.__init__(self) > > def start_body(self,attrs): > print "this is my body" > > p = ParseurHTML() > p.feed(open("/home/chaouche/TEST/AJAX/testXMLRPC.html","r").read()) > </code> > > this is the testXMLRPC.html html file : > > <html> > <head> > <script type="text/javascript" language="javascript" > src="ClientXMLRPC.js"> > </script> > > <script type="text/javascript" language="javascript" > > > if (typeof netscape != 'undefined' && typeof netscape.security != > 'undefined') { > > netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRea > d'); > } > > var chiffre = 0; > handler = function (self){ > if (self.xmlhttp.readyState == 4) { > reponse = self.xmlhttp.responseText; > //dump(reponse); permet d'acceder au dom si ce qu'on a recu est une > forme de xml. > document.getElementById("txt").innerHTML=reponse; > } > } > > function recupDonnees(){ > chiffre+=1; > client = new ClientXMLRPC(); > client.setUrl("http://10.75.49.100:8081/bonjour/sayHi? > chiffre="+chiffre); > client.executer(); > client.handlerEvenement = handler; > } > recupDonnees(); > > </script> > </head> > <body> > > <span id="txt">NON</span> > </body> > </html> > > > The script should output "this is my body", but nothing is printed. > Anyone ? You need a p.close() after the feed I guess. Diez From __peter__ at web.de Tue Jan 23 18:07:35 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Jan 2007 00:07:35 +0100 Subject: Overloading assignment operator References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> <ep5kt4$sun$01$1@news.t-online.com> <pan.2007.01.23.22.17.26.616891@REMOVE.THIS.cybersource.com.au> Message-ID: <ep64f2$6i4$00$1@news.t-online.com> Steven D'Aprano wrote: > On Tue, 23 Jan 2007 19:42:01 +0100, Peter Otten wrote: > >> Achim Domma wrote: >> >>> I want to use Python to script some formulas in my application. The user >>> should be able to write something like >>> >>> A = B * C >>> >>> where A,B,C are instances of some wrapper classes. Overloading * is no >>> problem but I cannot overload the assignment of A. I understand that >>> this is due to the nature of Python, but is there a trick to work around >>> this? >> >>>>> class D(dict): >> ... def __setitem__(self, key, value): >> ... print key, "<--", value >> ... dict.__setitem__(self, key, value) >> ... >>>>> namespace = D(B=42, C=24) >>>>> exec "A = B * C" in namespace >> A <-- 1008 > > Very clever, except: > > (1) The Original Poster's requirement was for a "clean syntax" and > 'exec "A = B * C" in namespace' is anything but a clean syntax. > > (2) The O.P. specifies that the syntax is for use by his users. We don't > know who these users are, but can you see users getting this right and not > ignoring the namespace argument? I thought he might hide everything but the expression A = B * C from the user. > (3) Even if they do use the namespace argument, how hard is it for the > users to break the security of your exec? > >>>> exec "A = B * C;import os;os.system('ls -l break-something')" in >>>> namespace > A <-- 1008 > os <-- <module 'os' from '/usr/lib/python2.4/os.pyc'> > -rw-rw-r-- 1 steve steve 0 Jan 24 08:27 break-something > > Using exec on user-supplied data is just begging to be p0wned. Yes. Unless the application is deployed to the user's machine, in which case he has more straightforward methods to destroy his own data. Peter From wolfson at gmail.com Wed Jan 24 00:23:07 2007 From: wolfson at gmail.com (Ben Wolfson) Date: Tue, 23 Jan 2007 21:23:07 -0800 Subject: sqlite user-defined functions & unicode issue Message-ID: <6282abf10701232123p306a85adq9ddf49f9ad2d56b8@mail.gmail.com> I've got a db some of whose elements have been created automatically from filesystem data (whose encoding is iso-8859-1). If I try to select one of those elements using a standard SQL construct, things work fine: >>> sqlite.register_converter("text", unicode) >>> db = sqlite.connect(".mdb/database", detect_types=sqlite.PARSE_COLNAMES) >>> cursor = db.cursor() >>> cursor.execute("SELECT * FROM artists WHERE name LIKE ?", ("John Butcher%",)).fetchall() [(1653, u'John Butcher & Eddie Pr\xe9vost')] >>> But if I use the pysqlite recipe for searching with a regexp, things don't work: >>> db.create_function("regexp", 2, regexp) >>> cursor.execute("SELECT * FROM artists WHERE REGEXP(?, name)", ('John Butcher',)).fetchall() Traceback (most recent call last): File "<pyshell#14>", line 1, in -toplevel- cursor.execute("SELECT * FROM artists WHERE REGEXP(?, name)", ('John Butcher',)).fetchall() OperationalError: user-defined function raised exception >>> Testing reveals that "item" is passed as None: >>> def regexp(expr, item): if item is None: return False r = re.compile(expr, re.I) return r.search(item) is not None >>> db = sqlite.connect(".mdb/database", detect_types=sqlite.PARSE_COLNAMES) >>> db.create_function("regexp", 2, regexp) >>> cursor.execute("SELECT * FROM artists WHERE REGEXP(?, name)", ('John Butcher',)).fetchall() [] >>> How can I get around this? I really want to be able to search by regexp, and not just the standard SQL %-pattern. -- Ben Wolfson "However, identifying what we call 'time' or even 'space', which I shall mention soon, is a very difficult problem, and a philosopher would say that it is an extremely annoying subject." (Soseki Natsume, "The Philosophical Foundations of Literature") From Sebastien.Boisgerault at gmail.com Wed Jan 17 14:22:05 2007 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 17 Jan 2007 11:22:05 -0800 Subject: XLM prolgoue References: <1169054322.500863.313660@11g2000cwr.googlegroups.com> Message-ID: <1169061724.975465.211010@s34g2000cwa.googlegroups.com> fscked wrote: > How do I go about creating the XML prologue like I want it to be? > Specifically, I am trying to add encoding and some namespace stuff. The XML declaration and the DTD that may appear in the prolog are optional. [22] prolog ::= XMLDecl? Misc* (doctypedecl Misc*)? [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' If your encoding is UTF-8 (or ASCII ...) you don't need an XML declaration. Otherwise everything depends on the XML lib you use. For ElementTree, `tostring(elt, "ISO-8859-1")` for example will automatically include the right declaration at the beginning of your xml string ... There is no namespace information inside the prolog. Such "stuff" may appear inside the root element. Again, RTFM of your specific XML lib :) For ElementTree, see http://effbot.org/zone/element.htm#xml-namespaces Cheers, SB From Eric_Dexter at msn.com Sat Jan 20 10:09:40 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 20 Jan 2007 07:09:40 -0800 Subject: when format strings attack In-Reply-To: <eor81m$fuu$1@gemini.csx.cam.ac.uk> References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> <pan.2007.01.19.19.06.43.598000@REMOVE.THIS.cybersource.com.au> <eor81m$fuu$1@gemini.csx.cam.ac.uk> Message-ID: <1169305780.851809.11520@38g2000cwa.googlegroups.com> I will give the formatting a try. I noticed another formatting thing I wasn't looking for. It is possible to have a \n at the end of a word or at least that is how it is shown and fixed through python 2.5. I had an error where 36\n isn't a number. easy to fix though. Jeremy Sanders wrote: > Steven D'Aprano wrote: > > > os.system('dir -l %s' % 'text.txt') > > > > > > Now, there is a security risk: you might set command1 yourself, and > > allow the user to set args. If command1 is an external application > > with a security hole, and the user provides arguments that trigger that > > bug, then naturally your application will inherit whatever security > > vulnerabilities the external application suffers from. No surprises there. > > There are also big risks like this > > filename = 'foo; rm importantfile' > cmd = 'ls %s' % filename > os.system(cmd) > > oops! > > -- > Jeremy Sanders > http://www.jeremysanders.net/ From jussij at zeusedit.com Tue Jan 23 01:15:05 2007 From: jussij at zeusedit.com (jussij at zeusedit.com) Date: 22 Jan 2007 22:15:05 -0800 Subject: Python Windows Editors In-Reply-To: <79e7c$45b3facb$d443bb3a$7251@news.speedlinq.nl> References: <p5Qsh.51413$wc5.6534@newssvr25.news.prodigy.net> <79e7c$45b3facb$d443bb3a$7251@news.speedlinq.nl> Message-ID: <1169532905.087232.220040@38g2000cwa.googlegroups.com> Stef Mientki wrote: > there a too many (good) IDE's for Python ;-) FWIW the Zeus for Windows IDE has Python support: http://www.zeusedit.com/python.html Zeus has standard IDE features like syntax highlighting, integrated version control, project/workspace, class browsing etc, but it does smart indenting and code folding for Python and you can even write Zeus macros using Python ;) It is even possible to integrate the Python SDK help directly into the editor: http://www.zeusedit.com/forum/viewtopic.php?t=8 > I tried 2 of them, and only was stable enough: Zeus is rock solid ;) Jussi Jumppanen Author: Zeus for Windows From anthonybaxter at gmail.com Tue Jan 2 23:47:32 2007 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Wed, 3 Jan 2007 15:47:32 +1100 Subject: Looking for python SIP/MGCP stacks In-Reply-To: <1ECA23B17E8AB54C859FA0449B729F0E03428702@xmb-sjc-235.amer.cisco.com> References: <1ECA23B17E8AB54C859FA0449B729F0E03428702@xmb-sjc-235.amer.cisco.com> Message-ID: <e69d3ed20701022047l5e697379q1dfe802824f24b80@mail.gmail.com> On 1/3/07, Jenny Zhao (zhzhao) <zhzhao at cisco.com> wrote: > Thanks Anthony. > > I am wondering where I can get Divmod Sine and Shtoom. Are they open > source ? > > Thanks again > Jenny http://www.google.com/search?q=divmod+sine http://www.google.com/search?q=shtoom From wangshuhao at sina.com Wed Jan 24 09:39:35 2007 From: wangshuhao at sina.com (Wang Shuhao) Date: Wed, 24 Jan 2007 22:39:35 +0800 Subject: sys.path issue in cygwin References: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> <ep7nni$5op$2@sea.gmane.org> Message-ID: <002901c73fc5$7a045540$1400a8c0@mytomato> There is only python2.2.3 on my machine, and the location is /usr/local/lib/python2.2 . I say the 'C/lib/python2.2/' is a wrong path is because the leading C/lib is not point to the location of my python installation. I'v found the solution anyway. The environment variable PYTHONHOME controls the content of the initial sys.path. put export PYTHONHOME=/usr/local in .bash_profile will fix it. ----- Original Message ----- From: "Steve Holden" <steve at holdenweb.com> To: <python-list at python.org> Sent: Wednesday, January 24, 2007 9:42 PM Subject: Re: sys.path issue in cygwin > Wang Shuhao wrote: >> >> >> I successfully built and installed Python 2.2.3 in cygwin. But there is >> something wrong in the sys.path. I use following statments for a test. >> >> >>> import sys >> >>> print sys.path >> ['', 'C/lib/python2.2/', 'C/lib/python2.2/plat-cygwin', >> 'C/lib/python2.2/lib-tk' >> , '\\Python24/lib/python2.2/lib-dynload'] >> >>> >> >> To keep the question simple, I've set PATH= in cygwin.bat to avoid >> python initialze sys.path from Windows' PATH environment. >> >> Obviously, 'C/lib/python2.2/' is a wrong path. In fact my python is >> installed in /usr/local/lib/python2.2.3. The result of the issue is that >> when you run a program python can't find the module. So what I really >> want to know is where these path came from and how to fix it. >> >> >> > Why "obviously"? 2.2.3 and 2.2.2 aren't meant to coexist, so one will > install over the other. So the directories you are seeing are what would > be used with standard prefix settings. > > If you mean "obviously because I used a setting to configure the > prefixes for loading from a specific directory" then perhaps you are > suffering from having set your Windows PATH. If you *don't* set your > Windows PATH do you see it using the "2.2.3" variants? > > Did you run "make install"? > > Just a couple of random thoughts ... are you even sure that running the > "python" command does run your new 2.2.3 binary? > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com > > -------------------------------------------------------------------------------- > -- > http://mail.python.org/mailman/listinfo/python-list From deacon.sweeney at gmail.com Tue Jan 30 17:13:07 2007 From: deacon.sweeney at gmail.com (deacon.sweeney at gmail.com) Date: 30 Jan 2007 14:13:07 -0800 Subject: Resizing widgets in text windows In-Reply-To: <op.tmwp1letrqur0o@eb.pragmadev> References: <1169847315.631951.295830@a75g2000cwd.googlegroups.com> <op.tmwp1letrqur0o@eb.pragmadev> Message-ID: <1170195187.058117.14830@q2g2000cwa.googlegroups.com> On Jan 29, 3:33 am, "Eric Brunel" <eric_bru... at despammed.com> wrote: > On Fri, 26 Jan 2007 22:35:20 +0100, <deacon.swee... at gmail.com> wrote: > > Hi, I've been searching for a .resize()-like function to overload much > > like can be done for the delete window protocol as follows: > > > toplevel.protocol("WM_DELETE_WINDOW", callback) > > > I realize that the pack manager usually handles all of the resize > > stuff, but I've found an arrangement that the pack manager fails for. > > That is, if one embeds a canvas into a window created inside a text > > widget, then resize the text widget (via its container), the canvas and > > its container windows do not resize. > > Supposing you call "embedding" inserting a widget in the text via the > window_create method, why should they? Embedding a window in a Text is > used to put some arbitrary widget in the middle of the text it contains. > So the embedded widget has no reason to grow or shrink with the parent > Text widget: it just moves with the text. > > > So I need to resize the window > > that the canvas is embedded in. The most obvious way of doing this > > would be as above, but there does not seem to be an equivalent to the > > "WM_DELETE_WINDOW" protocol for resizing. > > As James said, the <Configure> event is your friend. But I'm not sure I > understand your use case... > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" I'm using a text widget to hold a set of plots, one plot per line, such that the scrolling capability of the text widget can be taken advantage of to display only a subset of the plots at any given time. In the analyses my program automates, there are at least several plots are typically loaded into the text widget. This works out splendidly, but the width of the plots has thus far been a static thing. Now, I'll be able to adjust the plots widths so that when the owner window is resized, the width of each plot in the text widget is adjusted and the plot continues to occupy the entire text widget but no more, making for a much more professional looking product. I didn't mean to imply that create_window widgets should automatically resize with the toplevel... I just couldn't find any way to force it. Muchas gracias. Deacon From jmfbahciv at aol.com Thu Jan 11 08:52:22 2007 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Thu, 11 Jan 07 13:52:22 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> <N6Uoh.43209$wc5.29633@newssvr25.news.prodigy.net> <eo2t6h$8qk_014@s808.apx1.sbo.ma.dialup.rcn.com> <0001HW.C1CA63B1059BC980F0203648@news.verizon.net> <eo33rr$8ss_008@s1005.apx1.sbo.ma.dialup.rcn.com> <MPG.200f26e6b5607c46989ef0@news.individual.net> Message-ID: <eo5fem$8qk_007@s814.apx1.sbo.ma.dialup.rcn.com> In article <MPG.200f26e6b5607c46989ef0 at news.individual.net>, krw <krw at att.bizzzz> wrote: >In article <eo33rr$8ss_008 at s1005.apx1.sbo.ma.dialup.rcn.com>, >jmfbahciv at aol.com says... >> In article <0001HW.C1CA63B1059BC980F0203648 at news.verizon.net>, >> Lefty Bigfoot <nunya at busyness.info> wrote: >> >On Wed, 10 Jan 2007 08:28:33 -0600, jmfbahciv at aol.com wrote >> >(in article <eo2t6h$8qk_014 at s808.apx1.sbo.ma.dialup.rcn.com>): >> > >> >> In article <N6Uoh.43209$wc5.29633 at newssvr25.news.prodigy.net>, >> >> "Elan Magavi" <Elan at nomailnospam.com> wrote: >> >>> Is that like.. OctaPussy? >> >> >> >> I didn't read their stuff. Are they really trying to put a >> >> round peg in a square hole? >> > >> >Sounds more like an octagonal pole in a round hole. >> >> Nah, I figured they picked the word octal because it's never >> been used before..... > >....and "HexaPussy" just wouldn't be right. > Right. The PC types would put them in jail for being cruel to animals. /BAH From newstips6706 at yahoo.com Wed Jan 17 21:35:18 2007 From: newstips6706 at yahoo.com (newstips6706 at yahoo.com) Date: 17 Jan 2007 18:35:18 -0800 Subject: 1, 2, 3, 5, 7... PRIME Numbers Message-ID: <1169087718.529514.45710@11g2000cwr.googlegroups.com> 1, 2, 3, 5, 7... PRIME Numbers [ Mathematics / Physics / Engineering ] ________________________________ Definitions What is a PRIME Number ? A PRIME number is a number whose only positive divisors are one and itself. What is a MAGIC SQUARE? A magic square is an arrangement of numbers in a square, such that the numbers in all rows, all columns, and both diagonals sum to the same number. ________________________________ MAGIC SQUARES & PRIME Numbers The secret of PRIME Numbers are embedded within the puzzle known as "MAGIC SQUARES". PRIME Numbers and Magic Squares go hand in hand. PRIME Numbers & The Number '1' PRIME Numbers are the progress of TIME or The Number '1' in the universe. Another definition of "Science" is the comprehension of PRIME Numbers. The Number '1' is like "a seed" and PRIME Numbers is the "tree" that grows or progresses from that seed. The seed and the tree are one and the same. ________________________________ The Comphrehension of the Number '1' IS the study of PRIME Numbers, for the Number '1' is the only number in the universe that is truly "indivisible". Since PRIME Numbers take on the nature of the Number '1', and the Number '1' is the seed of all PRIME Numbers, therefore the Number '1' is PRIME Number. ________________________________ To "divide" a PRIME by "itself" OR by the Number '1', results in a "canceling of itself out" OR the PRIME Number "dissolves into its original state" of "NOTHING" OR . EXAMPLES: 1 / 1 = PI 2 / 1 = PI 2 / 2 = PI 3 / 1 = PI 3 / 3 = PI etc. ________________________________ PRIME Numbers & TIME To count 'TIME' is to count the number of 'coincidences' OR same - time - occurrences of The Number '1'. "To count TIME" IS NOT EQUAL TO "measuring TIME" in "seconds", "minutes", "hours", "days", etc. To measure TIME in "seconds", "minutes", etc. is impossible. THEREFORE "To count TIME" IS to count in (the) PRIME Numbers: 1,2,3,5,7,11,13... From freelapbandseminar at yahoo.com Fri Jan 19 04:26:14 2007 From: freelapbandseminar at yahoo.com (AwesomeMultimedia.com) Date: 19 Jan 2007 01:26:14 -0800 Subject: www.OutpatientSurgicare.com/video/ Message-ID: <1169198774.479699.107300@l53g2000cwa.googlegroups.com> www.OutpatientSurgicare.com/video/ Outpatient Doctors Surgery Center is committed to offering the healthcare the community needs. We offer patients a meaningful alternative to traditional surgery. This state-of-the-art outpatient surgery center, located in the heart of Orange County, at 10900 Warner Avenue, Suite 101A, Fountain Valley, Ca 92708, offers the latest innovations in outpatient surgery and technology. Please Call For Our Special Cash Discount Toll Free: 1-877-500-2525 Please Visit Our Websites: We offer extreme cosmetic surgery makeover packages. http://www.SurgeonToTheStars.com http://www.1cosmeticsurgery.com Specializing in the cure of hyperhidrosis, sweaty palms, underarm and foot sweating. http://www.CuresweatyPalms.com http://www.ControlExcessiveSweating.com No. 1 Weight Loss Surgery Center http://www.ControlWeightLossNow.com http://www.FreeLapBandSeminar.com Hernia Treatment Center http://www.HerniaDoc.com Take care of your feet http://www.CureFootPain.com The Experts in CARPAL TUNNEL SYNDROME http://www.CureHandPain.com Accidental Urine Leaks ? End Urinary Incontinence http://www.WomanWellnessCenter.com Hemorrhoid Treatment Center http://www.hemorrhoidtreatmentcenter.com From bbands at gmail.com Fri Jan 26 11:59:17 2007 From: bbands at gmail.com (BBands) Date: 26 Jan 2007 08:59:17 -0800 Subject: time series data and NumPy Message-ID: <1169830757.220964.196540@m58g2000cwm.googlegroups.com> Good morning, I store time series data in a SQL database. The results of a typical query using pyodbc look like this. Date Close "2007-01-17" 22.57 Where Date is a datetime.date object and Close is a float. I'd like to put this data in a NumPy array for processing, but am unsure as to how to handle the date. In the past I've used lists, but I am looking to boost speed a bit as I wish to do a large number of transformations and comparisons. Can one index an array using datetime objects? For example it would be nice to do a union of two arrays so that any dates missing in either one were eliminated. Thoughts on doing rolling operations, such as an n-period average or variance? Thoughts on working with time series data in arrays in general? Thanks in advance, jab--who is very happily returning to Python after a sojourn in R-land From jonc at icicled.net Sun Jan 28 18:17:59 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sun, 28 Jan 2007 17:17:59 -0600 Subject: Data structure and algorithms In-Reply-To: <1170025297.838143.191740@j27g2000cwj.googlegroups.com> References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> <1170025297.838143.191740@j27g2000cwj.googlegroups.com> Message-ID: <200701281717.59485.jonc@icicled.net> What are you trying to make in the first place? A singly linked list? If so google is littered with examples of linked lists done in python. A simple search for 'python linked list' brings up many results. Btw, for future reference, no need for apologetics (the second post). - Jonathan From bignose+hates-spam at benfinney.id.au Tue Jan 30 19:10:46 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 31 Jan 2007 11:10:46 +1100 Subject: Garbage collection (was: how to "free" an object/var ?) References: <dfacb$45bfd788$d443bb3a$7010@news.speedlinq.nl> Message-ID: <87ejpcvywp.fsf@benfinney.id.au> Stef Mientki <S.Mientki-nospam at mailbox.kun.nl> writes: > If I create a large array of data or class, how do I destroy it > (when not needed anymore) ? Python comes with garbage collection, which is enabled by default. Some time after your code stops needing the object, the garbage collector will clean it up. To check whether your Python has garbage collection enabled, you can use the 'gc' interface module: Python 2.4.4 (#2, Jan 13 2007, 17:50:26) [...] >>> import gc >>> gc.isenabled() True >>> help(gc) This module is only needed if you want to *interact* with the garbage collector, which you won't unless you want to tune it or turn it off. -- \ "Immorality: The morality of those who are having a better | `\ time." -- Henry L. Mencken | _o__) | Ben Finney From ptwobrussell at gmail.com Sat Jan 13 17:56:30 2007 From: ptwobrussell at gmail.com (MR) Date: 13 Jan 2007 14:56:30 -0800 Subject: Decorators inside of class and decorator parameters Message-ID: <1168728983.541526.202320@l53g2000cwa.googlegroups.com> Hello All, I have a question about decorators, and I think an illustration would be helpful. Consider the following simple class: #begin code class Foo: def fooDecorator(f): print "fooDecorator" def _f(self, *args, **kw): return f(self, *args, **kw) return _f @fooDecorator def fooMethod(self): print "fooMethod" f = Foo() f.fooMethod() #end of code This code runs, and actually serves my purpose. However, I'm a little confused about three things and wanted to try and work through them while I had the time to do so. I believe all of my confusion is related to the parameters related to the fooDecorator: -how I would pass arguments into the fooDecorator if I wanted to (my various attempts have failed) -what the difference is between decorating with @fooDecorator versus @fooDecorator() -why does this code even work, because the first argument to fooDecorator isn't self I'm searched the net and read the PEPs that seemed relevant, but I didn't see much about decorators inside of a class like this. Can anyone comment on any of these three things? From notsonice51 at yahoo.com Tue Jan 9 22:36:17 2007 From: notsonice51 at yahoo.com (notsonice51 at yahoo.com) Date: 9 Jan 2007 19:36:17 -0800 Subject: "tkinter module not found" please help Message-ID: <1168400177.167870.61900@i56g2000hsf.googlegroups.com> I'm trying to install python2.5 on my computer(os Fedora 5). My problem is that I'm unable to get the tkinter module loaded into python. I've tried the solution here:"wiki.python.org/moin/TkInter" but am unsure as how to modify my setup.py script. I have installed the latest versions of tcl/tk (8.4.14) twice as well as installing python again. Everything is installed in the default location but still no luck. Does anyone have any ideas? Thank you. From wolf_tracks at invalid.com Sat Jan 6 11:06:02 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 06 Jan 2007 08:06:02 -0800 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: <BDInh.32100$Gr2.31964@newssvr21.news.prodigy.net> References: <djvnh.11482$ZT3.4851@newssvr19.news.prodigy.com> <mailman.2332.1168016502.32031.python-list@python.org> <GAInh.32097$Gr2.21336@newssvr21.news.prodigy.net> <BDInh.32100$Gr2.31964@newssvr21.news.prodigy.net> Message-ID: <yNPnh.9155$x67.8570@newssvr17.news.prodigy.net> The wiki site lead to a link to download pythonwin, but the download is broken. Googling invariably leads back to that link. I found <http://www.python.org/download/releases/binaries-1.4/pythonwin/>, which has two files listed: oadist.exe and win32dbg.exe. Do I need both or is just the latter one? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet ""I do not fear death. I had been dead for billions and billions of years before I was born, and had not suffered the slightest inconvenience from it." -- Mark Twain (a nod to evolution) -- Web Page: <home.earthlink.net/~mtnviews> From nszabolcs at gmail.com Mon Jan 29 19:32:42 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 16:32:42 -0800 Subject: deepcopy alternative? In-Reply-To: <45be808e$0$27074$4c368faf@roadrunner.com> References: <45be808e$0$27074$4c368faf@roadrunner.com> Message-ID: <1170117161.953913.276600@v33g2000cwv.googlegroups.com> > I believe the only thing stopping me from doing a deepcopy is the > function references, but I'm not sure. If so is there any way to > transform a string into a function reference(w/o eval or exec)? what's your python version? for me deepcopy(lambda:1) does not work in py2.4 but it works in py2.5 (in py2.4 i tried to override __deepcopy__ but it had no effect) From arkanes at gmail.com Fri Jan 26 10:48:35 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 26 Jan 2007 09:48:35 -0600 Subject: Win XP "Sleep" mode: can Py wake up? In-Reply-To: <2387F0EED10A4545A840B231BBAAC722F117C8@slcimail1.slcgov.com> References: <2387F0EED10A4545A840B231BBAAC722F117C8@slcimail1.slcgov.com> Message-ID: <4866bea60701260748s1191a7et8fcc3a21b46e5dd4@mail.gmail.com> On 1/26/07, Bell, Kevin <kevin.bell at slcgov.com> wrote: > Does anyone have any experience having python deal with sleep mode? I'd > love to run something that would hear a sleep event coming and pickle > some data before sleep, then after coming out of sleep, unpickle... > > Any thoughts? > The whole point of sleep mode is that the OS "pickles" it's state and that of all processes, then restores them when it wakes up. The only reason you, as an application, would need to do anything is if you're consuming an external resource that can't survive sleep, like a network connection. Even then, if your application is robust against (non-sleep) network problems and outages you should be able to just pick up where you left off when the network comes back online. From gdamjan at gmail.com Wed Jan 24 20:28:33 2007 From: gdamjan at gmail.com (Damjan) Date: Thu, 25 Jan 2007 02:28:33 +0100 Subject: The reliability of python threads References: <mailman.3092.1169657938.32031.python-list@python.org> <ep841j$anu$1@gemini.csx.cam.ac.uk> <mailman.3095.1169659417.32031.python-list@python.org> <ep883i$iom$1@gemini.csx.cam.ac.uk> <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <mailman.3105.1169664198.32031.python-list@python.org> <1169683654.672020.136820@q2g2000cwa.googlegroups.com> <7xveiwklt0.fsf@ruckus.brouhaha.com> <1169687269.885833.285410@a34g2000cwb.googlegroups.com> <7x8xfr6h0j.fsf@ruckus.brouhaha.com> Message-ID: <45b807f8$0$49204$14726298@news.sunsite.dk> >> and the GIL is more than an "artifact". It is a central tenet of >> threaded python programming. > > If it's a central tenet of threaded python programming, why is it not > mentioned at all in the language or library manual? The threading > module documentation describes the right way to handle thread > synchronization in Python, and that module implements traditional > locking approaches without reference to the GIL. And we all hope the GIL will one day die it's natural death ... maybe... probably.. hopefully ;) -- damjan From tiedon_jano at hotmail.com Fri Jan 5 16:21:41 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Fri, 05 Jan 2007 21:21:41 GMT Subject: Learning to program in Python In-Reply-To: <mailman.2349.1168030739.32031.python-list@python.org> References: <mailman.2349.1168030739.32031.python-list@python.org> Message-ID: <Fjznh.445$sE.152@read3.inet.fi> Demel, Jeff kirjoitti: > If I were you, I'd think up a project and just build it. The best way > to really learn is to do, at least for me. If you run into problems, > then you can come back and ask the group here. Believe me, I've asked > some very basic questions, and everyone's been very friendly and > helpful. > > As an EE major, maybe you can think of some project that interests you > and build it. One thing that comes to mind is, maybe, a graphical > program to lay out circuits? Parts inventory program? Circuit tester? > I don't know, I was an English major, but you get the idea. > > Anyway, try to think of a project that includes several of the key > fundamentals of programming that we do every day, like reading and > writing files, reading and writing to a database, GUI development, and > things like that. > > HTH > > -Jeff > > > -----Original Message----- > From: python-list-bounces+jeff.demel=javelindirect.com at python.org > [mailto:python-list-bounces+jeff.demel=javelindirect.com at python.org] On > Behalf Of jbchua > Sent: Friday, January 05, 2007 2:22 PM > To: python-list at python.org > Subject: Learning to program in Python > > Hello everybody. > > I am an Electrical Engineering major and have dabbled in several > languages such as Python, C, and Java in my spare time because of my > interest in programming. However, I have not done any practical > programming because I have no idea where to get started. I taught myself > these languages basically by e-tutorials and books. This makes me feel > as if I don't really know how to implement these languages. > Does anybody have any advice on where to start applying my limited > knowledge practically in order to advance my learning? > > -- > http://mail.python.org/mailman/listinfo/python-list > This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. And choose a project on a subject you know well. The project should feel almost too easy to you. Believe me: it will still keep you busy but when you know your subject you can concentrate on learning to use Python as it should. HTH, Jussi From nmm1 at cus.cam.ac.uk Wed Jan 10 12:40:49 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 10 Jan 2007 17:40:49 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <mailman.2408.1168248992.32031.python-list@python.org> <Xns98B269DCC12Fduncanbooth@127.0.0.1> <entr6s$ovo$1@news.albasani.net> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> Message-ID: <eo38f1$6cu$1@gemini.csx.cam.ac.uk> In article <1168449342.414838.181050 at p59g2000hsd.googlegroups.com>, "sturlamolden" <sturlamolden at yahoo.no> writes: |> |> MPI is becoming the de facto standard for high-performance parallel |> computing, both on shared memory systems (SMPs) and clusters. It has been for some time, and is still gaining ground. |> Spawning |> threads or processes is not recommended way to do numerical parallel |> computing. Er, MPI works by getting SOMETHING to spawn processes, which then communicate with each other. |> Threading makes programming certain tasks more convinient |> (particularly GUI and I/O, for which the GIL does not matter anyway), |> but is not a good paradigm for dividing CPU bound computations between |> multiple processors. MPI is a high level API based on a concept of |> "message passing", which allows the programmer to focus on solving the |> problem, instead on irrelevant distractions such as thread managament |> and synchronization. Grrk. That's not quite it. The problem is that the current threading models (POSIX threads and Microsoft's equivalent) were intended for running large numbers of semi-independent, mostly idle, threads: Web servers and similar. Everything about them, including their design (such as it is), their interfaces and their implementations, are unsuitable for parallel HPC applications. One can argue whether that is insoluble, but let's not, at least not here. Now, Unix and Microsoft processes are little better but, because they are more separate (and, especially, because they don't share memory) are MUCH easier to run effectively on shared memory multi-CPU systems. You still have to play administrator tricks, but they aren't as foul as the ones that you have to play for threaded programs. Yes, I know that it is a bit Irish for the best way to use a shared memory system to be to not share memory, but that's how it is. Regards, Nick Maclaren. From steve at REMOVEME.cybersource.com.au Mon Jan 8 02:28:03 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Jan 2007 18:28:03 +1100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <ct1oh.8348$w91.141@newsread1.news.pas.earthlink.net> <7x7ivz88af.fsf@ruckus.brouhaha.com> <mailman.2385.1168171076.32031.python-list@python.org> <7xmz4v11jq.fsf@ruckus.brouhaha.com> <pan.2007.01.07.22.10.37.701405@REMOVE.THIS.cybersource.com.au> <7xlkke19he.fsf@ruckus.brouhaha.com> Message-ID: <pan.2007.01.08.07.28.02.494235@REMOVEME.cybersource.com.au> On Sun, 07 Jan 2007 19:30:05 -0800, Paul Rubin wrote: > Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> writes: >> > If you want to write bug-free code, pessimism is the name of the game. >> >> I wonder whether Paul uses snow chains all year round, even in the blazing >> summer? After all, "if you want to drive safely, pessimism is the name of >> the game". > > No. I'm willing to accept a 10**-5 chance of hitting a freak > snowstorm in summer, since I drive in summer at most a few hundred > times a year, so it will take me 100's of years before I'm likely to > encounter such a storm. There are millions of drivers, so if they all > take a similar chance, then a few times a year we'll see in the paper > that someone got caught in a storm, which is ok. Usually there's no > real consequence beyond some inconvenience of waiting for a tow truck. > > Tow truck or ambulance operators, on the other hand, should keep > chains available all year around, since they have to service the needs > of millions of users, have to be ready for freak summer storms. > > As a software developer wanting to deploy code on a wide scale, I'm > more like a tow truck operator than an individual car driver. > Alternatively, as a coder I "drive" a lot more often. If some Python > misfeature introduces a bug with probability 10**-5 per line of code, > then a 100 KLoc program is likely to have such a bug somewhere. It > doesn't take 100's of years. That's an irrelevant argument. We're not talking about random bugs in random places of code, we're talking about one specific type of bug which can only occur in a handful of very restricted set of circumstances, e.g. you have to inherit from two classes which not only have exactly the same name but they also have the same private attribute. Your argument is that Python's strategy for dealing with private attributes is insufficiently pessimistic, because it doesn't deal with those circumstances. Fine. I agree. Python isn't pessimistic. Does it need to be? Just how often do you inherit from two identically-named classes both of which use identically-named private attributes? You suggested that coders (and by extension, Python) should behave with equal pessimism whether they are subclassing two identically-named classes or not. That's equivalent to the argument that one should use snow chains whether it is snowing or not -- it only considers the benefit of the extra protection, without considering the costs. Python's private attribute handling balances convenience and protection, giving more weight to convenience, trading off some protection. And convenience gives increased productivity, easier debugging, few bugs overall, and other Good Things. It would probably change the character of Python unacceptably much to push that balance the other way. Don't get me wrong, it is a good thing for you to alert people to the circumstances that Python's strategy breaks down, so that they can "use snow chains" in those circumstances. And, hey, if somebody reads this thread and is motivated to find a better strategy that doesn't change the nature of the language by too much, great. (This happened once before: multiple inheritance was broken in classic classes, and new classes where added partly to fix that.) But chances are, the majority of Pythonistas will think that having to use snow chains once in a very great while is an acceptable trade-off to the smooth ride Python gives the rest of the time. -- Steven D'Aprano From akhavr at kds.com.ua Mon Jan 15 17:35:12 2007 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Tue, 16 Jan 2007 00:35:12 +0200 Subject: [ANN] Py2Py 0.0.1 - python code reformatter, initial dev release Message-ID: <m3irf7hqan.fsf@netmaster.kds.com.ua> Folks, We release development preview snapshot of Py2Py code reformatter [1]. It is a byproduct of the PyBeast project aimed to create the python mutation tester. Now Py2Py code reformatter ignores all comments and 80-char line length requirement. Nevertheless, it produces the same AST as the original code. The code is developed in a test-first manner and has 100% test coverage. Feedback, criticism and bug reports are welcome. Links: [1] http://trac.kds.com.ua/project/pybeast/ [2] http://www.kds.com.ua/wp/2007/01/16/py2py-001-initial-development-snapshot/ -- Andrey V Khavryuchenko Software Development Company http://www.kds.com.ua/ From bdesth.quelquechose at free.quelquepart.fr Sat Jan 6 17:16:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Jan 2007 23:16:26 +0100 Subject: still struggling, howto use a list-element as a name ? In-Reply-To: <b7908$459fef43$d443bb3a$26766@news.speedlinq.nl> References: <b7908$459fef43$d443bb3a$26766@news.speedlinq.nl> Message-ID: <45a01981$0$296$426a74cc@news.free.fr> Stef Mientki a ?crit : > In the example below, "pin" is an object with a number of properties. > Now I want > 1- an easy way to create objects that contains a number of these "pin" > 2- an multiple way to access these "pin", i.e. > device.pin[some_index] > device.some_logical_name > ad 1: > a dictionary (as "pinlist" in the example) seems a very convenient > way (from a viewpoint of the device creator). > As you can see in the "__init__" section this dictionary can easily be > transported to the pin-objects. > > ad 2: > THAT's the problem: how do automate these lines "self.GND = self.pin[0]" > > I'm also in for other solutions. I'm afraid I don't understand your design (nor the domain FWIW). A few comments anyway: > > class Power_Supply(device): Please reread my comments about naming convention in a previous thread... > pinlist = { This is *not* a list, so naming it 'pinlist' is misleading. Also, why is this defined here ? > 0: ('GND', _DIG_OUT, _par2), > 1: ('VCC', _DIG_OUT, _par33) > } > > def __init__(self): > # store pin-names and pin-parameters in pins > for k in self.pinlist.keys(): > self.pin[k].Name = self.pinlist[k][0] What is 'self.pin' ? Where is it defined ? (NB : please try to post *runnable* code). And FWIW, if it's a container, why is it named 'pin', and not 'pins' ? > self.pin[k].Value = self.pinlist[k][2] The appropriate way to use the for loop here is: for k, v in self.pinlist.items(): self.pin[k].name = v[0] # etc > # for some pins, we also want to be able to use logical names > # HOW TO USE SOMETHING like > # "self.pinlist[0] = self.pin[0]" > # INSTEAD OF > self.GND = self.pin[0] > self.VCC = self.pin[1] you can build a 'reversed index': # store pin-names and pin-parameters in pins for k, v in self.pinlist.items(): self.pin[k].name = v[0] self.pin[k].value = v[2] self.reversed_index[v[0]] = self.pin[k] and then use the __getattr__ hook: def __getattr__(self, name): return self.reversed_index[name] But the whole thing still looks awfully convulted and kludgy to me, and I suspect serious design flaws... Why don't you try and explain your real problem, instead of asking how to implement what you *think* is the solution ? From no-spam at no-spam-no-spam.invalid Thu Jan 11 09:17:49 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 11 Jan 2007 15:17:49 +0100 Subject: Parallel Python In-Reply-To: <1168516936.890690.235300@p59g2000hsd.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <mailman.2408.1168248992.32031.python-list@python.org> <Xns98B269DCC12Fduncanbooth@127.0.0.1> <entr6s$ovo$1@news.albasani.net> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <eo38f1$6cu$1@gemini.csx.cam.ac.uk> <7x8xga215f.fsf@ruckus.brouhaha.com> <eo3bjj$cen$1@gemini.csx.cam.ac.uk> <eo52h9$kad$1@news.albasani.net> <1168516936.890690.235300@p59g2000hsd.googlegroups.com> Message-ID: <eo5gtj$6bs$1@news.albasani.net> sturlamolden wrote: > robert wrote: > >> Thus communicated data is "serialized" - not directly used as with threads or with custom shared memory techniques like POSH object sharing. > > Correct, and that is precisely why MPI code is a lot easier to write > and debug than thread code. The OP used a similar technique in his > 'parallel python' project. Thus there are different levels of parallelization: 1 file/database based; multiple batch jobs 2 Message Passing, IPC, RPC, ... 3 Object Sharing 4 Sharing of global data space (Threads) 5 Local parallelism / Vector computing, MMX, 3DNow,... There are good reasons for all of these levels. Yet "parallel python" to me fakes to be on level 3 or 4 (or even 5 :-) ), while its just a level 2 system, where "passing", "remote", "inter-process" ... are the right vocables. With all this fakes popping up - a GIL free CPython is a major feature request for Py3K - a name at least promising to run 3rd millenium CPU's ... > This does not mean that MPI is inherently slower than threads however, > as there are overhead associated with thread synchronization as well. level 2 communication is slower. Just for selected apps it won't matter a lot. > With 'shared memory' between threads, a lot more fine grained > synchronization ans scheduling is needed, which impair performance and > often introduce obscure bugs. Its a question of chances and costs and nature of application. Yet one can easily restrict inter-thread communcation to be as simple and modular or even simpler as IPC. Search e.g. "Python CallQueue" and "BackgroundCall" on Google. Thread programming is less complicated as it seems. (Just Python's stdlib offers cumbersome 'non-functional' classes) Robert From gherron at islandtraining.com Tue Jan 16 14:16:33 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 16 Jan 2007 11:16:33 -0800 Subject: How can I create a linked list in Python? In-Reply-To: <eoj6rr$90bt$1@netnews.upenn.edu> References: <eoj6rr$90bt$1@netnews.upenn.edu> Message-ID: <45AD2491.90907@islandtraining.com> Dongsheng Ruan wrote: > with a cell class like this: > > #!/usr/bin/python > > import sys > > class Cell: > > def __init__( self, data, next=None ): > self.data = data > self.next = next > > def __str__( self ): > return str( self.data ) > > def echo( self ): > print self.__str__() > If you really want a list (as Python defines a list - with all the methods) then you should use Python's lists. They are quite efficient and convenient: l = [Cell(1), Cell(2), Cell(3)] However, if what you want is each cell to refer to a next cell (which after all is what a linked list does), then you already have it with the next attribute. (In other languages you might implement 'next' as a pointer, while in Python we call it a reference -- but it amounts to the same thing.) Create it this way: c = Cell(3) b = Cell(2, c) a = Cell(1, b) or a = Cell(1, Cell(2, Cell(3))) However, I'll repeat this: The concept of a linked list if a figment of languages with pointer data types. Python abstracts that by allowing attributes to contain references to other objects. However, you're much better off if you can use Python's list data structure rather than try to emulate an outdated concept in a modern language. Gary Herron From gagsl-py at yahoo.com.ar Mon Jan 29 23:43:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 01:43:13 -0300 Subject: Getting the output from a console command while it's been generated! References: <684b0a740701261905o76ca3a9av6425b88cd1c3b9fc@mail.gmail.com> <epeh79$nok$2@sea.gmane.org> <684b0a740701281854r7108415aqb43221ab5ad9a7d6@mail.gmail.com> Message-ID: <op.tmwfgtbjsd1mbx@gabriel2.softlabbsas.com.ar> En Sun, 28 Jan 2007 23:54:03 -0300, Ra?l G?mez C. <nachogomez at gmail.com> escribi?: > I can't use the subprocess module because my app needs to be compatible > with > Python 2.3 so, is there another approach to this problem??? Any variant of popen; see the popen2 module (but read the last notes on flow control issues). -- Gabriel Genellina From jrpfinch at gmail.com Thu Jan 11 11:12:14 2007 From: jrpfinch at gmail.com (jrpfinch) Date: 11 Jan 2007 08:12:14 -0800 Subject: Newbie question: SMTP -> SQL Server In-Reply-To: <j0tph.33102$X97.7130@newsfe18.lga> References: <1168529572.873867.207730@k58g2000hse.googlegroups.com> <j0tph.33102$X97.7130@newsfe18.lga> Message-ID: <1168531934.015865.177100@i56g2000hsf.googlegroups.com> Thank you. I have just realised I completely misunderstand how SMTP servers work. From what I can tell, when you run the cookbook script it listens locally on port 8025. You then have to configure a Linux (in my case) account with a username and password so my external piece of software (on another Windows machine) can log in and use the SMTP server. Then I write the some code in the cookbook example to redirect any mail content to the MS SQL server database. Note that the external piece of software can only talk SMTP - this is why I am having to develop this script. Does this sound sensible? Any tips on how to configure my Linux box (I don't have much experience with Linux either)? Many thanks Jon From frank at chagford.com Thu Jan 4 00:23:32 2007 From: frank at chagford.com (Frank Millman) Date: 3 Jan 2007 21:23:32 -0800 Subject: Cannot build 2.5 on FC6 x86 In-Reply-To: <503a8vF1d8dn2U1@mid.individual.net> References: <502e72F1eh7ngU1@mid.individual.net> <459c0ac1$0$28366$9b622d9e@news.freenet.de> <503a8vF1d8dn2U1@mid.individual.net> Message-ID: <1167888210.999557.234760@i80g2000cwc.googlegroups.com> Paul Watson wrote: > Martin v. L?wis wrote: > > Paul Watson schrieb: > >> ./configure > >> make > >> make test > >> > >> The result appears to hang after the test_tkl... line. I had to kill > >> the 'make test' process which terminated it. Any suggestions? > > > > Sorry, I mis-typed. It is not test_tkl. It was test_tcl... > > The last line output was as shown below my mistyping. > > I let it sit overnight one time. FWIW, this is my experience. I installed 2.5 on FC6 a few weeks ago, and it has been running with no problems. I ran 'make test' now, and this is what I got. Near the top of the output, I saw the following message - INFO: Can't locate Tcl/Tk libs and/or headers When it got to test_tcl, it showed the following message - test_tcl skipped -- No module named _tkinter At the end, it showed the following - 284 tests OK. 35 tests skipped: [snip details] 1 skip unexpected on linux2: test_tcl It ran to the end without stopping. Hope this may be of some help in diagnosis. Frank Millman From gagsl-py at yahoo.com.ar Thu Jan 18 12:15:44 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 14:15:44 -0300 Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl><mailman.2867.1169130619.32031.python-list@python.org> <45af8f52$0$339$e4fe514c@news.xs4all.nl> Message-ID: <eooa02$uu9$1@sea.gmane.org> "Cecil Westerhof" <dummy at dummy.nl> escribi? en el mensaje news:45af8f52$0$339$e4fe514c at news.xs4all.nl... > Gabriel Genellina wrote: > >> "Cecil Westerhof" <dummy at dummy.nl> escribi? en el mensaje >> news:45af6f47$0$322$e4fe514c at news.xs4all.nl... >> >>>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse >>>I >>> can not time the time used to import time, but os and sys do not take >>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But >>> importing >>> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is >>> there a way to make this more fast? The import off cgi makes the script >>> at least 20 times as slow. Something like mod-python is not a >>> possibility. I could use it on my test machine, but not at the osting >>> provider. >> Surely os was imported earlier, and was already loaded. sys is a builtin >> module. But I think your problem is not how much time takes importing >> cgi, >> but how much time takes launching a new python process on each request. > > Nope, it was certainly cgi. When I fetch time after importing and after > the > script finishes, the difference is 4 milliseconds. If I import the modules > apart from cgi after I fetch the first time, there is added about 1 > millisecond to the difference. When I also import cgi after taking the > time, the difference grows with 95 milliseconds. So for one reason ore > another, cgi is very expensive. I'll try to explain better: the cgi *protocol* (I'm not talking about the cgi *module*) requires a *new* python process to be created on *each* request. Try to measure the time it takes to launch Python, that is, the time from when you type `python ENTER` on your shell and the interpreter prompt appears. That time is wasted for *every* cgi request, and I bet it is much greater than the 95 ms you measure importing a module (be it cgi or whatever). You'll gain much more responsiveness if you can switch to another protocol, be it FastCGI, WSGI, mod_python or another. Anyway, comparing the import time between os, sys, and cgi is not very meaningful. sys is a builtin module, so "import sys" does very little. os is likely to be already imported by the time your script begins, so "import os" just verifies that os is already in sys.modules. "import cgi" is the only example when Python actually has to load something, so it's not a surprise if it takes longer. -- Gabriel Genellina From malaclypse2 at gmail.com Thu Jan 11 11:26:21 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 11 Jan 2007 11:26:21 -0500 Subject: os.mkfifo In-Reply-To: <eo5jh9$2ng$1@ss408.t-com.hr> References: <eo5jh9$2ng$1@ss408.t-com.hr> Message-ID: <16651e80701110826i4d6121b2wed42bbfaeaead28d@mail.gmail.com> On 1/11/07, Gigs_ <gigs at hi.t-com.hr> wrote: > is os.mkfifo available on windows xp http://docs.python.org/lib/os-file-dir.html#l2h-2683 -- Jerry From exarkun at divmod.com Wed Jan 31 22:09:19 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Jan 2007 22:09:19 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <45C1400B.2000204@mvista.com> Message-ID: <20070201030919.25807.112618992.divmod.quotient.5435@ohm> On Wed, 31 Jan 2007 17:19:07 -0800, "Carl J. Van Arsdall" <cvanarsdall at mvista.com> wrote: >Jean-Paul Calderone wrote: >> On Wed, 31 Jan 2007 15:13:59 -0800, "Carl J. Van Arsdall" <cvanarsdall at mvista.com> wrote: >> >>> Jean-Paul Calderone wrote: >>> >>>> [snip] >>>> >>>>> >>>> You're right. Learning new things is bad. My mistake. >>>> >>>> Jean-Paul >>>> >>>> >>> That isn't what I said at all. You have to look at it from a >>> cost/benefit relationship. Its a waste of time/money to learn something >>> complex to do something simple. For the simple things, use a simple >>> solution. KISS. When he has an application that would require >>> something more complex, it would be at that point he should consider >>> using it for a project. Unless the OP has a desire to learn this >>> technology, then more power to him. I, however, do not believe that >>> would be the best approach for a simple problem. >>> >>> Knowing the appropriate tool for the job is a trait of an good engineer. >>> >>> >> >> You are assuming that he already knows how to use threads, and so there >> is no investment required for a threaded solution. In my experience, it's >> much safer to assume the opposite. _Even_ (often _especially_ when a >> threaded solution is explicitly requested. >> >I have a bit more confidence in python threads, but that takes us back >to the age old debate on this list. So we agree to disagree. > You misunderstand. I wasn't expressing a lack of confidence in Python threads, but in the facility with which they can be used by programmers. Jean-Paul From harvey.thomas at informa.com Tue Jan 16 08:55:56 2007 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 16 Jan 2007 05:55:56 -0800 Subject: re.sub and empty groups References: <mailman.2773.1168952918.32031.python-list@python.org> Message-ID: <1168955754.885882.318810@a75g2000cwd.googlegroups.com> Hugo Ferreira wrote: > Hi! > > I'm trying to do a search-replace in places where some groups are > optional... Here's an example: > > >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola").groups() > ('ola', None) > > >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|").groups() > ('ola', '') > > >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|ole").groups() > ('ola', 'ole') > > The second and third results are right, but not the first one, where > it should be equal to the second (i.e., it should be an empty string > instead of None). This is because I want to use re.sub() and when the > group is None, it blows up with a stack trace... > > Maybe I'm not getting the essence of groups and non-grouping groups. > Someone care to explain (and, give the correct solution :)) ? > > Thanks in advance, > > Hugo Ferreira > > -- > GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 >From the documentation: groups( [default]) Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. Your second group is optional and does not take part in the match in your first example. You can, however, still use this regular expression if you use groups('') rather than groups(). A better way probably is to use a simplified regular expression re.match(r"Image:([^\|]+)\|?(.*)", "Image:ola").groups() i.e. match the text "Image:" followed by at least one character not matching "|" followed by an optional "|" followed by any remaining characters. From smusnmrNOSPAM at yahoo.com Thu Jan 11 09:32:25 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Thu, 11 Jan 2007 15:32:25 +0100 Subject: how to clean sys.path References: <eo0eom$cirq$1@zam602.zam.kfa-juelich.de> <p3pbq2h0gaa9qkrl03iansir43vjjp00k7@4ax.com> Message-ID: <eo5hpp$2tmo$1@zam602.zam.kfa-juelich.de> "Tim Roberts" wrote: >> >>when I do >>>sys.path in IDLE (winXP), i get a horrendously long list of >>paths, paths I may have used during a lot of trials and errors. How can I >>clean up sys.path? I mean, trim it of unnecessary paths? > > What do mean by "used during a lot of trials and errors"? sys.path is > recreated from scratch every time Python starts. It doesn't accumulate > over time, other than from new packages that you install. > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. Sorry Tim, my statement was not correct, due to my inexperience with Python. And sorry, too, for my somewhat lengthy reply: After having had inspected my current sys.path... ['C:\\Documents and Settings\\User\\My Documents\\My Python files', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\Lib\\idlelib', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\python25.zip', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\DLLs', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\plat-win', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\lib-tk', 'C:\\Documents and Settings\\User\\My Documents\\Python25', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\site-packages', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\site-packages\\PIL', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\site-packages\\win32', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\site-packages\\win32\\lib', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\site-packages\\Pythonwin', 'C:\\Documents and Settings\\User\\My Documents\\Python25\\lib\\site-packages\\wx-2.8-msw-ansi'] or in plain DOS: C:\Documents and Settings\User\My Documents\My Python files C:\Documents and Settings\User\My Documents\Python25\Lib\idlelib C:\Documents and Settings\User\My Documents\Python25\python25.zip C:\Documents and Settings\User\My Documents\Python25\DLLs C:\Documents and Settings\User\My Documents\Python25\lib C:\Documents and Settings\User\My Documents\Python25\lib\plat-win C:\Documents and Settings\User\My Documents\Python25\lib\lib-tk C:\Documents and Settings\User\My Documents\Python25 C:\Documents and Settings\User\My Documents\Python25\lib\site-packages C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\PIL C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\win32 C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\win32\lib C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\Pythonwin C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\wx-2.8-msw-ansi ...it just looked horrible to me at first sight! If I interpret your explanation correctly, all these paths are necessary, and not relics of previous installations and deinstallations. What puzzles me, though, is, that e.g., when I run the wxPython application "AnalogClock.py" with IDLE or in the command line , this works only in the directory "...\My Python files\wxDemos\" . This directory contains all files and folders from the original "\wx-2.8-msw-ansi\demos\"). When I copy AnalogClock.py to ...\My Python Files\ , nothing happens after running it with IDLE or in the command line. Appending 'C:\Documents and Settings\User\My Documents\My Python files\wxDemos ' to the sys.path does not help either. Thinking that I am clever, I changed my sys.path with sclicing and concatenation such that my sys.path starts with 'C:\Documents and Settings\User\My Documents\My Python files', 'C:\Documents and Settings\User\My Documents\My Python files\wxDemos'. Now \wxDemos\ is being searched very early. ... no way! After running AnalogClock.py again, this error message appears: ------------------------------------------ Traceback (most recent call last): File "C:\Documents and Settings\My Documents\My Python files\wxAnalogClock.py", line 14, in <module> import wx ImportError: No module named wx. ------------------------------------------ Very strange! Because all this wx stuff IS IN the directory 'C:\Documents and Settings\User\My Documents\My Python files\wxDemos'. And AnalogClock.py does work when residing in that directory. Can you help me again? Thanks, siggi P.S. On another PC where the python program is in c:\programs\python25\, same as above! From python at hope.cz Thu Jan 18 11:14:10 2007 From: python at hope.cz (Lad) Date: 18 Jan 2007 08:14:10 -0800 Subject: How to read and write huge binary files Message-ID: <1169136850.518228.103360@l53g2000cwa.googlegroups.com> What is a good way to read binary data from HUGE file and write it to another file? Thanks for help La. From pydecker at gmail.com Sun Jan 7 11:39:48 2007 From: pydecker at gmail.com (Peter Decker) Date: Sun, 7 Jan 2007 11:39:48 -0500 Subject: How to invoke parent's method? In-Reply-To: <1168162412.253449.296520@38g2000cwa.googlegroups.com> References: <1168138626.574514.102060@i15g2000cwa.googlegroups.com> <1168162412.253449.296520@38g2000cwa.googlegroups.com> Message-ID: <ca55a9900701070839y6bbaf116s8a5803e73758a257@mail.gmail.com> On 7 Jan 2007 01:33:32 -0800, Frank Millman <frank at chagford.com> wrote: > The essential point is that you save a reference to the frame when you > create the panel. Then when the button is clicked you can use the > reference to call the frame's Close method. Or you could look into Dabo. This is one of those common needs that has been built into the framework. Any object on a form (a wx.Frame) can simple reference 'self.Form' to get a reference to the containing frame. Controls that are contained within other controls (such as inside panels or notebook pages) can always reference that container with 'self.Parent'. -- # p.d. From python at hope.cz Sat Jan 27 12:24:50 2007 From: python at hope.cz (Johny) Date: 27 Jan 2007 09:24:50 -0800 Subject: IP address of webserver Message-ID: <1169918690.690636.42690@a75g2000cwd.googlegroups.com> How can I find server's IP address? >From console I can use ping, for example: C:\RobotP\cgi-bin>ping www.google.com Pinging www.google.com [209.85.129.147] with 32 bytes of data: Reply from 209.85.129.147: bytes=32 time=30ms TTL=244 Reply from 209.85.129.147: bytes=32 time=30ms TTL=244 .. .. So I know that www.google.com has 209.85.129.147 IP address. But how can I find it directly from Python script? Thanks for help J. From cbfalconer at yahoo.com Tue Jan 9 15:16:44 2007 From: cbfalconer at yahoo.com (CBFalconer) Date: Tue, 09 Jan 2007 15:16:44 -0500 Subject: Internet Survey References: <1168354730.421464.159680@51g2000cwl.googlegroups.com> Message-ID: <45A3F82C.AF4769A2@yahoo.com> octabox at gmail.com wrote: > > I represent Octabox, an Internet Start-up developing a wide-scale > platform for Internet services. We are very interested to know > your thoughts on Internet productivity and how it might be > improved, and to that end we have set up a short survey at our > website - http://www.octabox.com/productivity_poll.php > We would very much appreciate if you would take a couple of > minutes to fill it up and influence our direction and empahsis. Failure to set follow-ups on excessively cross-posted article. Failure to give any incentive for response. Failure to give any assurance of privacy. Failure to monitor the various news-groups for suitability. -- Chuck F (cbfalconer at maineline dot net) Available for consulting/temporary embedded and systems. <http://cbfalconer.home.att.net> From nmm1 at cus.cam.ac.uk Thu Jan 11 11:58:19 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 11 Jan 2007 16:58:19 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <mailman.2408.1168248992.32031.python-list@python.org> <Xns98B269DCC12Fduncanbooth@127.0.0.1> <entr6s$ovo$1@news.albasani.net> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <eo38f1$6cu$1@gemini.csx.cam.ac.uk> <7x8xga215f.fsf@ruckus.brouhaha.com> <eo3bjj$cen$1@gemini.csx.cam.ac.uk> <eo52h9$kad$1@news.albasani.net> <1168516936.890690.235300@p59g2000hsd.googlegroups.com> <eo5gtj$6bs$1@news.albasani.net> Message-ID: <eo5qbb$i13$1@gemini.csx.cam.ac.uk> In article <eo5gtj$6bs$1 at news.albasani.net>, robert <no-spam at no-spam-no-spam.invalid> writes: |> |> Thus there are different levels of parallelization: |> |> 1 file/database based; multiple batch jobs |> 2 Message Passing, IPC, RPC, ... |> 3 Object Sharing |> 4 Sharing of global data space (Threads) |> 5 Local parallelism / Vector computing, MMX, 3DNow,... |> |> There are good reasons for all of these levels. Well, yes, but to call them "levels" is misleading, as they are closer to communication methods of a comparable level. |> > This does not mean that MPI is inherently slower than threads however, |> > as there are overhead associated with thread synchronization as well. |> |> level 2 communication is slower. Just for selected apps it won't matter a lot. That is false. It used to be true, but that was a long time ago. The reasons why what seems to be a more heavyweight mechanism (message passing) can be faster than an apparently lightweight one (data sharing) are both subtle and complicated. Regards, Nick Maclaren. From goofyheadedpunk at gmail.com Thu Jan 18 16:09:59 2007 From: goofyheadedpunk at gmail.com (Brian L. Troutwine) Date: 18 Jan 2007 13:09:59 -0800 Subject: distutils data file difficulties Message-ID: <1169154599.262622.268380@s34g2000cwa.googlegroups.com> I am new to the use of distutils and am having difficulty getting distutils recognize and install data files. Here are the relevant parts of my source directory: ExampleTree/ |-- __init__.py |-- data | |-- Example1.txt | |-- Example2.txt | `-- __init__.py |-- subPackage1 | |-- (...) `-- subPackage2 |-- (...) I would like to install Example1.txt and Example2.txt under data/ upon installation. I cannot seem to write a proper setup.py to accomplish this. Here are the relevant bits of my setup.py: #!/usr/bin/env python from distutils.core import setup setup(name="ExampleTree", (...), packages=['ExampleTree', ExampleTree/data', 'ExampleTree/subPackage1', ''ExampleTree/subPackage2'], package_dir={'data' : 'ExampleTree/data'}, package_data={'data': ['Example1.txt', 'Example2.txt']}, ) What am I doing incorrectly? From m.yanowitz at kearfott.com Mon Jan 22 10:48:48 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Mon, 22 Jan 2007 10:48:48 -0500 Subject: Is there a better way to implement this: Message-ID: <01aa01c73e3c$ce2416e0$0d7d12ac@kearfott.com> Hello: I wrote the code below (much irrelevant code removed). This doesn't quite work. What I wanted it to do was a) Execute function ftimed, which takes a function and a timeout in seconds. b) This will also execute function abort() as a thread. This function just runs for the specified number of seconds and returns. However, before it returns, throws an exception. c) If test() is still running when abort() is finished, ftimed() should catch the exception and return. It is catching the exception, however it continues running the function. Why does it continue and not return? What am I missing, or is there a better way to implement this (having ftimed() return when the abort-timer time is exceeded? import time, thread, sys thread_finished = "MAX RUN TIME EXCEEDED!" def abort (seconds): start_time = time.time() while ((time.time() - start_time) < seconds): time.sleep(0.01) print "script run time exceeded max_run_time of", seconds, "seconds." raise thread_finished return def test(): i = 0 while (True): time.sleep(1) print "HELLO", i i+=1 def ftimed (func, seconds): thread.start_new_thread (abort, (seconds,)) try: func() except thread_finished: print "Timeout" return ftimed (test, 30) print "Script finished" It presently generates the following output: $ python ./testthread.py HELLO 0 HELLO 1 HELLO 2 HELLO 3 HELLO 4 HELLO 5 HELLO 6 HELLO 7 HELLO 8 HELLO 9 HELLO 10 HELLO 11 HELLO 12 HELLO 13 HELLO 14 HELLO 15 HELLO 16 HELLO 17 HELLO 18 HELLO 19 HELLO 20 HELLO 21 HELLO 22 HELLO 23 HELLO 24 HELLO 25 HELLO 26 HELLO 27 HELLO 28 HELLO 29 script run time exceeded max_run_time of 30 seconds. Unhandled exception in thread started by <function abort at 0x009CEF30> Traceback (most recent call last): File "./testthread.py", line 10, in abort raise thread_finished MAX RUN TIME EXCEEDED! HELLO 30 HELLO 31 HELLO 32 .... Thanks in advance: Michael Yanowitz From emin.shopper at gmail.com Thu Jan 4 15:26:00 2007 From: emin.shopper at gmail.com (Emin) Date: 4 Jan 2007 12:26:00 -0800 Subject: bug in copy.deepcopy or in getattr or in my understanding? Message-ID: <1167942359.246311.80700@s34g2000cwa.googlegroups.com> Dear experts, I got some unexpected behavior in getattr and copy.deepcopy (see transcript below). I'm not sure if this is actually a bug in copy.deepcopy or if I'm doing something too magical with getattr. Comments would be appreciated. Thanks, -Emin ######### Transcript follows ################## Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> # THE FOLLOWING BREAKS >>> class a: ... def foo(self): ... print 'hi' ... >>> class b(a): ... def __init__(self): ... self.y = getattr(self,'foo') ... >>> c = b() >>> import copy >>> copy.deepcopy(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\Python25\lib\copy.py", line 162, in deepcopy y = copier(x, memo) File "c:\Python25\lib\copy.py", line 291, in _deepcopy_inst state = deepcopy(state, memo) File "c:\Python25\lib\copy.py", line 162, in deepcopy y = copier(x, memo) File "c:\Python25\lib\copy.py", line 254, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "c:\Python25\lib\copy.py", line 189, in deepcopy y = _reconstruct(x, rv, 1, memo) File "c:\Python25\lib\copy.py", line 322, in _reconstruct y = callable(*args) File "c:\Python25\lib\copy_reg.py", line 92, in __newobj__ return cls.__new__(cls, *args) TypeError: instancemethod expected at least 2 arguments, got 0 >>> # THE FOLLOWING WORKS >>> class b(a): ... def __init__(self): ... self.x = self.__class__.__bases__[0].__dict__['foo'] ... >>> c=b() >>> copy.deepcopy(c) <__main__.b instance at 0x00EADE18> From sjdevnull at yahoo.com Thu Jan 25 00:47:27 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 24 Jan 2007 21:47:27 -0800 Subject: ctypes: Setting callback functions in C libraries Message-ID: <1169704047.486695.157820@l53g2000cwa.googlegroups.com> Hey, I'm trying to wrap GNU readline with ctypes (the Python readline library doesn't support the callback interface), but I can't figure out how to set values to a variable inside the library. This is Python 2.5 on Linux. Here's what I have so far--if you comment out the memmove call (3 lines) it works as expected: # START #!/usr/local/bin/python2.5 import ctypes ctypes.cdll.LoadLibrary("libcurses.so")#, mode=ctypes.RTLD_GLOBAL) ctypes.CDLL("libcurses.so", mode=ctypes.RTLD_GLOBAL) ctypes.cdll.LoadLibrary("libreadline.so") readline = ctypes.CDLL("libreadline.so") RL_COMPLETION_FUNC_T = ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_char_p), ctypes.c_char_p, ctypes.c_int, ctypes.c_int) RL_LINE_BUFFER = ctypes.c_char_p.in_dll(readline, "rl_line_buffer") RL_ATTEMPTED_COMPLETION_FUNCTION = RL_COMPLETION_FUNC_T.in_dll(readline, "rl_attempted_completion_function") def our_complete(text, start, end): print "Test", text, start, end rv = None arrtype = ctypes.c_char_p*4 globals()["rv"] = arrtype("hello", "hatpin", "hammer", None) globals()["crv"]=ctypes.cast(rv, ctypes.POINTER(ctypes.c_char_p)) return rv ourfunc = RL_COMPLETION_FUNC_T(our_complete) _readline = readline.readline _readline.argtypes = [ctypes.c_char_p] _readline.restype = ctypes.c_char_p ctypes.memmove(ctypes.addressof(RL_ATTEMPTED_COMPLETION_FUNCTION), ctypes.addressof(ourfunc), 4) line = _readline("Input: ") print "INPUT was: ", line #END I need to assign ourfunc to RL_ATTEMPTED_COMPLETION_FUNCTION, but obviously simple assignment rebinds the name rather than assigning it to the C variable. Using ctypes.memmove to overwrite it(as I have here) will run the function but segfault when ourfunc goes to return (poking around with the debugger shows it's dying in ctypes' callbacks.c at line 216, "keep = setfunc(mem, result, 0);" because setfunc is NULL). I'm not entirely sure that's not because of some error in the prototyping or restype setting rather than as a result of memmove, but the memmove seems sketchy enough (only sets the function pointer itself presumably, not anything that ctypes wrappers need) that I'm looking for a better way to do it. As it is, returning rv directly or simply returning None causes the same segfault. Any ideas? Thanks very much for your time! From gagsl-py at yahoo.com.ar Fri Jan 5 15:49:48 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 17:49:48 -0300 Subject: strange for loop construct In-Reply-To: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> Message-ID: <7.0.1.0.0.20070105174716.03dee1e0@yahoo.com.ar> At Friday 5/1/2007 17:39, Sardaukary at gmail.com wrote: >wordfreq = [wordlist.count(p) for p in wordlist] > >I would expect > >for p in wordlist: > wordfreq.append(wordlist.count(p)) > > >I didn't know you could have an expression in the same line. That's known as a "list comprehension" and is roughly equivalent to your code. Section 5 of the tutorial covers them. http://docs.python.org/tut/node7.html -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From skip at pobox.com Wed Jan 24 07:12:40 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 Jan 2007 06:12:40 -0600 Subject: easy_install pylons failure - www.myghty.org unavailable In-Reply-To: <ep6llk$nn1$1@sea.gmane.org> References: <17846.54389.27457.383902@montanaro.dyndns.org> <ep6la3$mrh$1@sea.gmane.org> <ep6llk$nn1$1@sea.gmane.org> Message-ID: <17847.19768.794607.756945@montanaro.dyndns.org> Robert, Thanks, I passed the contents of this thread along to distutils-sig. Hopefully the list moderator is awake, as I'm not subscribed there... ;-) Skip From ajdeshpande at gmail.com Wed Jan 31 12:00:46 2007 From: ajdeshpande at gmail.com (Analog Kid) Date: Wed, 31 Jan 2007 22:30:46 +0530 Subject: Python module for the IPod shuffle ... Message-ID: <4ccf86300701310900g2b642847s5d0dab31857f42a6@mail.gmail.com> Hi all: Im looking for a python module thatll let me do simple reads/writes from and to an iPod shuffle similar to iTunes ... I read about the gPod module ... but Im not sure whether it will work in Windows ... Any help is greatly appreciated. Thanks in advance ... -Ajay -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070131/ed8f04c3/attachment.html> From paallen at attglobal.net Mon Jan 8 12:22:32 2007 From: paallen at attglobal.net (PAllen) Date: 8 Jan 2007 09:22:32 -0800 Subject: A Good Intro to wxpython/PostgreSQL Applications? Message-ID: <1168276952.498242.78120@v33g2000cwv.googlegroups.com> Hi all, I am trying to get rid of a few of my old MS Access applications and move them to PostgreSQL and Python/wxpython. Does anyone have any suggestions on the easiest way to learn to program small database applications with python & wxpython? Does anyone have a few small examples at least? I will mainly need forms with/without subforms for viewing and inserting data into the database. Nothing too complicated to get started. thanks, Phillip Allen From Roka100 at gmail.com Wed Jan 31 23:59:59 2007 From: Roka100 at gmail.com (Jia Lu) Date: 31 Jan 2007 20:59:59 -0800 Subject: Can I import a file without file extension .py? Message-ID: <1170305999.001998.251390@m58g2000cwm.googlegroups.com> Hi all I wonder if I can import a file with other file extensions ? Can I do that only with python? Thank you Jia Lu From aspmanualator_1234567890 at yahoo.com Wed Jan 10 01:16:48 2007 From: aspmanualator_1234567890 at yahoo.com (Asper Faner) Date: 9 Jan 2007 22:16:48 -0800 Subject: "tkinter module not found" please help In-Reply-To: <1168400177.167870.61900@i56g2000hsf.googlegroups.com> References: <1168400177.167870.61900@i56g2000hsf.googlegroups.com> Message-ID: <1168409808.203690.186240@o58g2000hsb.googlegroups.com> notsonic... at yahoo.com wrote: > I'm trying to install python2.5 on my computer(os Fedora 5). My problem > is that I'm unable to get the tkinter module loaded into python. I've > tried the solution here:"wiki.python.org/moin/TkInter" but am unsure as > how to modify my setup.py script. I have installed the latest versions > of tcl/tk (8.4.14) twice as well as installing python again. Everything > is installed in the default location but still no luck. Does anyone > have any ideas? Thank you. Compatibility is needed, Fed5 doesn't go with Py2.5, you try reinstalling by yummie or from add&remove From paul at boddie.org.uk Fri Jan 26 13:53:16 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 26 Jan 2007 10:53:16 -0800 Subject: Handling empty form fields in CGI In-Reply-To: <mailman.3207.1169834026.32031.python-list@python.org> References: <mailman.3207.1169834026.32031.python-list@python.org> Message-ID: <1169837596.200333.94360@s48g2000cws.googlegroups.com> Christopher Mocock wrote: > > Bit of a python newbie so need a little help with a CGI script I'm > trying to write. I've got it working fine as long as the fields of the > form are filled in correctly, however I need to be able to accept blank > entries. Therefore I want to convert any empty entries to an empty string. [...] > form = cgi.FieldStorage() Try replacing this with... form = cgi.FieldStorage(keep_blank_values=1) Paul From nospam at domain.tld Thu Jan 25 01:50:06 2007 From: nospam at domain.tld (Stephan Kuhagen) Date: Thu, 25 Jan 2007 07:50:06 +0100 Subject: Python does not play well with others References: <NXyth.51860$wc5.6792@newssvr25.news.prodigy.net> <xqxirex3psq.fsf@cola3.ca.boeing.com> Message-ID: <ep9juv$a77$1@kohl.informatik.uni-bremen.de> Harry George wrote: > Perl - excellent modules and bindings for just about everything you ... > Java - a world of its own. They reinvent the wheel instead of linking ... > PHP - are we talking web scripts or serious programs? Are you doing ... > C - the portable assembler. Solid, trusted, tunable performance, ... > C++ - objects tacked onto C; but that didn't work so invent a whole ... > Python - it just works. Same scripts run on every platform. The world has become very small these days... Although I do not agree to the OP, because Python works for me very good on different platforms (i.e. different Versions of Windows, Linux and Mac OS X), there are some other old fellows around, which are very good for cross platform programming. C and C++ are definitely *not* one of them, I would say. True, you can write cross platform with them, but... I'm missing especially some of the older cross platform languages in your list (I would set Tcl at the top of the list, but Lisp and others will appear in such a list also), which have grown and became mature over the years. Most cross platform problems and others issues have been fixed and really worked out in them. New kids on the block may be more dynamic (Python really is), but they can learn much from the old guys. Sometimes one should have a look and learn from still good working ancestors... Regards Stephan From bdesth.quelquechose at free.quelquepart.fr Thu Jan 4 05:44:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Jan 2007 11:44:16 +0100 Subject: array of class / code optimization In-Reply-To: <AOPmh.83$9v1.124@nntpserver.swip.net> References: <mailman.2221.1167763760.32031.python-list@python.org> <AOPmh.83$9v1.124@nntpserver.swip.net> Message-ID: <459cd45e$0$320$426a34cc@news.free.fr> mm a ?crit : > > Yes, it was the (), equivalent to thiks like new() create new object > from class xy. Yeps. In Python there's no 'new' operator. Instead, classes are themselves 'callable' objects, acting as instance factory. It's very handy since it let's you replace a class with a factory function (or vice-versa) without impacting client code. >> s1.append(Word) > > s1.append(Word()) > > But I was looking for a "struct" equivalent like in c/c++. You can use a dict or a class. > And/or "union". I can't find it. What is your real use case ? Direct translation from one language to another usually leads to code that's both non-idiomatic and inefficient. IOW, don't try to write C++ in Python. > Maybe you know a source (URL) "Python for c/c++ programmers" or things > like that. Not really, but quite a lot of Python programmers come from the C++ world. FWIW, I'd say that the official Python tutorial should be enough to get you started. Then, and if you're at ease with OO, you may want to have a look at more advanced stuff like special methods and attributes, decriptors and metaclasses (here again documented on python.org). From chizzua at gmail.com Fri Jan 5 15:21:57 2007 From: chizzua at gmail.com (jbchua) Date: 5 Jan 2007 12:21:57 -0800 Subject: Learning to program in Python Message-ID: <1168028517.005902.172880@11g2000cwr.googlegroups.com> Hello everybody. I am an Electrical Engineering major and have dabbled in several languages such as Python, C, and Java in my spare time because of my interest in programming. However, I have not done any practical programming because I have no idea where to get started. I taught myself these languages basically by e-tutorials and books. This makes me feel as if I don't really know how to implement these languages. Does anybody have any advice on where to start applying my limited knowledge practically in order to advance my learning? From bthom at cs.hmc.edu Thu Jan 11 16:33:59 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Thu, 11 Jan 2007 13:33:59 -0800 Subject: Pythonic A*-Algorithm In-Reply-To: <200701112201.37129.w.richert@gmx.net> References: <200701112201.37129.w.richert@gmx.net> Message-ID: <77C074CD-2F46-482E-A6BE-29B3A4297374@cs.hmc.edu> Willi, Maybe you could use something from the Python AIMA code? http:// aima.cs.berkeley.edu/code.html On Jan 11, 2007, at 1:01 PM, Willi Richert wrote: > Hi, > > I'm looking for an A* implementation in Python (at least some > wrapper around a > C lib). So far I've only found http://arainyday.se/projects/python/ > AStar/ > which looks not so promising. > > http://wiki.python.org/moin/PythonGraphApi lists all major > available graph > libraries in Python, hoping to find a path to some standard Python > graph > library (as DBAPI). But none of them seems to have a decent A*- > implementation > (at least with Fibonacci-heap, as pqueue is supposed to be). > > I know I could implement it myself as it is not that complicated, > but I would > rather like to align my project to some already existing and well > established > graph library containing A*. > > Thanks, > wr > -- > http://mail.python.org/mailman/listinfo/python-list From deets at nospam.web.de Fri Jan 5 08:58:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Jan 2007 14:58:11 +0100 Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> Message-ID: <5073rjF1ek2b1U1@mid.uni-berlin.de> king kikapu wrote: >> Python code is normally deployed as straight source code. > > But isn't this a problem of its own ?? I mean, many people do not feel > good if the know that their source code is lying around on other > machines... This has been discussed a bazillion times on this list - the summary is (at least from my POV): - it is possible to decompyle python pretty easy. So, spare yourself the hassle just distributing only the pyc - it is easy enough to hack even C-written apps, if anything is _worth_ being hacked, it will be hacked - 99% of all code isn't worth being hacked or ripped. Really. Even though the result of cobbling together lots of unimaginative code might be impressive, there are only very few areas of coding (like e.g. sophisticated compression algorithms and the like) that are worth ripping - the rest is bound to be runnable in one app only anyway, as it is coupled closely - if you have something you really, really, really need to be as secure as possible, go use a remote service - otherwise, it _will_ be compromised. Diez From richfahey at gmail.com Thu Jan 11 14:10:37 2007 From: richfahey at gmail.com (Rich) Date: 11 Jan 2007 11:10:37 -0800 Subject: passing a variable to an external program Message-ID: <1168542633.290682.267570@77g2000hsv.googlegroups.com> I want to run an external program using os.system() but I want to include a variable in the middle of the command line. An example of the type of thing I want to be able to do: pathname = os.path.dirname(sys.argv[0]) os.system('cscript /nologo ' + pathname + '\test.vbs') When I run this, everything after pathname + seems to be ignored. Is this just incorrect syntax or am I trying to do something fundamentally wrong? Is there a better way to do something like this? I'm trying to move from perl to python and this is my first attempt at python. From jwaixs at gmail.com Thu Jan 11 14:35:30 2007 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Thu, 11 Jan 2007 19:35:30 +0000 Subject: Rational Numbers Message-ID: <cb63d1e10701111135g528837b1wce8b2ff43452ba85@mail.gmail.com> Hello, When I was programming in a mathematical project I began to wonder if python supports rational numbers[1]. In a language like magma[2] it's not such a problem. Does python supports something simular? Greetings, Noud Aldenhoven -- <:3 )~ [1] http://en.wikipedia.org/wiki/Rational_number [2] http://www.math.uiuc.edu/Software/magma/text283.html -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20070111/1c9a5982/attachment.html> From hrvoje.niksic at avl.com Tue Jan 23 10:36:59 2007 From: hrvoje.niksic at avl.com (Hrvoje =?UTF-8?Q?Nik=C5=A1i=C4=87?=) Date: Tue, 23 Jan 2007 16:36:59 +0100 Subject: Py_DECREF after an exception Message-ID: <1169566619.5169.67.camel@localhost> I'm wondering what happens with the exception info during object cleanup immediately after an exception is thrown. Consider this code: PyObject *args = PyBuild_Value("(O(O){})", name, parent); if (!args) return NULL; PyObject *val = some_python_func(x, args, NULL); Py_DECREF(args); if (!val) return NULL; The idea is to propagate the exception possibly raised by some_python_func and at the same time avoid leaking memory. But Py_DECREF can cause arbitrary Python code to get executed, including the code that eventually ends up calling PyErr_Clear when it wants to ignore some unrelated exception. This could cause exception information to be forgotten. Is there a way around this, or is there a reason why this is not a problem in practice? From codecraig at gmail.com Wed Jan 24 12:21:04 2007 From: codecraig at gmail.com (abcd) Date: 24 Jan 2007 09:21:04 -0800 Subject: Thoughts on using isinstance In-Reply-To: <pan.2007.01.24.16.49.21.555688@gmx.net> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <mailman.3077.1169645738.32031.python-list@python.org> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <mailman.3087.1169652310.32031.python-list@python.org> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> <pan.2007.01.24.16.49.21.555688@gmx.net> Message-ID: <1169659264.605545.211000@s48g2000cws.googlegroups.com> >Yes because usually you don't expect a list or dictionary but some object > that *acts* like a list or dictionary. Or you even expect just some > aspects of the type's behavior. For example that it is something you can > iterate over. > > Ciao, > Marc 'BlackJack' Rintsch good point. is there place that documents what methods/attrs I should check for on an object? for example, if its a list that I expect I should verify the object that is passed in has a ??? function? etc. thanks. From kylotan at gmail.com Tue Jan 2 06:08:03 2007 From: kylotan at gmail.com (Ben Sizer) Date: 2 Jan 2007 03:08:03 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <etvgp25hjdju857j8o4spsj2jictceht6j@4ax.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <1167543262.361311.123700@v33g2000cwv.googlegroups.com> <etvgp25hjdju857j8o4spsj2jictceht6j@4ax.com> Message-ID: <1167736083.756075.273450@s34g2000cwa.googlegroups.com> Tom Plunket wrote: > vbgunz wrote: > > Some if not most python documentation assumes Python is on the path... > > Really? I must live in different places in the docs, but I can't recall > encountering any such documentation. I have posted a few examples above: "Installing Python Modules" (http://python.org/doc/2.2.3/inst/inst.html) is a key example. 3rd party packages often expect you to type "python setup.py install". Setuptools/easyinstall will give you an 'easy_install' script, but then notes that you have to manually fix up the PATH yourself. > Users who want it in their paths are certainly capable of putting it > there. By that logic, users who want Python are probably capable of unzipping the archive and putting it somewhere semi-suitable. So why provide an installer? If you're going to provide an installer, it should do the whole job, and get Python in a state that is reasonably consistent across all platforms, where practical. Adding to the PATH variable isn't impractical. > I am in the camp that detests apps that automatically install > tons of crap everywhere without prompts. Why use hyperbole here? Is 13 or 14 bytes optionally added to a single environment variable "tons of crap"? And did anybody insist that the installer would have no prompts? > Certainly, though, the > suggestion that one pane in the installer offer to put it in the path > would leave the default as it is today ("don't edit PATH"), though, > right? Doesn't make a whole lot of sense to add a new option and > default it to something completely different from the old behavior, does > it? I have no problem with something being configurable, but I do have a problem with Windows users being forced to jump through unnecessary hoops that Unix and MacOS users don't have to endure. And I think the default should be to edit the PATH and allow you to explicitly disallow this: changing from the current behaviour is the right thing to do because the current behaviour is wrong, in terms of cross-platform compatibility and usability. -- Ben Sizer From manouchk at gmail.com Fri Jan 19 12:07:23 2007 From: manouchk at gmail.com (manouchk) Date: 19 Jan 2007 09:07:23 -0800 Subject: nsis and command-line argument In-Reply-To: <1169138095.499650.8530@m58g2000cwm.googlegroups.com> References: <1169138095.499650.8530@m58g2000cwm.googlegroups.com> Message-ID: <1169226443.365409.103280@v45g2000cwv.googlegroups.com> manouchk wrote: > Hi, > > is there a standart way to prepare a single exe with nsis that pass the > command line to an exe created by py2exe on windows? > > py2exe allows to prepare an exe that get the command-line but needs > some lib file so that it is not so elegant to ditribute. I tried a > simple setup.nsis script to prepare a single file exe with works fine > except that it does get the command-line. > > Is there a way do get the command line with the setup.nsis script? > or any other simple method ? Answering myself, well with NSIS it is not supported as written there : http://www.py2exe.org/index.cgi/SingleFileExecutable I'm looking for the py2exe option that allows that, I guess it could be --bundle 1. It does not seem to be documented but I will try that. From george.sakkis at gmail.com Sun Jan 21 16:32:19 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Jan 2007 13:32:19 -0800 Subject: mmap caching References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <slrner7h27.d8g.nick@irishsea.home.craig-wood.com> Message-ID: <1169415139.515834.233700@a75g2000cwd.googlegroups.com> Nick Craig-Wood wrote: > George Sakkis <george.sakkis at gmail.com> wrote: > > I've been trying to track down a memory leak (which I initially > > attributed erroneously to numpy) and it turns out to be caused by a > > memory mapped file. It seems that mmap caches without limit the chunks > > it reads, as the memory usage grows to several hundreds MBs according > > to the Windows task manager before it dies with a MemoryError. I'm > > positive that these chunks are not referenced anywhere else; in fact if > > I change the mmap object to a normal file, memory usage remains > > constant. The documentation of mmap doesn't mention anything about > > this. Can the caching strategy be modified at the user level ? > > I'm not familiar with mmap() on windows, but assuming it works the > same way as unix... > > The point of mmap() is to map files into memory. It is completely up > to the OS to bring pages into memory for you to read / write to, and > completely up to the OS to get rid of them again. > > What you would expect is that the file is demand paged into memory as > you access bits of it. These pages will remain in memory until the OS > feels some memory pressure when the pages will be written out if dirty > and then dropped. > > The OS will try to keep hold of pages as long as possible just in case > you need them again. The pages dropped should be the least recently > used pages. > > I wouldn't have expected a MemoryError though... > > Did you do mmap.flush() after writing? The file is written once and then opened as read-only, there's no flushing. So if caching is completely up to the OS, I take it that my options are either (1) modify my algorithms so that they work in fixed-size batches instead of arbitrarily long sequences or (2) implement my own memory-mapping scheme to fit my algorithms. I guess (1) would be the less trouble overall, or is there a way to give a hint to the OS on how large cache can it use ? George From martin at v.loewis.de Tue Jan 9 15:46:15 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Jan 2007 21:46:15 +0100 Subject: distutils and ctypes In-Reply-To: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> Message-ID: <45A3FF17.2070509@v.loewis.de> jtravs at gmail.com schrieb: > I suspect that I'm doing something stupid, I would like some other > opinions though. > I'm getting started with ctypes and am trying to use distutils to help > build my module. At the moment I simply want distutils to build a > shared c library (not a python extension!). Under linux, the following > works, under windows xp id doesn't (which I guess is obvious, but the > linux success lead me on). Not sure it's stupid, but I wonder why you want to use ctypes. What's wrong with extension modules? Regards, Martin From bdesth.quelquechose at free.quelquepart.fr Wed Jan 24 15:15:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Jan 2007 21:15:52 +0100 Subject: Thoughts on using isinstance In-Reply-To: <1169656371.689791.216360@v33g2000cwv.googlegroups.com> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <mailman.3077.1169645738.32031.python-list@python.org> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <mailman.3087.1169652310.32031.python-list@python.org> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> Message-ID: <45b7b7ba$0$391$426a74cc@news.free.fr> abcd a ?crit : > Well my example function was simply taking a string and printing, but > most of my cases would be expecting a list, dictionary or some other > custom object. Still propose not to validate the type of data being > passed in? Yes - unless you have a *very* compelling reason to do otherwise. From webb.sprague at gmail.com Thu Jan 4 20:01:03 2007 From: webb.sprague at gmail.com (_) Date: 4 Jan 2007 17:01:03 -0800 Subject: Turn off line wrap for lists? Message-ID: <1167958863.538291.60820@s34g2000cwa.googlegroups.com> (I did google for this, I promise) How do I get python NOT to insert newlines into string representations of lists when I do something like this: strCollector += "%s" % (['a', 'list', 'with', 'lots', 'of', 'elements'] * 100) ? I would like to set a default never to do this, if possible. (Never mix formatting with display, or tequila with bourbon -- bad, bad, bad!) FYI I am using this to export data into tab delimited format, so the lines can be as long as they need to be, but a newline means a new record. FYI (2), this is in web application too, so I am afraid I might have to set the default in a bunch of different modules. TIA From rschroev_nospam_ml at fastmail.fm Wed Jan 3 18:45:11 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 03 Jan 2007 23:45:11 GMT Subject: Unsubscribing from the list In-Reply-To: <mailman.2253.1167856980.32031.python-list@python.org> References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <ene064$bm5$1@sea.gmane.org> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> <enghj3$qhf$1@sea.gmane.org> <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> <engs22$6u3$1@sea.gmane.org> <880dece00701031033o151cbe76h92a5a5adde51db90@mail.gmail.com> <mailman.2253.1167856980.32031.python-list@python.org> Message-ID: <beXmh.271710$bW2.5771379@phobos.telenet-ops.be> Robert Kern schreef: > Dotan Cohen wrote: >> On 03/01/07, Fredrik Lundh <fredrik at pythonware.com> wrote: >>> Robert provided *detailed* instructions, which you ignored. I quoted >>> the same instructions in my reply, which you also ignored. the sentence >>> after the one where you stopped reading also tells you what to do. one >>> might suspect that you don't really want to unsubscribe from this list... >> I didn't ignore his instructions. I went to the page, and found what I >> was looking for. I told him thank you, and explained why I didn't find >> it the first time. > > He misunderstood you (as I nearly did, too). The way you phrased "decided that > there was no futher interest on the page for me" is somewhat ambiguous: it can > seem like it refers to the second time, not the first. I almost misunderstood too. Dotan is not the only one to be somewhat confusing though: I've always thought that the way Mailman formulates that page is confusing. It always seems to me that "(The subcribers list is only available to the list administrator.)" seems to cover the whole "Python-list Subscribers" section instead of just the first part of it. I think this layout would be much clearer (although this is actually a Mailman issue, not a Python issue): Python-list Subscribers Unsubscribe: To unsubscribe from Python-list, get a password reminder, or change your subscription options enter your subscription email address: _______ [Unsubscribe or edit options] If you leave the field blank, you will be prompted for your email address Subscriber list (only available to the list administrator): Enter your admin address and password to visit the subscribers list: Admin address: _______ Password: _______ [Visit Subscriber List[ -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From no-spam at no-spam-no-spam.invalid Thu Jan 18 04:13:17 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 18 Jan 2007 10:13:17 +0100 Subject: Making a simple script standalone In-Reply-To: <mailman.2856.1169075613.32031.python-list@python.org> References: <5d1084-5j7.ln1@whisper.very.softly> <mailman.2820.1169032834.32031.python-list@python.org> <ek8284-od9.ln1@whisper.very.softly> <mailman.2856.1169075613.32031.python-list@python.org> Message-ID: <eondm3$ouo$1@news.albasani.net> Gabriel Genellina wrote: > At Wednesday 17/1/2007 16:05, Rikishi 42 wrote: > >> >>What I want to do is to compile/bundle/prepare/whatever_term a simple >> >>Python script for deployment on a Windows machine. Installing Python >> >>itself on that machine, is not an option. Ideally I would like to >> obtain >> >>a single executable file, but a script+runtime is acceptable. >> > >> > distutils + py2exe >> >> Tried that, just after asking here. >> A bit messy (poor docs) and a very bloated result. > > Consider that, at a bare minimum, you need to include python25.dll wich > is rather large, and transitive module imports can lead to a large > library.zip too. > Different "bundlers" may be more or less convenient, have more or less > documentation, easier or harder to use, but they all make comparable > file sizes; no one is so dumb to include all the scripts reachable along > the PYTHONPATH, and on the other hand, if it included too few files your > script might fail when it can't import a needed module. > See http://mail.python.org/pipermail/python-list/2005-August/336851.html > for a related issue. > If you're going to try different alternatives, posting your findings at > the end would be a good thing. > stay with py23 for "a script" (and more) and make <700kB independent distros - UPX and 7zip involved: http://groups.google.com/group/comp.lang.python/msg/edf469a1b3dc3802 From fccoelho at gmail.com Wed Jan 24 15:57:03 2007 From: fccoelho at gmail.com (Flavio) Date: 24 Jan 2007 12:57:03 -0800 Subject: raise UnicodeError, "label too long" Message-ID: <1169672223.231030.262610@l53g2000cwa.googlegroups.com> Hi I am havin a problem with urllib2.urlopen. I get this error when I try to pass a unicode to it. raise UnicodeError, "label too long" is this problem avoidable? no browser or programs such as wget seem to have a problem with these strings. From jorge.vargas at gmail.com Fri Jan 5 16:06:18 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Fri, 5 Jan 2007 17:06:18 -0400 Subject: MySQLdb windows binaries for Python 2.5?? Yes, but from a World of Warcraft guild. In-Reply-To: <1166144355.616642.127080@n67g2000cwd.googlegroups.com> References: <1162408100.985370.148650@m7g2000cwm.googlegroups.com> <1163238145.257490.144410@b28g2000cwb.googlegroups.com> <mailman.2093.1163244341.11739.python-list@python.org> <Fgkgh.9311$hI.6215@newssvr11.news.prodigy.net> <Ulmgh.70$u%4.58@newsfe04.lga> <1166144355.616642.127080@n67g2000cwd.googlegroups.com> Message-ID: <32822fe60701051306o2a4d91beycc919d1d21d6e495@mail.gmail.com> On 14 Dec 2006 16:59:15 -0800, Fuzzyman <fuzzyman at gmail.com> wrote: > > johnf wrote: > > >> > > >> If you search the Help Forum of the MySQLdb project on SourceForge, you > > >> will find a couple of people who have successfully built MySQLdb on > > >> Windows for 2.5, and are willing to share their installers. > > >> That's how I got my binaries. well it seems noone has talk to Andy directly I build the one for 1.2.1_p2 for python2.4 ones it was done all I had to do is email Andy and he posted it without problems the biggest issue here is that building that driver in windows is a pain, you need mysql headers, python headers and microsoft compilers a total of around 2Gb, plus some bug I found that ended up being an error in between the setup.py file and windows commandline. also windows lacks the mysql-config tool which means you need to find out a lot of flags which on *NIX are fill in automagically. ahh did I mention you need to patch distutils to work with the "free windows" compiler because the official windows python builds agains the non-free MS compiler. > > > This, apparently, is the extent of current Python support for MySQL. > > > Want to install that executable, as root, on your production machines? > > > > > > This is embarassing for the Python community. Perl and PHP come > > > with MySQL support built in. Python is out to lunch on this. > > > > > I couldn't disagree more. That fact that no Database drivers are built-in > > makes Python stronger - allowing Python to access any Data Engine that > > supports DBI 2.0. Of course I'm not including pickle in my assessment. > > actually in this case I disagree having this driver as buildin will take much of the pain out of any user who tries to compile this driver, it will also help in standarizing the drivers for example in postgre there is more then one, I think we will be better off with just one driver, that is one DBI2.0 driver, there are some experiments outthere which make it more "pythonic" which shouldn't be excluded. From tactics40 at gmail.com Mon Jan 22 19:30:44 2007 From: tactics40 at gmail.com (tac-tics) Date: 22 Jan 2007 16:30:44 -0800 Subject: arrow keys don't work In-Reply-To: <1169511711.594390.167630@11g2000cwr.googlegroups.com> References: <1169506381.452422.179070@11g2000cwr.googlegroups.com> <pan.2007.01.23.00.14.29.144841@REMOVEME.cybersource.com.au> <1169511711.594390.167630@11g2000cwr.googlegroups.com> Message-ID: <1169512244.036184.175650@38g2000cwa.googlegroups.com> It looks like I got readline working. Thanks for the help! From pink at odahoda.de Wed Jan 31 08:02:33 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Wed, 31 Jan 2007 14:02:33 +0100 Subject: marshal.loads ValueError References: <1170247461.799295.227550@a75g2000cwd.googlegroups.com> Message-ID: <epq41g$ne6$1@online.de> Hello, abcd wrote: > I have the following code which is sent over the wire as a string... > > from time import time > class Foo: > def go(self): > print "Time:", time() > > > I get this code and store it as, "data" > > data = receivePythonSource() > > Then I try... > > exec marshal.loads(data) in my_module.__dict__ > > However I get an error saying: > ValueError: invalid literal for __float__: om time import time > class Foo: > def go(self): > > ....almost like when I try to marshal and exec it misses the first two > characters, "fr" ...any ideas? marshal is used to (de)serialize python objects from/to strings. marshal.loads() tries to deserialize an encoded string back into a python object - which does not make sense here. What you probably want is: exec data in my_module.__dict__ HTH -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From mark.m.mcmahon at gmail.com Thu Jan 18 17:38:15 2007 From: mark.m.mcmahon at gmail.com (Mark) Date: 18 Jan 2007 14:38:15 -0800 Subject: How to write code to get focuse the application which is open from server References: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> <45a0dae2$0$8948$4c368faf@roadrunner.com> <1168837895.073936.270330@11g2000cwr.googlegroups.com> <m%Oqh.10311$pQ3.45@newsread4.news.pas.earthlink.net> <1168887206.135633.182600@s34g2000cwa.googlegroups.com> Message-ID: <1169159895.511475.301830@v45g2000cwv.googlegroups.com> Hi, There are better places to find me then on comp.lang.python (just too much traffic for me) pywinauto forums: http://forums.openqa.org/forum.jspa?forumID=15 or subscribe pywinauto mailing list: https://lists.sourceforge.net/lists/listinfo/pywinauto-users vithi wrote: <SNIP> > MatchError: Could not find 'Print' in '['', u'Transparent Windows > Client0', u'Transparent Windows Client2', u'Transparent Windows > Client1', u'Print - \\\\Remote', u'Transparent Windows Client', u'Print > - \\\\RemoteTransparent Windows Client']' > > This is the code > import sys > import time > import application > app = application.Application() > qi=app.window_(title_re = ".*ArcView.*") > time.sleep(2) > qi.TypeKeys("%FP") > time.sleep(2) > > app.Print.Ok.CloseClick() > > My guess is that problem above is that teh title of the window is u"Print - \\Remote", and "Print" is not enough information for pywinauto to go on. I suggest you replace the last line with one of the following... app.PrintRemote.Ok.CloseClick() app.window_(title_re = "Print - .*").Ok.CloseClick() Someone also was wondering why they do not have to call Application.Start() or Application.Connect() explicitly - that is because the first call to app.window_() will initialize the application appropriately. The reason for this is that most usages ended up being a) Connect to a window with specific title, then use that window in the next line - so I was trying to avoid duplication. Thanks Mark From mail at microcorp.co.za Fri Jan 12 00:09:44 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Jan 2007 07:09:44 +0200 Subject: Urgent Openings with the World's Leading Software Company !!! References: <1168499359.596195.286240@77g2000hsv.googlegroups.com> Message-ID: <005501c73607$e0246120$03000080@hendrik> "Software Hiring" <vamsi.hr.rec at gmail.com> wrote: > If you're interested in relocating to India for such a good > opportunity and be a part of the World's Best Software Company and if > you have good skill sets in: > > C, C++, C#, Java (for .Net Platform or Visual Studio) > > OR > > C, C++, Java, Product Development (for MS RFID Infrastructure > PathFinder - Adapters) > > OR > > C, C++, driver or kernel, Linux or Unix (for Windows Serviceability) > not much to do with python.... *closes eyes, and imagines the sing-song accent of the Indians contrasting with his guttural Afrikaans accent * *shudders* I think I will give this one a miss - it would be worse than relocating to Wales... - Hendrik From skip at pobox.com Mon Jan 15 10:13:17 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 15 Jan 2007 09:13:17 -0600 Subject: How naive is Python? In-Reply-To: <1168848408.785931.285160@q2g2000cwa.googlegroups.com> References: <huCqh.1309$O02.170@newssvr11.news.prodigy.net> <mailman.2724.1168834095.32031.python-list@python.org> <1168848408.785931.285160@q2g2000cwa.googlegroups.com> Message-ID: <17835.39437.115750.617750@montanaro.dyndns.org> John> Sorry, Skip, but I find that very hard to believe. The foo() John> function would take quadratic time if it were merely adding on John> pieces of constant size -- however len(str(i)) is not a constant, John> it is O(log10(i)), so the time should be John> super-quadratic. Sorry, I should have pointed out that I'm using the latest version of Python. I believe += for strings has been optimized to simply extend s when there is only a single reference to it. Skip From hg at nospam.org Fri Jan 5 04:57:28 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 10:57:28 +0100 Subject: importing / loading a module / class dynamically References: <o1vnh.281$rv1.88@newsfe21.lga> <mailman.2329.1168015250.32031.python-list@python.org> Message-ID: <Qrvnh.22242$Dy2.4262@newsfe20.lga> Laszlo Nagy wrote: > >> .../.../../plugin/name1/name1.py >> .... >> .../.../../plugin/namen/namen.py >> >> >> I block at the beginning and tried this (test.py is a real file) >> >>>>> s = 'test.py' >>>>> eval ('import ' + s) >>>>> > import test.py # This is invalid > import test # This MAY be valid > import name1.name1 # Most probably this is what you want if you have the > aforementioned directory stucture > from name1 import name1 # Or this? > > You must also: > > 1. Have the 'plugin' dir in your sys.path > 2. Have at least an empty plugin/name1/__init__.py file > > Another alternative is to have plugins/__init__.py and do something like: > > from plugins.name1 import name1 > > You should not overcomplicate things anyway. If you do not need these > name1...namen directories for sure, then just drop them. > > Hint: try this (untested) > > import os > fnames = os.listdir('plugins') > for fname in fnames: > if os.path.isdir(fname): > root,ext = os.path.splitext(fname) > cmd = "from plugins.%s import %s" % (root,root) > print "I should eval this:",cmd > > Best, > > Laszlo > > >> Traceback (most recent call last): >> File "<pyshell#1>", line 1, in -toplevel- >> eval ('import ' + s) >> File "<string>", line 1 >> import test.py >> Thanks, What I am doing is adding plugin support to PyCrust ... so I'm looking for a mechanism where anyone can develop a plugin and have it loaded by pycrust. the .py was a typo why the "...Have at least an empty plugin/name1/__init__.py file..." ? Thanks, hg From grahn+nntp at snipabacken.dyndns.org Mon Jan 22 15:55:32 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 22 Jan 2007 20:55:32 GMT Subject: Getting to an SSH account over a HTTP proxy References: <mailman.2985.1169469575.32031.python-list@python.org> <51jt71F1k884hU1@mid.uni-berlin.de> Message-ID: <slrnera43v.tcj.grahn+nntp@frailea.sa.invalid> On Mon, 22 Jan 2007 14:40:49 +0100, Diez B. Roggisch <deets at nospam.web.de> wrote: > BJ?rn Lindqvist wrote: > >> I want to use Python to connect to a SSH account over a HTTP proxy to >> automate some operations. I thought paramiko would be able to do that, >> but it can not (it seems). >> >> Is there some other Python module that can do what I want? > > Is there anything that can do what you want? Last time I checked there is no > such thing as SSH-over-HTTP. Are you sure that is possible? I am pretty sure there is. Or at least TCP-over-HTTP, or IP-over-HTTP. An acquaintance of mine used it to tonnel home through a corporate firewall. I think -- I didn't want to know the details. If you implement in the same way as ssh tunnels, the application doesn't need to know anything about it -- you just talk to a TCP port on localhost. Good for everyone involved. /Jorgen -- // Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn! From aboudouvas at panafonet.gr Fri Jan 5 10:19:37 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 5 Jan 2007 07:19:37 -0800 Subject: program deployment In-Reply-To: <12psqtppgi5cme6@corp.supernews.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> Message-ID: <1168010377.179056.220500@s80g2000cwa.googlegroups.com> > > Are they embarassed by their code? hehehe...no, just worried about stealing their ideas... From gheissenberger at gmail.com Fri Jan 12 10:31:32 2007 From: gheissenberger at gmail.com (gheissenberger at gmail.com) Date: 12 Jan 2007 07:31:32 -0800 Subject: Python nuube needs Unicode help In-Reply-To: <50pldgF1gecd0U2@mid.uni-berlin.de> References: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> <eo7goj$n4s$03$1@news.t-online.com> <1168613067.354487.40840@51g2000cwl.googlegroups.com> <50pldgF1gecd0U2@mid.uni-berlin.de> Message-ID: <1168615892.477387.176500@i15g2000cwa.googlegroups.com> Diez, you are awesome! This works! Thank you so much!!! You are so awesome! Diez B. Roggisch wrote: > gheissenberger at gmail.com wrote: > > > Can you attach files in this forum? Couldn't find the option. Oh well, > > here's the file. > > > > #!/usr/bin/python > > # Version: 1.1 > > # Author: Steve Losh > > > > from sets import Set > > from optparse import OptionParser > > from xml.dom.minidom import parse > > > > AudioPath = 'audio/' > > DatafilePath = 'utterances.trmxml' > > CONFIDENCE_LOW = None #'500' > > CONFIDENCE_HIGH = None #'500' > > > > utterancesFile = None > > > > > > class Utterance: > > def __init__(self, audio, grammarSet, text): > > self.audio = audio > > self.grammarSet = grammarSet > > self.text = text > > > > def __str__(self): > > return "SWIrecAcousticStateReset\ntranscription " + self.text \ > > + "\nrecognize " + AudioPath + self.audio > > There your __str__-method is. self.text and self.audio come from the > xml-parsing and are unicode objects - so they need to be encoded, like > this: > > def __str__(self): > return "SWIrecAcousticStateReset\ntranscription " + > self.text.encode('utf-8') + "\nrecognize " + AudioPath + > self.audio.encode('utf-8') > > > Diez From sean at datafly.net Sun Jan 21 21:47:53 2007 From: sean at datafly.net (Sean Schertell) Date: Mon, 22 Jan 2007 11:47:53 +0900 Subject: PyMeld for html templates? In-Reply-To: <1169241497.610167.130580@a75g2000cwd.googlegroups.com> References: <mailman.2858.1169084154.32031.python-list@python.org> <1169241497.610167.130580@a75g2000cwd.googlegroups.com> Message-ID: <69A8B843-8676-4498-AFD5-4E015E35CF20@datafly.net> I'm trying to get PyMeld happening but I'm a bit stumped as to how to make it work with mod_python. The pymeld docs show examples only for the Python command line interpreter and show using the print statement to output stuff. But using mod_python.apache, I think you need to use req.write(something) format. And of course, this fails when you feed it output from Meld. Any tips? Sean On Jan 20, 2007, at 6:18 AM, Richie Hindle wrote: > [Sean] >> I wonder if anyone has any thoughts on PyMeld as a template >> system for churning out general websites? > > I'm doing that (but then I would be wouldn't I? 8-) > http://www.mandant.net is an example - the content of each page comes > from a file containing just the content, the layout and sidebar are > defined in a template HTML file, and the navigation is built by a > Python script. All that is pulled together using PyMeld into a set of > HTML files and deployed to the web server (there's no need to it on > the > fly for that site, but you certainly could). > >> I want for a URI request to mysite.com/info >> to pull in a layout.html template which will in turn be populated by >> the info.html template. [...] how about PyMeld, any ideas on how >> to do it or whether it will even work as I've described? > > You'd do something like this: > > from PyMeld import Meld > > LAYOUT = """<html><head><title id='title'>The Title >
The page information goes here.
>

The real title >

Here is the info, which would in the real world > be read from a file.

""" > > page = Meld(LAYOUT) > info = Meld(INFO) > page.title = info.title._content > page.info = info.info._content > print page > > Is that the sort of thing you had in mind? > > -- > Richie Hindle > richie at entrian.com > > -- > http://mail.python.org/mailman/listinfo/python-list From Roberto.Bonvallet at cern.ch Fri Jan 12 15:25:07 2007 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Fri, 12 Jan 2007 20:25:07 +0000 (UTC) Subject: parsing a file name References: <1168622211.188972.179680@38g2000cwa.googlegroups.com> Message-ID: CSUIDL PROGRAMMEr wrote: > I have a filename > cairo-2.3.4.src.rpm > Is there any way i can only get 2.3.4 from this file name >>> a = "cairo-2.3.4.src.rpm" >>> import re >>> re.compile(r"\d+([.]\d+)*").search(a).group(0) '2.3.4' >>> a.split("-")[-1][:-len(".src.rpm")] '2.3.4' >>> ".".join(map(str, range(2, 5))) '2.3.4' -- Roberto Bonvallet From michele.cella at gmail.com Thu Jan 25 11:31:30 2007 From: michele.cella at gmail.com (Michele Cella) Date: 25 Jan 2007 08:31:30 -0800 Subject: ANN: Dejavu 1.5.0RC1 In-Reply-To: <1169712139.759270.165670@l53g2000cwa.googlegroups.com> References: <1169703594.951755.180990@m58g2000cwm.googlegroups.com> <1169712139.759270.165670@l53g2000cwa.googlegroups.com> Message-ID: <1169742690.210321.264090@v33g2000cwv.googlegroups.com> On 25 Gen, 09:02, "fumanchu" wrote: > > > I am curious ... how this compare to SQLAlchemy?The comparisons could be endless ;) but here are some of the larger > differences: > > 1. Dejavu uses generic "storage" concepts and syntax, while SQLAlchemy > prefers database concepts and syntax. > 2. Dejavu uses Python expressions (lambdas) to query storage, whereas > SQLAlchemy uses functions and magic attributes: > * SQLAlchemy: users.select(and_(users.c.age < 40, users.c.name != > 'Mary')) > * Dejavu: recall(users, lambda u: u.age < 40 and u.name != 'Mary') > 3. SQLAlchemy prefers that you write data classes, table classes and > the mappers between them. Dejavu only expects you to write a data > class. New in 1.5: you can auto-generate even the data classes if you > already have a populated database. > 4. SQLAlchemy allows you to write more complicated queries (like > subqueries and aggregate columns). Dejavu doesn't provide those yet > (slated for 1.6). > 5. Dejavu supports model evolution (very much like rails's ActiveRecord migrations) I will add that I've never been able to (easily) wrap my head around ORMs like SQLObject and SQLAlchemy, while they are both great pieces of software and SQLAlchemy is impressively well documented (like every other things powered by Michael Bayer) they are trying to reinvent an ad-hoc query language on top of SQL using python that you need to learn, that's why my favorite Dejavu feature it's the way you build queries (using common python constructs like lambda) and define models (using python types like str, unicode... or your own). I really encourage anyone to check it out, it's not getting the publicity it deserves but this doesn't mean it's not good at what it does, and Robert is like a quality assurance. ;-) Ciao Michele From bearophileHUGS at lycos.com Thu Jan 18 19:55:39 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Jan 2007 16:55:39 -0800 Subject: Iterator length In-Reply-To: <1169167258.553202.190130@m58g2000cwm.googlegroups.com> References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> <1169167258.553202.190130@m58g2000cwm.googlegroups.com> Message-ID: <1169168139.350836.79790@s34g2000cwa.googlegroups.com> George Sakkis: > Is this a rhetorical question ? If not, try this: It wasn't a rhetorical question. > >>> x = (i for i in xrange(100) if i&1) > >>> if leniter(x): print x.next() What's your point? Maybe you mean that it consumes the given iterator? I am aware of that, it's written in the function docstring too. But sometimes you don't need the elements of a given iterator, you just need to know how many elements it has. A very simple example: s = "aaabbbbbaabbbbbb" from itertools import groupby print [(h,leniter(g)) for h,g in groupby(s)] Bye, bearophile From rasmussen.bryan at gmail.com Sat Jan 27 03:32:13 2007 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Sat, 27 Jan 2007 09:32:13 +0100 Subject: Yank Bastards KILLED THEIR OWN PEOPLE to stage 911 DRAMA In-Reply-To: <1169837804.481376.5790@q2g2000cwa.googlegroups.com> References: <1169837804.481376.5790@q2g2000cwa.googlegroups.com> Message-ID: <3bb44c6e0701270032j22e59864v1a598aea47e91b26@mail.gmail.com> See, if the python list mail server was written in Lisp Paul Graham would already have been able to write up a spam filter to ban this guy. Seriously though, shouldn't Thermate be banned by now. Cheers, Bryan Rasmussen On 26 Jan 2007 10:56:44 -0800, thermate at india.com wrote: > There is a million dollar reward for ANY fascist bastard to disprove > this assertion by giving a consistent theory of ALL the major observed > effects on that day about the related events. > > Dick faced Cheney sprayed his own lawyer with BB's. > > See the video by Alex Jones on the Forensics, why the claims of > distance and mistake were such a big lie ....... > > 911 TRUTH BACK WITH VIGOR AND NEW SITE > Now it has two sites under > www.st911.org > > -- > http://mail.python.org/mailman/listinfo/python-list > From libintr at gmail.com Sun Jan 28 06:25:11 2007 From: libintr at gmail.com (lee) Date: 28 Jan 2007 03:25:11 -0800 Subject: from future module!!!!!!! Message-ID: <1169983511.674847.281290@s48g2000cws.googlegroups.com> Guys whats the from future module in python?thanks From tim at tdw.net Wed Jan 17 09:05:39 2007 From: tim at tdw.net (Tim Williams) Date: Wed, 17 Jan 2007 14:05:39 +0000 Subject: generate tuples from sequence In-Reply-To: References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: <9afea2ac0701170605m2aa59f7hbea57159451d0e86@mail.gmail.com> On 17 Jan 2007 04:50:33 -0800, Will McGugan wrote: > > Will McGugan wrote: > > > Hi, > > > > I'd like a generator that takes a sequence and yields tuples containing > > n items of the sqeuence, but ignoring the 'odd' items. For example > > Forgot to add, for my purposes I will always have a sequence with a > multiple of n items. something along the lines of....... >>> [ (x,x+1,x+2) for x in xrange(0,9,3) ] [(0, 1, 2), (3, 4, 5), (6, 7, 8)] HTH :) From brochu121 at gmail.com Wed Jan 17 17:34:31 2007 From: brochu121 at gmail.com (David Brochu) Date: Wed, 17 Jan 2007 17:34:31 -0500 Subject: Making a simple script standalone Message-ID: <9583ed900701171434s155907f0s5d681a6935d37ff9@mail.gmail.com> > Hi, > I'm new to this group. I've tried finding my answer in existing messages, > but no such luck. > > What I want to do is to compile/bundle/prepare/whatever_term a simple > Python script for deployment on a Windows machine. Installing Python > itself on that machine, is not an option. Ideally I would like to obtain > a single executable file, but a script+runtime is acceptable. > > There is nothing graphical, nothing fancy about the script. > The only imports are: os, stat, string and time. > > > Any suggestions on an - easy and clear - path to follow ? > > cx_Freeze was not mentioned so far. its perhaps most easy and clear. Robert [You might also look into Py2Exe - http://www.py2exe.org/ I have used this before and it wasn't too difficult to bundle everything up into 1 exe file. Definately read the tutorial] Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.kasak at gmail.com Wed Jan 3 16:34:26 2007 From: denis.kasak at gmail.com (Denis Kasak) Date: Wed, 03 Jan 2007 22:34:26 +0100 Subject: type classobj not defined? In-Reply-To: References: Message-ID: Wesley Brooks wrote: > Dear Users, > > I'm in the process of adding assert statements to a large piece of > code to aid with bug hunting and came across the following issue; > > Using python in a terminal window you can do the following: > >> type(False) == bool > True > > I would like to check that an object is a class, here's an example: > >> class b: > ....def __init__(self): > ........self.c = 1 > ....def d(self): > ........print self.c > >> type(b) > > > But the following fails: > >> type(b) == classobj > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'classobj' is not defined You can compare it against the ClassType object located in the types module. > import types > class b: ....def __init__(self): ........self.c = 1 ....def d(self): ........print self.c > type(b) == types.ClassType True -- Denis Kasak From bearophileHUGS at lycos.com Wed Jan 3 21:00:38 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 Jan 2007 18:00:38 -0800 Subject: code optimization (calc PI) / Full Code of PI calc in Python and C. In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> <1167872076.937415.250340@11g2000cwr.googlegroups.com> Message-ID: <1167876037.524055.315250@v33g2000cwv.googlegroups.com> Michael M.: > * The C is very fast, Python not. > * Target: Do optimization, that Python runs nearly like C. Python can't be fast as C for that kind of programs. Note that your original C program gives less digits than the Python program. Your original takes about ~15.2 s on my PC. The following version (I have just cleaned it up a bit, probably it can be improved) needs about ~0.7 seconds with Psyco and ~5.7 s without (Psyco compilation time and Python startup times aren't included, if you include them the timings are ~0.94 s and ~5.96 s). Compiled with ShedSkin this program needs ~0.29 s (redirecting the output to a file, because ShedSkin printing is slow still). from time import clock def compute_pi(): pi = [] a = 10000 b = d = e = g = 0 c = 5600 f = [2000] * (c + 4000 + 1) while c: d = 0 g = c * 2 b = c while b > 1: d += f[b] * a g -= 1 f[b] = d % g d = d // g g -= 1 d *= b b -= 1 c -= 14 pi.append("%04d" % int(e + d // a)) e = d % a return "".join(pi) import psyco; psyco.bind(compute_pi) start_time = clock() print compute_pi() print "Total time elapsed:", round(clock() - start_time, 2), "s" Bye, bearophile From chris at kateandchris.net Tue Jan 30 10:39:19 2007 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 30 Jan 2007 10:39:19 -0500 Subject: printing to a redirected stdout from a process that was called with "2>&1 > /dev/null &" In-Reply-To: <1170112357.792999.241280@s48g2000cws.googlegroups.com> References: <1170112357.792999.241280@s48g2000cws.googlegroups.com> Message-ID: <20070130153919.GA12259@kateandchris.net> On Mon, Jan 29, 2007 at 03:12:37PM -0800, Pappy wrote: > SHORT VERSION: > Python File B changes sys.stdout to a file so all 'prints' are written > to the file. Python file A launches python file B with os.popen("./B > 2>&^1 >dev/null &"). Python B's output disappears into never-never > land. > > LONG VERSION: > I am working on a site that can kick off large-scale simulations. It > will write the output to an html file and a link will be emailed to > the user. Also, the site will continue to display "Loading..." if the > user wants to stick around. > > The simulation is legacy, and it basically writes its output to stdout > (via simple print statements). In order to avoid changing all these > prints, I simply change sys.stdout before calling the output > functions. That works fine. The whole thing writes to an html file > all spiffy-like. > > On the cgi end, all I want my (python) cgi script to do is check for > form errors, make sure the server isn't crushed, run the simulation > and redirect to a loading page (in detail, I write a constantly > updating page to the location of the final output file. When the > simulation is done, the constantly updating file will be magically > replaced). The root problem is that the popen mechanism described > above is the only way I've found to truly 'Detach' my simulation > process. With anything else, Apache (in a *nix environment) sits and > spins until my simulation is done. Bah. > > Any ideas? The subprocess module is probably a good starting point: http://docs.python.org/dev/lib/module-subprocess.html It will allow you greater control over what happens with the output of a process that you start. Specifically look at the the stdout and stderr arguments to Popen. You can provide these with an open file descriptor or a file object and it will dump the output into there. -Chris > > _jason > > -- > http://mail.python.org/mailman/listinfo/python-list From ggrp1.20.martineau at dfgh.net Sun Jan 7 17:15:09 2007 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 7 Jan 2007 14:15:09 -0800 Subject: PDF rendering toolkit? References: Message-ID: <1168208109.479979.99370@38g2000cwa.googlegroups.com> Jorge Vargas wrote: > Hi > > I'm looking for a tool to take an actual .pdf file and display it in a > window (I'm using wxwidgets at the moment) > > [snip] How about just using Adobe's Acrobat Reader application which is freely available on most platforms? There's some related information about doing this in the following thread that might help get you started : > http://groups.google.com/group/comp.lang.python/browse_frm/thread/3a578c032ff72d46/c1ddf40bf738cd7f?&hl=en#c1ddf40bf738cd7f HTH, -Martin From steve at holdenweb.com Mon Jan 29 13:29:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Jan 2007 18:29:22 +0000 Subject: Can I undecorate a function? In-Reply-To: References: Message-ID: Matthew Wilson wrote: > The decorator as_string returns the decorated function's value as > string. In some instances I want to access just the function f, > though, and catch the values before they've been decorated. > > Is this possible? > > def as_string(f): > def anon(*args, **kwargs): > y = f(*args, **kwargs) > return str(y) > return anon > > @as_string > def f(x): > return x * x > It's much simpler not to use the decorator syntax if you also want access to the original function. Simply declare f as a function, then assign decorator(f) to some other name. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From gherron at islandtraining.com Wed Jan 24 16:12:21 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 24 Jan 2007 13:12:21 -0800 Subject: Static variables In-Reply-To: References: Message-ID: <45B7CBB5.3060200@islandtraining.com> Florian Lindner wrote: > Hello, > does python have static variables? I mean function-local variables that keep > their state between invocations of the function. > > Thanks, > > Florian > Nope. Not really. In new versions of Python, functions and methods can have attributes that can be used like function level static variables. However, I usually use module level attributes for such things. Gary Herron From grzesiof at gmail.com Sun Jan 7 10:44:50 2007 From: grzesiof at gmail.com (gz) Date: 7 Jan 2007 07:44:50 -0800 Subject: low level python read's Message-ID: <1168184689.924811.305290@42g2000cwt.googlegroups.com> Hi! I wanted to use python to test a simple character device (on linux) and I'm running into strange behaviour of read.. I have a short buffer inside my device and the idea is that it blocks read's when the buffer is empty. For reads that ask for more characters that the buffer holds the device should return the number of bytes actually read... In c i can write: f = open("/dev/testdevice",O_RDWR); read(f,buffer,1000); and i see in my device, that everything is ok. No I'd love to reproduce this in python.. f = open("/dev/testdevice", "r+",0) # for unbuffered access f.read(1000) ..but now i see in the device log's that python issued 2 reads! One that got the whole buffer (less then 1000 chars) and after that python tries to read more! (and hangs in my device, since the buffer is empty... So how do i stop python from trying to be smart and just read *at most* 1000 chars and let it go if he(it?*) reads less? grzes. p.s *is python a "he" or an "it"? From smusnmrNOSPAM at yahoo.com Tue Jan 9 02:47:08 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Tue, 9 Jan 2007 08:47:08 +0100 Subject: help: code formatter? References: <50f5nnF1fb5uqU1@mid.individual.net> Message-ID: Bjoern wrote: > Why don't you just write one? :) Very funny! Just learning Python :( Regards, siggi > siggi wrote: > >> as a newbie I have problems with formatting code of downloaded >> programs, because IDLE's reformatting capabilities are limited . >> Incorrect indentation, mixing of TAB with BLANKs or eol are often >> very nasty to correct. >> Is there a simple code formatter that first removes all >> indentations and then refomats correctly? > > Why don't you just write one? :) > > Seriously: Try. > > BTW: Guessing to what amount of space TABs must be converted in > mixed source can be non-trivial. > > Regards, > > > Bj?rn > > -- > BOFH excuse #289: > > Interference between the keyboard and the chair. > From paddy3118 at netscape.net Wed Jan 31 12:26:46 2007 From: paddy3118 at netscape.net (Paddy) Date: 31 Jan 2007 09:26:46 -0800 Subject: how to "free" an object/var ? In-Reply-To: References: <1170228172.691120.200280@a75g2000cwd.googlegroups.com> Message-ID: <1170264406.588032.116550@s48g2000cws.googlegroups.com> On Jan 31, 7:34 am, Steven D'Aprano wrote: > On Tue, 30 Jan 2007 23:22:52 -0800, Paddy wrote: > >> As far as I know there is no way to force the deletion of an object > >> even if it is in use. This is a Good Thing. > > >> -- > >> Steven D'Aprano > > > The folowing will make the data available for garbage collection no > > matter what references it: > > >>>> l = ["data"] *10 > >>>> l > > ['data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', 'data', > > 'data'] > >>>> l2 = l > >>>> l[:] = [] > >>>> l2 > > [] > > Sort of. > > What happens is that both l and l2 are names referring to the same list. > After executing l[:] the *contents* of the list change, from lots of > "data" to nothing. Naturally both l and l2 see the change, because they > both point to the same list. But the original contents of the list still > exist until the garbage collector sees that they are no longer in use, > and then frees them. > > You can prove this by doing something like this: > > data = "\0"*1000000 # one (decimal) megabyte of data > L = [data] # put it in a list > L[:] = [] # "free" the contents of the list > assert len(data) == 1000000 > # but the megabyte of data still there > > Again, you can't force Python to free up memory that is still in use. > If you could, that would be a bug. > > -- > Steven D'Aprano Thanks Stephen for explaining my answer a bit more. The [:] = [] trick should be of most use when you go on to allocate large amounts of data in your program once again, when the gc coud then make some of the same memory available for the new objects. As others have said, getting Python to give back memory to the underlying OS is murder - The best way I have of doing that is to split your program into two and chain their execution, which allows the OS to reclaim the memory used by the first Python process when it finishes. - Paddy. From huayang.xia at gmail.com Wed Jan 10 17:40:58 2007 From: huayang.xia at gmail.com (Huayang Xia) Date: 10 Jan 2007 14:40:58 -0800 Subject: where to find the spec of format in PyObject_CallMethod In-Reply-To: References: <1168466755.996033.130120@i39g2000hsf.googlegroups.com> Message-ID: <1168468858.432320.129920@k58g2000hse.googlegroups.com> Thanks. I have mixed arguments. I found the format spec @ http://docs.python.org/api/arg-parsing.html On Jan 10, 5:31 pm, Carsten Haese wrote: > On Wed, 2007-01-10 at 14:05 -0800, Huayang Xia wrote: > > I am trying to use PyObject_CallMethod. It needs a format string to > > specify what are the followed arguments. Is it possible to use a > > PyObject* as an argument? > > > Where can I find the spec for the format? > > > Thanks in advance.Seehttp://docs.python.org/api/object.html#l2h-247: > > Note in particular "The C arguments are described by a Py_BuildValue() > format string that should produce a tuple" and "Note that if you only > pass PyObject * args, PyObject_CallMethodObjArgs is a faster > alternative." > > So, If all your arguments are PyObject pointers, use > PyObject_CallMethodObjArgs instead. Otherwise, use PyObject_CallMethod > and consult the documentation for Py_BuildValue on how to construct the > format string. > > Hope this helps, > > Carsten. From daniele.varrazzo at gmail.com Thu Jan 18 08:16:56 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 18 Jan 2007 05:16:56 -0800 Subject: Is it possible to fasten the import of cgi? In-Reply-To: <45af6f47$0$322$e4fe514c@news.xs4all.nl> References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> Message-ID: <1169126216.239740.202950@38g2000cwa.googlegroups.com> Cecil Westerhof wrote: > I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I > can not time the time used to import time, but os and sys do not take more > as a millisecond. My script itself takes 3 or 4 milliseconds. But importing > cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is > there a way to make this more fast? The import off cgi makes the script at > least 20 times as slow. Something like mod-python is not a possibility. I > could use it on my test machine, but not at the osting provider. Does the hosting provider support fastcgi? It would avoid starting the interpreter at each request too. From aisaac at american.edu Wed Jan 17 22:53:14 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 18 Jan 2007 03:53:14 GMT Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: "Peter Otten" <__peter__ at web.de> wrote in message news:eol9ac$v3l$02$1 at news.t-online.com... > I like > > >>> items = range(9) > >>> N = 3 > >>> zip(*[iter(items)]*N) > [(0, 1, 2), (3, 4, 5), (6, 7, 8)] Except that it is considered implementation dependent: http://mail.python.org/pipermail/python-list/2005-February/307550.html Alan Isaac From rocky at panix.com Thu Jan 25 08:08:39 2007 From: rocky at panix.com (R. Bernstein) Date: 25 Jan 2007 08:08:39 -0500 Subject: pdb in python2.5 References: <1169717486.230356.79730@l53g2000cwa.googlegroups.com> Message-ID: "Rotem" writes: > Hi, > > Maybe I'm repeating a previous post (please correct me if I am). > > I've tried the following code in python 2.5 (r25:51908, Oct 6 2006, > 15:22:41) > example: > > from __future__ import with_statement > import threading > > def f(): > l = threading.Lock() > with l: > print "hello" > raise Exception("error") > print "world" > > try: > f() > except: > import pdb > pdb.pm() > > This fails because pdb.pm() attempts to access sys.last_traceback which > is not assigned. Recent releases of pydb (http://bashdb.sf.net/pydb) don't suffer this problem. (But see below.) > Trying: > pdb.post_mortem(sys.exc_traceback) > > Yields the following: > > test.py(9)f() > -> print "world" > (Pdb) > > the 'w' command yields a similar output, which implies that the > exception was thrown from the wrong line. > the traceback module is better, yielding correct results (displays line > 8 instead of 9). > > Has anyone encountered this behavior? Yes, this seems to be a bug in pdb. It is using the traceback's f_line instance variable rather than the tb_lineno instance variable. I guess these two values are usually the same. In fact, I haven't been able to come up with a Python 2.4 situtation where they are different. (If someone can, I'd appreciate it if you'd send me a small example so I can put it in the pydb regression tests.) Even in 2.5, it's kind of hard to get a case where they are different. If I remove the "with", the problem goes away. It was also bug in pydb, but I've just committed in CVS the fix for this > is pdb broken? Best as I can tell pdb isn't all that well maintained. (Had it been, I probably wouldn't have devoted the time to pydb that I have been.) > I get similar results for larger/more complex pieces of code. > > Thanks in advance, > > Rotem From mail at microcorp.co.za Wed Jan 17 02:57:33 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 17 Jan 2007 09:57:33 +0200 Subject: asyncore/asynchat and terminator string References: <45AD5A2F.7060701@ilm.com> Message-ID: <000301c73a17$b11ee800$03000080@hendrik> "David Hirschfield" wrote: 8< --------------- problems on syncing up in serial comms ----------------- I have seen people address this with success by using stuff like: "XXHEADERXX" as a "here starts the lesson" identifier, with no trouble, on a high volume newsfeed. If you assume that any binary value is possible and equally likely, then the problem looks hopeless, but in practice if you do this kind of thing, followed by a length, which automatically points to the next "instance" of the "here starts the lesson" in a stream, then it becomes extremely unlikely to occur in the wild. If you also repeat the length at the end, then you can "scan Backwards" through the stream. And if its not like that, its a "false sync"... The other way is to take a leaf out of the bit oriented protocols' book, and to "frame" the "packets" between (possibly repetitious) occurrences of a character that is guaranteed not to occur in the data, known as a "flag" character. You do this by a process that is called "escaping" the occurrences of the flag character in the data with yet another "escape char", that also needs special treatment if it happens in the data... Escaping can be accomplished by replacing each instance of the "Poison Characters" by an instance of the escape char, followed by the bitwise inversion of the poison char. Unescaping has to do the reverse. Using a tilde "~" as a flag char, and the ordinary slash as an escape char works well. So a packet with both poison chars in it will look like this: "~~ordinary chars followed by tilde" + "/\x81"+ "ordinary followed by slash" +"/\xd0" + "somestuff~~" So you sync up by looking for a tilde followed by a non tilde, and the end is when you hit a tilde again. To unescape, you look for slashes and invert the chars following them. Also Yahoo for "netstrings" If you want to be Paranoid, then you also implement message numbers, to make sure you don't lose packets, and for hyper paranoia, put in a BCC or LRC to make sure what you send off is received... If you are running over Ethernet, the last lot is not warranted, as its done anyway - but on a serial port, where you are on your own, it makes sense. HTH - Hendrik From rubic88 at gmail.com Wed Jan 31 17:04:13 2007 From: rubic88 at gmail.com (Rubic) Date: 31 Jan 2007 14:04:13 -0800 Subject: ctypes error on exit of win32 application Message-ID: <1170281053.423976.85890@j27g2000cwj.googlegroups.com> I'm attempting to use ctypes on a DLL with the following signature: __declspec(dllimport) void process_record(char *, char *); An example .cpp file has code like this: int main(int argc, char **argv) { char record[100]; char code[6]; ... process_record(code, record); When I invoke it under Python everything fine while the interpreter is running: >>> from ctypes import * >>> record = create_string_buffer("My Record") >>> code = create_string_buffer('\000' * 6) >>> cdll.grouper.process_recode(code, record) >>> print code.value '9999' But when the interpreter exits, either interactively or from a script, the following Program Error popup gets displayed: "python.exe has generated errors and will be closed by Windows. You will need to restart the program." What can I do to prevent this error? (Environment: Win2000, Python 2.5) -- Jeff Bauer Rubicon, Inc. From george.sakkis at gmail.com Thu Jan 11 19:51:25 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 11 Jan 2007 16:51:25 -0800 Subject: Fixed keys() mapping References: <1168535970.585977.317760@p59g2000hsd.googlegroups.com> Message-ID: <1168563085.550262.83550@s34g2000cwa.googlegroups.com> For what it's worth, I added it to the Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499373 George From gagsl-py at yahoo.com.ar Mon Jan 22 14:19:54 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Jan 2007 16:19:54 -0300 Subject: (newbie) new version install (winXP) ? In-Reply-To: References: Message-ID: <7.0.1.0.0.20070122161709.0598aaf0@yahoo.com.ar> At Monday 22/1/2007 15:58, you wrote: >Can I install only the higher version of a certain package ? >Is that done by simply copying them ? You should read the install instructions given in the package, but usually it's as easy as: - extract the .zip into a temporary directory - open a command line window, go to that directory, and run: - python setup.py install >Should I make a backup (of what) ? Perhaps... -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From joel.hedlund at gmail.com Thu Jan 11 11:01:05 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Thu, 11 Jan 2007 17:01:05 +0100 Subject: Need startup suggestions for writing a MSA viewer GUI in python In-Reply-To: <1168525085.580490.76860@i39g2000hsf.googlegroups.com> References: <1168525085.580490.76860@i39g2000hsf.googlegroups.com> Message-ID: > UI design requires a different skillset than programming. It can be a > very frustrating and thankless task as well. It is incomparably easier > to see the flaws in existing interfaces than correcting them (or even > creating the said interface). Make sure to start with something simple, > and learn that way. > > I would also recommend that you implement something novel, there are > many existing MSA viewers and it won't be easy to improve on them. Do > something that adds new value and people will be willing to expend > effort to use it. That's true for any software. And for any aspect of life, come to think about it. /Joel From no-spam at no-spam-no-spam.invalid Wed Jan 17 12:55:27 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 17 Jan 2007 18:55:27 +0100 Subject: predefined empty base class ?? In-Reply-To: <1169053011.399278.290980@a75g2000cwd.googlegroups.com> References: <1169053011.399278.290980@a75g2000cwd.googlegroups.com> Message-ID: iwl wrote: > Hi, > > is there an predefined empty base class > which I can instanziate to have an > container i can copy attributes in? > you are not the only one missing such class http://groups.google.com/group/comp.lang.python/msg/3ff946e7da13dba9 RFE SF #1637926 Robert From paul at boddie.org.uk Sun Jan 7 12:02:55 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 7 Jan 2007 09:02:55 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> Message-ID: <1168189375.843789.306180@51g2000cwl.googlegroups.com> Paul Rubin wrote: > > class A: > __x = 3 > > class B(A): > __x = 4 # ok > > class C(B): > __x = 5 # oops! > > Consider that the above three class definitions might be in separate > files and you see how clumsy this gets. What are you trying to show with the above? The principal benefit of using private attributes set on either the class or the instance is to preserve access, via self, to those attributes defined in association with (or within) a particular class in the inheritance hierarchy, as opposed to providing access to the "most overriding" definition of an attribute. This is demonstrated more effectively with a method on class A: class A: __x = 3 def f(self): print self.__x # should always refer to A.__x class B(A): __x = 4 class C(B): __x = 5 Here, instances of A, B and C will always print the value of A.__x when the f method is invoked on them. Were a non-private attribute to be used instead, instances of A, B and C would print the overridden value of the attribute when the f method is invoked on them. Paul From godson.g at gmail.com Mon Jan 15 06:31:34 2007 From: godson.g at gmail.com (Godson) Date: Mon, 15 Jan 2007 17:01:34 +0530 Subject: python and MOV or MPEG In-Reply-To: <510uf3F1i9oo6U1@mid.uni-berlin.de> References: <510uf3F1i9oo6U1@mid.uni-berlin.de> Message-ID: On 1/15/07, Diez B. Roggisch wrote: > > siggi wrote: > > > Hi all, > > > > does Python support MPEG or MOV videoclips? I couldn't find anything > about > > it online. > > Weak in googling today? Must have been a rough weekend. > > There are several options, including pymedia and pygame. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Here is a way how you can do it! http://godsongera.blogspot.com/2006/12/play-mpeg-file-with-python.html -- Godson Gera, http://godson.auroinfo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From S.Mientki-nospam at mailbox.kun.nl Mon Jan 15 15:45:20 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 15 Jan 2007 21:45:20 +0100 Subject: Anyone has a nice "view_var" procedure ? Message-ID: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> hello, Is there some handy/ nice manner to view the properties of some variable ? As a newbie, I often want to see want all the properties of a var, and also some corner values (large arrays) etc. Probably it's not so difficult, but I don't see how to distinguish for example between a string and an array. An array has a shape, a string not etc. thanks, Stef Mientki From deets at nospam.web.de Mon Jan 22 08:40:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Jan 2007 14:40:49 +0100 Subject: Getting to an SSH account over a HTTP proxy References: Message-ID: <51jt71F1k884hU1@mid.uni-berlin.de> BJ?rn Lindqvist wrote: > I want to use Python to connect to a SSH account over a HTTP proxy to > automate some operations. I thought paramiko would be able to do that, > but it can not (it seems). > > Is there some other Python module that can do what I want? Is there anything that can do what you want? Last time I checked there is no such thing as SSH-over-HTTP. Are you sure that is possible? Diez From gatis.tomsons at gmail.com Tue Jan 9 08:30:46 2007 From: gatis.tomsons at gmail.com (Gacha) Date: 9 Jan 2007 05:30:46 -0800 Subject: pyExcelerator big integer values Message-ID: <1168349446.381187.65810@11g2000cwr.googlegroups.com> I use pyExcelerator to import some data from xml file. One column contains integer values like: 4750456000708 4750456000715 4750456000333 ... But when I do import the pyExcelerator converts them to something like this: 4.7504560002e+12 4.7504560007e+12 4.7504560007e+12 4.7504560003e+12 How I understand it's because the integer value is too big. If the type of the items was string, then all would be fine, but I can't control the file content. The question is, how can I import the integers in normal format. From pete at fenelon.com Tue Jan 9 15:16:01 2007 From: pete at fenelon.com (Pete Fenelon) Date: Tue, 9 Jan 2007 20:16:01 +0000 Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: <1p9d74-5i71.ln1@stratos.fenelon.com> In comp.arch.embedded octabox at gmail.com wrote: > Hello all, > > I represent Octabox, an Internet Start-up developing a wide-scale Hello. F*ck off, spammer. pete -- pete at fenelon.com "he just stuck to buying beer and pointing at other stuff" From richard.m.tew at gmail.com Mon Jan 8 05:14:42 2007 From: richard.m.tew at gmail.com (Richard Tew) Date: 8 Jan 2007 02:14:42 -0800 Subject: Stackless Python 2.5 for Nintendo DS Message-ID: <1168251282.391733.274050@38g2000cwa.googlegroups.com> Hi, I have updated NDS Python from Python 2.4.3 to Python 2.5 (or rather the Stackless version of it). You can read more about it here if it might interest you: http://www.disinterest.org/NDS/Python25.html Cheers, Richard. From could.net at gmail.com Sat Jan 27 21:33:49 2007 From: could.net at gmail.com (Frank Potter) Date: 27 Jan 2007 18:33:49 -0800 Subject: extracting from web pages but got disordered words sometimes In-Reply-To: <1169926006.739252.57360@p10g2000cwp.googlegroups.com> References: <1169896727.567159.239160@a34g2000cwb.googlegroups.com> <1169926006.739252.57360@p10g2000cwp.googlegroups.com> Message-ID: <1169951629.215444.322170@s48g2000cws.googlegroups.com> Thank you, I tried again and I figured it out. That's something with beautiful soup, I worked with it a year ago also dealing with Chinese html pages and nothing error happened. I read the old code and I find the difference. Change the page to unicode before feeding to beautiful soup, then everything will be OK. On Jan 28, 3:26 am, "Paul McGuire" wrote: > After looking at the pyparsing results, I think I see the problem with > your original code. You are selecting only the characters after the > rightmost "-" character, but you really want to select everything to > the right of "- -". In some of the titles, the encoded Chinese > includes a "-" character, so you are chopping off everything before > that. > > Try changing your code to: > title=full_title.split("- -")[1] > > I think then your original program will work. > > -- Paul From tubby at bandaheart.com Thu Jan 4 21:46:32 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 04 Jan 2007 21:46:32 -0500 Subject: clarification on open file modes Message-ID: Does a py script written to open and read binary files on Windows affect files on a Linux or Mac machine in a negative way? My concern is portability and safety. I want scripts written within Windows to work equally well on Linux and Mac computers. Is this the safest, most portable way to open files on any platform: fp = open(file_name, 'rb') fp.close() I understand that doing the following on Windows to a binary file (a jpeg or exe files for example) can cause file corruption, is that correct? fp = open(file_name, 'r') fp.close() How can a simple open in read mode corrupt data??? From deets at nospam.web.de Mon Jan 8 04:41:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Jan 2007 10:41:07 +0100 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> Message-ID: <50ehtmF1fh46iU1@mid.uni-berlin.de> vizcayno schrieb: > Hello: > Need your help in the "correct" definition of the next function. If > necessary, I would like to know about a web site or documentation that > tells me about best practices in defining functions, especially for > those that consider the error exceptions management. > I have the next alternatives but I think there are better: IMHO none of them is good. Python has exceptions. Use them. There is no need to awkwardly communicate error conditions using return-values. Use return values to return values. Use exceptions in case of errors. Diez From deets at nospam.web.de Mon Jan 1 15:08:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Jan 2007 21:08:51 +0100 Subject: Question concerning this list [WebCrawler] In-Reply-To: References: Message-ID: <4vt82jF1ddi9fU1@mid.uni-berlin.de> Thomas Ploch schrieb: > John Nagle schrieb: >> Very true. HTML is LALR(0), that is, you can parse it without >> looking ahead. Parsers for LALR(0) languages are easy, and >> work by repeatedly getting the next character and using that to >> drive a single state machine. The first character-level parser >> yields tokens, which are then processed by a grammar-level parser. >> Any compiler book will cover this. >> >> Using regular expressions for LALR(0) parsing is a vice inherited >> >from Perl, in which regular expressions are easy and "get next >> character from string" is unreasonably expensive. In Python, at least >> you can index through a string. >> >> John Nagle > > I take it with LALR(0) you mean that HTML is a language created by a > Chomsky-0 (regular language) Grammar? Nope. LALR is a context free grammar parsing technique. Regular expressions can't express languages like a^n b^n but something like
is
^2
^2 Diez From libintr at gmail.com Mon Jan 8 13:27:11 2007 From: libintr at gmail.com (lee) Date: 8 Jan 2007 10:27:11 -0800 Subject: newbieee Message-ID: <1168280831.323496.277020@38g2000cwa.googlegroups.com> I getting familiarised with python...can any one suggest me a good editor available for python which runs on windows xp....one more request guys...can nyone tell me a good reference manual for python.. From cvanarsdall at mvista.com Thu Jan 11 19:09:22 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 11 Jan 2007 16:09:22 -0800 Subject: Tools Designing large/complicated applications Message-ID: <45A6D1B2.2040508@mvista.com> For those of you that work on larger applications but still code in python... do your development teams use any tools to facilitate the design? (i'm not asking about editors here, i'm really asking about software design tools) Are these the same tools you would use to help engineer software in another language? Is there anyone here who is forced to use a tool to design python software that completely hates it? Why do you hate it? Thanks! -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From postindex at gmail.com Fri Jan 12 18:11:46 2007 From: postindex at gmail.com (postindex at gmail.com) Date: 12 Jan 2007 15:11:46 -0800 Subject: Is it possible to get whole commandline include redirection.., etc Message-ID: <1168643505.949920.154470@a75g2000cwd.googlegroups.com> Can I get whole commandline not only argument list. 1. When I command like this $ a.py > filename 2. sys.argv is returns only argument list ['a.py'] Is there a way to find out 'redirection' information. thank you for reading this From Eric_Dexter at msn.com Thu Jan 18 02:57:04 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 17 Jan 2007 23:57:04 -0800 Subject: Projects anyone? In-Reply-To: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> References: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> Message-ID: <1169107024.688867.145120@l53g2000cwa.googlegroups.com> I have a project available if you are intrested. It is a music package that includes everything from tracker style editing to code generators for fltk(generates csound and python code) and dot code generation.. There is a huge range of possible projects and a little debugging so you can even have your choice of tasks or come up with one of your own https://sourceforge.net/projects/dex-tracker placid wrote: > Hi all, > > I'm looking for anyone who is working on a project at the moment that > needs help (volunteer). The last project i worked on personally was > screen-scraping MySpace profiles (read more at the following link) > > http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles > > > but that didn't go all to well, so im kinda bored and need something to > do, with Python. So any suggestions anyone? > > Cheers From gagsl-py at yahoo.com.ar Wed Jan 17 16:55:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Jan 2007 18:55:52 -0300 Subject: predefined empty base class ?? In-Reply-To: <2%trh.15631$X72.7347@newsread3.news.pas.earthlink.net> References: <1169053011.399278.290980@a75g2000cwd.googlegroups.com> <2%trh.15631$X72.7347@newsread3.news.pas.earthlink.net> Message-ID: <7.0.1.0.0.20070117185239.040f67b0@yahoo.com.ar> At Wednesday 17/1/2007 15:34, Dennis Lee Bieber wrote: > > is there an predefined empty base class > > which I can instanziate to have an > > container i can copy attributes in? > > I think that's a two-liner... > > >>> class EmptyBase(object): >... pass Do you want a one liner? class EmptyBase(object): pass :) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From hg at nospam.org Fri Jan 5 04:11:49 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 10:11:49 +0100 Subject: find a .py path References: Message-ID: <0Nunh.45640$gl2.30462@newsfe16.lga> hg wrote: > Hi, > > Is there an easy way for a script being executed (from anywhere) to know > where is is ... something in os.path ? > > Thanks, > > hg oops: os.path.abspath(sys.argv[0]) hg From jon at ffconsultancy.com Mon Jan 1 17:21:36 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 01 Jan 2007 22:21:36 +0000 Subject: Writing more efficient code References: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> <1167687229.430930.197720@v33g2000cwv.googlegroups.com> Message-ID: <459989ec$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> bearophileHUGS at lycos.com wrote: > Jon Harrop: >> OCaml's pattern matcher is very sophisticated and very fast. You'll >> probably shrink your code by several fold whilst also having it run a few >> orders of magnitude faster and having it statically checked, so it will >> be more reliable. > > You seem to forget some months of time to learn OCaml. I think most people could pick up the core ideas in a day and start writing working programs. Just read: http://www.ffconsultancy.com/free/ocaml http://www.ffconsultancy.com/products/ocaml_for_scientists/chapter1.html > And my Python programs seem reliable enough despite being unstatically > checked :-) Damn. ;-) >> You might want to look at any language with pattern matching: OCaml, SML, >> Haskell, F#, Mathematica etc. > > Mathematica pattern matching is good, but Mathematica costs a lot of > money (and you need some time to learn it, it's not an easy system). Mathematica is expensive but learning to use pattern matching is much easier than learning how to write a pattern matcher and much less tedious than reimplementing it yourself all the time (which is exactly what the OP will end up doing). -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet From pavlovevidence at gmail.com Fri Jan 5 16:40:49 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 5 Jan 2007 13:40:49 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: <1168033249.612218.233730@s34g2000cwa.googlegroups.com> Stef Mientki wrote: > Not sure I wrote the subject line correct, > but the examples might explain if not clear > > > *** first attempt *** > class pin: > def __init__ (self): > self.Name = 'Unknown Pin' > > aap = pin() # create an instance > aap.Name = 'aap' # set it's name > print aap.Name # print it's name > # but why should I set it's name ?? > print 'aap' # I can just as well print a constant string !! > # (ok there will be an extra check) > > > *** second attempt *** > class pin2: > def __init__ (self, naam): > self.Name = naam > > aap2 = pin2('aap2') # seems completely redundant to me. > print aap2.Name > print 'aap2' > > > Can this be achieved without redundancy ? No. Simply not possible in Python. You should consider whether there is another opportunity to eliminate the redundancy. For instance, it looks like these pin definitions might end up in a dictionary of some sort (I don't know your use case). You could automatically generate the keys from the names like this: _pindefs = ( pin("aap"), pin("wap"), pin("dcr"), ... ) pins = {} for pin in _pindefs: pins[pin.Name] = pin Then you access pins["aap"]. The reason I suspect the pins will end up in a dictionary is that, in many real applications, the pin name would often be specified in the input. (This is very often the case whenever people want to know the symbol an object is bound to, for any application.) Carl Banks From banaouas.medialog at wanadoo.fr Mon Jan 22 10:16:29 2007 From: banaouas.medialog at wanadoo.fr (m.banaouas) Date: Mon, 22 Jan 2007 16:16:29 +0100 Subject: OpenOffice 2.0 UNO update Links; need help In-Reply-To: References: Message-ID: <45b4d44b$0$25921$ba4acef3@news.orange.fr> Sells, Fred a ?crit : > I've got a ~100 page document I assemble from ~30 OOo .odt files with some > search and replace functions. I then produce a PDF. So far so good. > > Now I need to get a barcode from our internal website and insert that. The > barcode will vary based on some parameters. Our internal site provides a > .jpg image (or .gif) based on those parameters. > > Can anyone provide a snippet or some pointers on how to do this. I've > googled it to death and checked the OOo DevGuide to no avail. > > Either python or java solution is acceptable. > > you can use urllib2 python module: # TestGoogle.py # import urllib2 # f = urllib2.urlopen('http://www.google.fr/images/nav_logo.png') data = f.read() f = file('nav_logo.png', 'w') f.write(data) f.close() in your case, may be parameters are passed thru url to get a particular barcode image (http://myserver/myapplication/barcode?format=xxx&id=yyy etc. ...). for authentication, if any, it needs a little more sophisticated coding. From thn at mail.utexas.edu Tue Jan 30 19:14:24 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 30 Jan 2007 16:14:24 -0800 Subject: Sorting a List of Lists In-Reply-To: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> References: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> Message-ID: <1170202464.838174.26040@a75g2000cwd.googlegroups.com> On Jan 30, 5:55 pm, apoth... at gmail.com wrote: > I can't seem to get this nailed down and I thought I'd toss it out > there as, by gosh, its got to be something simple I'm missing. > > I have two different database tables of events that use different > schemas. I am using python to collate these records for display. I do > this by creating a list of lists that look roughly like this: > > events = [['Event URL as String', 'Event Title as String ', Event Date > as Datetime], ...] > > I then thought I'd just go events.sort(lambda x,y: x[2] it a day. That didn't work. But then lamda functions like to be very > simple, maybe object subscripts aren't allowed (even though I didn't > get an error). So I wrote a comparison function that looks much as you > would expect: > > def date_compare(list1, > list2): > x = list1[2] > y = list2[2] > if > x>y: > return > 1 > elif > x==y: > return > 0 > else: # > x return -1 > > But as before sorting with this function returns None. > > What have I overlooked? All sorts return None. the sort is in place. Check your list post- sort. THN From __peter__ at web.de Tue Jan 23 03:13:21 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Jan 2007 09:13:21 +0100 Subject: Is there a better way to implement this: References: <1169490140.401270.226830@l53g2000cwa.googlegroups.com> Message-ID: Paul Boddie wrote: > Michael Yanowitz wrote: >> >> I guess I am looking for something portable (both >> Windows and Linux) where I can abort a function after >> a certain time limit expires. > > Doing a search for "timeout function Python" on Google reveals a number > of approaches. > Using threads: > > * http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473878 That doesn't abort the calculation, however -- it just moves on with a default value instead of the actual result if that is not available after the specified timespan. The calculation may go on forever eating up resources. Peter From sjmachin at lexicon.net Sun Jan 7 02:08:32 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Jan 2007 23:08:32 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 References: <459f1703$0$24039$9b622d9e@news.freenet.de> Message-ID: <1168153712.697954.127690@i15g2000cwa.googlegroups.com> Martin v. L?wis wrote: > Carroll, Barry schrieb: > > What I want to know is: > > > > * has anyone else encountered a problem like this, * how was the > > problem corrected, * can the fix be retro-fitted to 2.5 and 2.4? > > From your description, I suspect an error in your code. Your description > indicates that you don't expect to have more than five files open > simultaneously. Yet, the error message "Too many open files" occurs when > you open many more files (in the order of hundreds of files). > > It is very unlikely that there is a bug in Python where it would fail to > close a file when .close() is explicitly invoked on it (as your > description suggests that you do), so if you get that error message, it > can only mean that you fail to close some files. I don't understand: the OP's description suggests nothing of the sort to me. What he said was: """ In this way, a tree of Parser instances is created, each with a single open file object. (BTW, recursive and circular references are not allowed.) When each Parser instance comes to the end of its table, the instance is explicitly destroyed, presumably destroying any objects it holds, AND closing its open file. """ which I interpret as: he is doing del parser_instance, and *presuming* (incorrectly) that attributes of parser_instance (including an open file object) are magically whisked away instantly, instead of later/maybe. He later says he explicitly closed the files, which fixed what he alleges (incorrectly) to be a bug. To the OP: (1) The del statement doesn't "destroy" anything. It unbinds the name from the object in the current namespace, and decrements the object's reference count. Only if the reference count is then zero will the janitor be called in. (2) Check the reference count on the parser_instance just before you del it. You could be retaining a reference somewhere. (3) Explicitly close all non-lightweight objects like files (even read-only ones) and sockets rather than hoping they will go away. HTH, John From hanke at brailcom.org Sat Jan 6 17:45:32 2007 From: hanke at brailcom.org (Hynek Hanke) Date: Sat, 06 Jan 2007 23:45:32 +0100 Subject: Traceback of hanged process Message-ID: <1168123532.3498.51.camel@chopin> Hello, please, how do I create a pythonic traceback from a python process that hangs and is not running in an interpreter that I executed manually or it is but doesn't react on CTRL-C etc? I'm trying to debug a server implemented in Python, so I need some analog of 'gdb attach' for C. Unfortunatelly, googling and reading documentation revealed nothing, so please excuse if this question is dumb. Thank you, Hynek Hanke From steven.bethard at gmail.com Sat Jan 27 13:25:28 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 27 Jan 2007 11:25:28 -0700 Subject: distutils, sdist and tests Message-ID: How do I get distutils to include my testing module in just the "sdist" distribution? My current call to setup() looks like:: distutils.core.setup( ... py_modules=['argparse'], ) If change this to:: distutils.core.setup( ... py_modules=['argparse', 'test_argparse'], ) then test_argparse.py gets included in the source distribution, but it also gets installed to site-packages like a normal module. I don't think I want that. If I change it to:: distutils.core.setup( ... py_modules=['argparse'], scripts=['test_argparse.py'], ) then test_argparse.py gets included in the source distribution, but it also gets installed in the Python scripts directory. I don't think I want that either. I want test_argparse.py to be available in the source distribution, but I don't think it should be included in the binary distributions. Or am I just being to picky? Do folks normally include their tests in the binary distributions? STeVe From ptmcg at austin.rr.com Tue Jan 23 09:45:26 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jan 2007 06:45:26 -0800 Subject: How to instantiate a different class in a constructor? In-Reply-To: References: Message-ID: <1169563525.644251.118250@v45g2000cwv.googlegroups.com> On Jan 23, 5:09 am, GiBo wrote: > Hi all, > > I have a class URI and a bunch of derived sub-classes for example > HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is > module urllib & friends, however my actual problem however maps very > well to this example). > > Now I want to pass a string to constructor of URI() and get an instance > of one of the subclasses back. For example uri=URI('http://abcd/...') > will make 'uri' an instance of HttpURI class, not instance of URI. > > To achieve this I have a list of all subclasses of URI and try to > instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI > to HttpURI constructor it raises ValueError exception and I want to test > HttpsURI, FtpURI, etc. > > For now I have this code: > > ===== > class URI(object): > def __new__(self, arg): > for subclass in subclasses: > try: > instance = object.__new__(subclass, arg) > return instance > except ValueError, e: > print "Ignoring: %s" % e > raise ValueError("URI format not recognized" % arg) > Call __new__ and subclass.__init__ explicitly: class URI(object): def __new__(self, arg): for subclass in subclasses: try: instance = object.__new__(subclass) instance.__init__(arg) return instance except ValueError, e: print "Ignoring: %s" % e raise ValueError("URI format not recognized" % arg) (Might I suggest 4-space indents vs. 8?) -- Paul From http Fri Jan 12 18:43:43 2007 From: http (Paul Rubin) Date: 12 Jan 2007 15:43:43 -0800 Subject: MP3 decoder module? Message-ID: <7x4pqvste8.fsf@ruckus.brouhaha.com> Anyone know of a reasonable mp3 decoder library I can call from Python? Some Googling didn't find anything too promising. It found Pymedia (which plays mp3's through a sound system) and any number of utilities that parse ID3 tags and other metadata. But I want to actually decode the mp3 frames and crunch on the audio samples. Basically I want to write a program that takes an mp3 audio file and finds the silent frames, with the idea of chopping the file into segments at those points automatically, or compressing the silences out of spoken audio to make it play faster without chipmunking up the pitch, etc. Of course if you know of something that does this stuff already, that can help too. I think I don't need mp3 encoding, just decoding. I want to decode and recognize certain frames and chop them out, but the non-chopped frames will be copied verbatim to avoid quality loss from re-encoding. Thanks. From bj_666 at gmx.net Mon Jan 8 10:59:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 08 Jan 2007 16:59:33 +0100 Subject: Maybe a little bug of ipython 0.7.3 ? References: Message-ID: In , fdu.xiaojf at gmail.com wrote: > In [8]: a = range(1000) > > In [9]: a? > Type: list > Base Class: > String Form: [0, 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, 26 <...> 0, 981, 98 > 2, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, > 997, 998, 999] > Namespace: Interactive > Length: 1000 > Docstring: > list() -> new list > list(sequence) -> new list initialized from sequence's items > > *Please note that there is an extra "0" after "**26 <...>", which > doesn't appear for the followling cases:* This 0 is the last digit of `980`. If the string form is very long the string itself is shortened by leaving out the middle part. It's irrelevant which object it was before the conversion to a string. Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Mon Jan 22 03:47:44 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jan 2007 08:47:44 GMT Subject: html + javascript automations = [mechanize + ?? ] or somethingelse? References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> <1169441279.556814.16770@38g2000cwa.googlegroups.com> <1169445833.722792.53680@a75g2000cwd.googlegroups.com> Message-ID: "John" wrote: > I tried it, didnt work with the python25 distribution msi file that is > on python.org > But activestate python worked. Now I can open IE using COM. What I am > trying > to figure out is how to click an x,y coordinate on a page in IE > automatically > using COM. How about typing something automatically...Any ideas? Don't think about clicking a coordinate or typing something; think about the actions on the page. e.g. to fill in a field on a form you'll want something like: ie.document.forms[formname][fieldname].value = 'whatever' to click a button call its click method e.g. submit = ie.document.forms[0]['submit'] submit.focus() submit.click() Check out the documentation at msdn.microsoft.com for the application, document, form etc. objects. Generally speaking anything you could have done through javascript you should be able to do through automation, plus a few of other things that javascript might have blocked for security reasons. From buzzard at urubu.freeserve.co.uk Sun Jan 14 21:00:38 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 15 Jan 2007 02:00:38 +0000 Subject: Python web app. (advice sought) Message-ID: <45aae51b.0@entanet> Hello, I find myself in the, for me, unusual (and at the moment unique) position of having to write a web application. I have quite a lot of existing Python code that will form part of the business logic. This relies on 3rd party libraries (such as numpy) which would make porting to e.g. IronPython difficult (I would imagine). I was thinking LAMP (the P standing for Python, of course), particularly as I was originally encouraged to go for open source solutions. The application will provide some basic statistical analyses of data contained in database tables and associated plots (R / matplotlib / graphviz). There will also be some heavier duty Monte Carlo simulation and graphical modelling / MCMC. The user(s) will need to be able to set model parameters; maybe even tinker with model structure, so it will be very interactive (AJAX?). I've had a look at Django, Turbogears and Plone, and at the moment I am torn between Turbogears and Plone. I get the impression that Turbogears will require me to write more non-Python code, but maybe Plone is more than I need (steeper learning curve?). Maybe Turbogears will lead to a more loosely coupled app. than Plone? The disconcerting thing is that others on the project (who won't be developing) have started to talk about a LAMP back end with an IIS front end, .NET, and the benefits of sharepoint. The emphasis is supposed to be on rapid development, and these technologies are supposed to help. But I have no real familiarity with them at all; just Python, C and SQL to any realistic level of competence. Any advice would be greatly appreciated. I have to do much of the statistical work too, so I need to make good choices (and hopefully be able to justify them so nobody else on the project makes inappropriate choices for me). e.g. I don't mind learning Javascript if it doesn't take too long. The physical server will initially be a multiprocessor machine with several GB of RAM. But we also have a cluster (I have no details, I only started the project a week ago). So any advice regarding parallelisation would also be appreciated (or, in fact, any useful advice / pointers at all). Thanks. Duncan From Art at Arthurian.com Wed Jan 31 19:01:22 2007 From: Art at Arthurian.com (Frank Arthur) Date: Wed, 31 Jan 2007 19:01:22 -0500 Subject: Germany issues warrants for 13 American CIA agents References: <1170286881.262636.315770@a75g2000cwd.googlegroups.com> Message-ID: <75awh.27298$uW.7695@bignews3.bellsouth.net> wrote in message news:1170286881.262636.315770 at a75g2000cwd.googlegroups.com... > Here is the daily good news. > ======================== Is it now 39 "American CIA agents" or did you just posted this 3 times? From khemkaamit at gmail.com Fri Jan 19 08:41:04 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Fri, 19 Jan 2007 19:11:04 +0530 Subject: How to find out if another process is using a file In-Reply-To: References: Message-ID: <1360b7230701190541y3bbf3769made02659c24cfb8b@mail.gmail.com> > > Yes, that would work very neatly but I don't have any control over the > writing process. I think the modification time route might be the best > option, but thanks to all for their replies. Its not pythonic, but may be "lsof" on POSIX can be helpful: see: http://www.physiol.ox.ac.uk/Computing/Online_Documentation/lsof-quickstart.txt cheers, -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From S.Mientki-nospam at mailbox.kun.nl Sun Jan 28 16:36:20 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 28 Jan 2007 22:36:20 +0100 Subject: working model of a microcoded computer In-Reply-To: <1170018888.634619.289950@s48g2000cws.googlegroups.com> References: <1170018888.634619.289950@s48g2000cws.googlegroups.com> Message-ID: <628b5$45bd173e$d443bb3a$27924@news.speedlinq.nl> kloro wrote: > This is somewhat off topic, but I think many programmers would be > interested to look at a working model of a microcoded computer at: > > tomspages.com > > click on the link for 'Hack the Com puter Model.' It conveys among > other > things the physical events that underlie execution of a microcode > instruction and, by extension, of machine language. > > I would like very much to get people's feedback on the thing. > > Thanks, > > tom arnall > north spit, ca > usa > hi Tom, looks nice ! But probably completely written in Java ? However, people who can handle this kind of complex circuits, can do without such a simulation :-( But still I see a good practical use of it, for educational and debugging purposes, if you would implement one of those small micro-controllers (e.g. PIC). succes, Stef Mientki From skip at pobox.com Mon Jan 1 09:50:57 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 1 Jan 2007 08:50:57 -0600 Subject: Collecting list of module dependencies In-Reply-To: <45991BE2.2010803@eastlink.ca> References: <45991BE2.2010803@eastlink.ca> Message-ID: <17817.8145.709408.736456@montanaro.dyndns.org> David> Hi. Is anyone aware of any code to create a list of dependent David> modules for a python module. modulefinder: http://docs.python.org/lib/module-modulefinder.html Added to Python in 2.3. Skip From slow at slowhome.org Wed Jan 10 00:36:18 2007 From: slow at slowhome.org (Julio Biason) Date: Tue, 9 Jan 2007 21:36:18 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) In-Reply-To: <7.0.1.0.0.20070109203637.0422acb8@yahoo.com.ar> References: <2BBAEE949D384D40A2B851287ADB6A4304595A6D@eugsrv400.psc.pscnet.com> <7.0.1.0.0.20070109203637.0422acb8@yahoo.com.ar> Message-ID: <20070110053618.GA24572@chiclet.dreamhost.com> [Kinda stealing the thread] On Tue, Jan 09, 2007 at 09:05:30PM -0300, Gabriel Genellina wrote: > And do you actually need so many open files simultaneously? > Try to close them explicitely when you finish working on them - do > not rely on GC for closing files. This has *always* been the > recomended practice (except maybe, inside a short script that > finishes quickly). If I use a file() in a for, how to I explicitely close the file? for line in file('contents'): print line Would this work like the new 'with' statement or it will only be closed when the GC finds it? -- Julio "slow" Biason From horpner at yahoo.com Wed Jan 10 10:10:12 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Jan 2007 16:10:12 +0100 Subject: An iterator with look-ahead References: Message-ID: On 2007-01-10, Fredrik Lundh wrote: > if you're doing simple parsing on an iterable, it's easier and > more efficient to pass around the current token and the > iterator's next method: > > http://online.effbot.org/2005_11_01_archive.htm#simple-parser-1 Thank you. Much better. -- Neil Cerutti From half.italian at gmail.com Thu Jan 25 06:58:40 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 25 Jan 2007 03:58:40 -0800 Subject: My Tkinter Threading nightmare In-Reply-To: <7xac07wzh2.fsf@ruckus.brouhaha.com> References: <1169693266.209082.323310@a75g2000cwd.googlegroups.com> <7x1wljajgg.fsf@ruckus.brouhaha.com> <7xac07wzh2.fsf@ruckus.brouhaha.com> Message-ID: <1169726320.703566.272120@k78g2000cwa.googlegroups.com> On Jan 24, 7:35 pm, Paul Rubin wrote: > Paul Rubin writes: > > def idle(self): > > # read and execute any commands waiting on the queue > > while True: > > try: > > func, args, kw = self.cmd_queue.get(block=False) > > except QueueEmpty: > > return > > func (*args, **kw)Whoops, I forgot, you have to set up the after event again at the end > of this: > > def idle(self): > # read and execute any commands waiting on the queue > while True: > try: > func, args, kw = self.cmd_queue.get(block=False) > except QueueEmpty: > return > func (*args, **kw) > self.after(20, self.idle) Thanks Paul. That has made more sense than all of my scrounging combined, but I still need to mess around with the idea and code some. How can I put something like the window delete into the command queue? Isn't window.protocol() just binding the close window button to a function? I'll look deeper and experiment and try to make sense of it once again tomorrow. :) ~Sean From pretoriano_2001 at hotmail.com Mon Jan 8 13:52:25 2007 From: pretoriano_2001 at hotmail.com (vizcayno) Date: 8 Jan 2007 10:52:25 -0800 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <45A1F1D9.8070206@v.loewis.de> <1168262749.852897.13010@q40g2000cwq.googlegroups.com> Message-ID: <1168282345.456346.103590@q40g2000cwq.googlegroups.com> Thank you for your guidelines and for changing my mind. I am trying to do my best in generating good code and, in that attempt ... I only know that nothing know. Regards. From tim at tdw.net Mon Jan 15 04:32:31 2007 From: tim at tdw.net (Tim Williams) Date: Mon, 15 Jan 2007 09:32:31 +0000 Subject: Python web app. (advice sought) In-Reply-To: References: <45aae51b.0@entanet> Message-ID: <9afea2ac0701150132q28a49cbfy366fbc01862a4445@mail.gmail.com> On 15 Jan 2007 00:52:33 -0800, Torabisu wrote: > > Duncan Smith wrote: > > Hello, > > I find myself in the, for me, unusual (and at the moment unique) > > position of having to write a web application. I have quite a lot of > > existing Python code that will form part of the business logic. This > > relies on 3rd party libraries (such as numpy) which would make porting > > to e.g. IronPython difficult (I would imagine). I was thinking LAMP > > (the P standing for Python, of course), particularly as I was originally > > encouraged to go for open source solutions. > > > > The application will provide some basic statistical analyses of data > > contained in database tables and associated plots (R / matplotlib / > > graphviz). There will also be some heavier duty Monte Carlo simulation > > and graphical modelling / MCMC. The user(s) will need to be able to set > > model parameters; maybe even tinker with model structure, so it will be > > very interactive (AJAX?). > > > > I've had a look at Django, Turbogears and Plone, and at the moment I am > > torn between Turbogears and Plone. I get the impression that Turbogears > > will require me to write more non-Python code, but maybe Plone is more > > than I need (steeper learning curve?). Maybe Turbogears will lead to a > > more loosely coupled app. than Plone? > > > > The disconcerting thing is that others on the project (who won't be > > developing) have started to talk about a LAMP back end with an IIS front > > end, .NET, and the benefits of sharepoint. The emphasis is supposed to > > be on rapid development, and these technologies are supposed to help. > > But I have no real familiarity with them at all; just Python, C and SQL > > to any realistic level of competence. > > > > Any advice would be greatly appreciated. I have to do much of the > > statistical work too, so I need to make good choices (and hopefully be > > able to justify them so nobody else on the project makes inappropriate > > choices for me). e.g. I don't mind learning Javascript if it doesn't > > take too long. The physical server will initially be a multiprocessor > > machine with several GB of RAM. But we also have a cluster (I have no > > details, I only started the project a week ago). So any advice > > regarding parallelisation would also be appreciated (or, in fact, any > > useful advice / pointers at all). Thanks. > > > > Duncan > > I was in a similar boat a while back, needing to make a decision on > what to use for our web development. I had worked with Plone > previously and found that for our needs it wasn't going to work. Our > web development was quite specific and didn't fit ideally into the > standard content management realm. I also looked at Django and > TurboGears, installing and working with each. I eventually went with > Django, and I've really enjoyed working with it. Was a personal choice > and I'm sure our development would have been as successful if I'd > chosen TurboGears. > > If you want the strength of persistent layers, MVC, templating etc etc > but want to stay away from the heavier frameworks, another possibility > is http://webpy.org/. Very simple to implement, lightweight yet still > fairly full of features. > Don't overlook Karrigell either, with a tiny learning curve its always worth consideration, especially if you need rapid development and a web server that will sit on top of your exising .py modules. www.karrigell.com hth :) From gblais at cox.net Mon Jan 1 13:47:16 2007 From: gblais at cox.net (gblais at cox.net) Date: Mon, 1 Jan 2007 18:47:16 GMT Subject: Wow, Python much faster than MatLab References: Message-ID: We're not so far apart. I've used SAS or 25 years, and R/S-PLUS for 10. I think you've said it better than I did, though: R requires more attention (which is often needed). I certainly didn't mean that R crashed - just an indictment of how much I thought I was holding in my head. Gerry From robert.kern at gmail.com Sun Jan 28 00:51:10 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Jan 2007 23:51:10 -0600 Subject: distutils, sdist and tests In-Reply-To: References: Message-ID: Steven Bethard wrote: > Robert Kern wrote: >> Are you sure that you don't have changes left over in your setup.py when you >> tested that? > > Yep. (Though I still cleared everything out and tried it again.) > Here's what I got using an unmodified setup.py and the MANIFEST.in you > suggested. Note that the "bdist" version is putting test_argparse.py > into site-packages. > > python setup.py bdist_dumb > running bdist_dumb > running build > running build_py > installing to build\bdist.win32\dumb > running install > running install_lib Are you sure that you removed the build/ directory? Because if it wasn't there, distutils would say that it was creating one: [argparse]$ python setup.py bdist_dumb running bdist_dumb running build running build_py creating build creating build/lib copying argparse.py -> build/lib installing to build/bdist.macosx-10.3-fat/dumb running install running install_lib -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py at yahoo.com.ar Wed Jan 3 20:57:50 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Jan 2007 22:57:50 -0300 Subject: code optimization (calc PI) / Full Code of PI calc in Python and C. In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> <1167872076.937415.250340@11g2000cwr.googlegroups.com> Message-ID: <7.0.1.0.0.20070103222616.0569cd80@yahoo.com.ar> At Wednesday 3/1/2007 22:10, Michael M. wrote: >Ok, here is the code. It is a translation of the following code, found >on the internet. > >* The C is very fast, Python not. >* Target: Do optimization, that Python runs nearly like C. Why? Python is strong in other aspects, *not* on computation speed. Anyway, for a nice and rather fast Python implementation (yielding unlimited digits *without* unlimited storage), see http://mail.python.org/pipermail/python-list/2006-November/414347.html The code, for reference: def pi(): k, a, b, a1, b1 = 2, 4, 1, 12, 4 while 1: # Next approximation p, q, k = k*k, 2*k+1, k+1 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 # Yield common digits d, d1 = a/b, a1/b1 while d == d1: yield str(d) a, a1 = 10*(a%b), 10*(a1%b1) d, d1 = a/b, a1/b1 import sys sys.stdout.writelines(pi()) (The converted C code does a lot of nonsense in Python terms - maybe you should try to interpret *what* it does and then reimplement that using Python) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bbands at gmail.com Fri Jan 26 17:49:23 2007 From: bbands at gmail.com (BBands) Date: 26 Jan 2007 14:49:23 -0800 Subject: time series data and NumPy In-Reply-To: References: <1169830757.220964.196540@m58g2000cwm.googlegroups.com> <51us3uF1mdcpsU1@mid.uni-berlin.de> Message-ID: <1169851763.205104.63450@m58g2000cwm.googlegroups.com> On Jan 26, 10:46 am, Robert Kern wrote: > Yes, one can make numpy arrays with "object" as its type. One can even extend > the C-level parts as well. For example, we have an experimental package in the > scipy sandbox for uniform time series that uses mx.DateTime. > > http://www.scipy.org/TimeSeriesPackage I saw that, but I am working with irregular time series. > This is frequently what I do. For dates, I like Modified Julian Day Numbers > although I am sure that would horrify some people more knowledgeable than I. Not horrified, just doing it. ;-) jab From mail at microcorp.co.za Sun Jan 14 00:38:51 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 14 Jan 2007 07:38:51 +0200 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <004a01c7379e$466f2cc0$03000080@hendrik> "Nick Maclaren" wrote: > The "cheap" means "cheap in hardware" - it needs very little logic, > which is why it was used on the old, discrete-logic, machines. > > I have been told by hardware people that implementing IEEE 754 rounding > and denormalised numbers needs a horrific amount of logic - which is > why only IBM do it all in hardware. And the decimal formats are > significantly more complicated. > > What I don't know is how much precision this approximation loses when > used in real applications, and I have never found anyone else who has > much of a clue, either. > I would suspect that this is one of those questions which are simple to ask, but horribly difficult to answer - I mean - if the hardware has thrown it away, how do you study it - you need somehow two different parallel engines doing the same stuff, and comparing the results, or you have to write a big simulation, and then you bring your simulation errors into the picture - There be Dragons... - Hendrik From stephen at theboulets.net Sun Jan 21 22:30:40 2007 From: stephen at theboulets.net (stephen_b) Date: 21 Jan 2007 19:30:40 -0800 Subject: Help with 'popen' Message-ID: <1169436640.161806.111510@38g2000cwa.googlegroups.com> Can someone let me know why this won't work? Thanks. >>> from os import popen >>> popen('export asdfasdf=hello').read() '' >>> popen('echo $asdfasdf').read() '\n' Thanks. Stephen From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 4 11:35:01 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 04 Jan 2007 17:35:01 +0100 Subject: Best way to implement a timed queue? References: Message-ID: <504ollF1enbn0U1@mid.individual.net> Thomas Ploch wrote: > I am having troubles with implementing a timed queue. I am using > the 'Queue' module to manage several queues. But I want a timed > access, i.e. only 2 fetches per second max. I am horribly stuck on > even how I actually could write it. Has somebody done that before? > And when yes, how is the best way to implement it? If you use an event loop system you could derive a class from your queue class whose "pop" method only returns an element if some timer has run out. After the maximum number of fetches you'd have to reset the timer. Regards, Bj?rn -- BOFH excuse #327: The POP server is out of Coke From nagle at animats.com Sun Jan 14 22:25:01 2007 From: nagle at animats.com (John Nagle) Date: Mon, 15 Jan 2007 03:25:01 GMT Subject: How naive is Python? Message-ID: How naive (in the sense that compiler people use the term) is the current Python system? For example: def foo() : s = "This is a test" return(s) s2 = foo() How many times does the string get copied? Or, for example: s1 = "Test1" s2 = "Test2" s3 = "Test3" s = s1 + s2 + s3 Any redundant copies performed, or is that case optimized? How about this? kcount = 1000 s = '' for i in range(kcount) : s += str(i) + ' ' Is this O(N) or O(N^2) because of recopying of "s"? I just want a sense of what's unusually inefficient in the current implementation. Thanks. John Nagle From webraviteja at gmail.com Mon Jan 8 20:26:27 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Jan 2007 17:26:27 -0800 Subject: Network failure when using urllib2 In-Reply-To: <1168302603.565442.113760@v33g2000cwv.googlegroups.com> References: <1168292352.349983.139260@i15g2000cwa.googlegroups.com> <1168301738.984509.3030@38g2000cwa.googlegroups.com> <1168302603.565442.113760@v33g2000cwv.googlegroups.com> Message-ID: <1168305987.647165.21720@42g2000cwt.googlegroups.com> jdvolz at gmail.com wrote: > I am fetching different web pages (never the same one) from a web > server. Does that make a difference with them trying to block me? > Also, if it was only that site blocking me, then why does the internet > not work in other programs when this happens in the script. It is > almost like something is seeing a lot of traffic from my computer, and > cutting it off thinking it is some kind of virus or worm. I am > starting to suspect my firewall. Anyone else have this happen? > > I am going to read over that documentation you suggested to see if I > can get any ideas. Thanks for the link. > > Shuad No! What I suggested should not effect traffic from other servers. I would go with Gabriel's suggestion and check for open connections just in case. Although I can't imagine why that would give you a 404 response since it is a server response (implies successful connection). I would expect that you would get a client error in such a case. Of course, you can always rule out your suspicions of local conditions (turn off security software briefly or try from a different machine) unless your ISP is implementing safeguards against DOS attacks from their network with normal users in mind. Ravi Teja. From john106henry at hotmail.com Fri Jan 5 15:32:13 2007 From: john106henry at hotmail.com (John Henry) Date: 5 Jan 2007 12:32:13 -0800 Subject: Learning to program in Python In-Reply-To: <1168028517.005902.172880@11g2000cwr.googlegroups.com> References: <1168028517.005902.172880@11g2000cwr.googlegroups.com> Message-ID: <1168029133.866590.43770@i15g2000cwa.googlegroups.com> jbchua wrote: > Hello everybody. > > I am an Electrical Engineering major and have dabbled in several > languages such as Python, C, and Java in my spare time because of my > interest in programming. However, I have not done any practical > programming because I have no idea where to get started. I taught > myself these languages basically by e-tutorials and books. This makes > me feel as if I don't really know how to implement these languages. > Does anybody have any advice on where to start applying my limited > knowledge practically in order to advance my learning? Which area of EE are you in? Or just starting on that as well? If you're just starting, chanllege yourself to build a R mesh and calculate the Thevenin equivalent looking out from a particular node. Then you can expand that to an RLC network. Besure to use Objects, think in terms of objects, and code in objects. Don't hard code the data type. You'll be able to see how magical the Duck Typing is in Python. Have fun. From __peter__ at web.de Tue Jan 30 08:18:58 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 30 Jan 2007 14:18:58 +0100 Subject: error messages containing unicode References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> <1170160464.576122.62230@h3g2000cwc.googlegroups.com> <528sn0F1nhkoiU1@mid.uni-berlin.de> <1170162459.577853.282090@l53g2000cwa.googlegroups.com> Message-ID: Jim wrote: > On Jan 30, 7:41 am, "Diez B. Roggisch" wrote: >> >> (2) convert the file name to ASCII before you store it; or >> > I need the non-ascii information, though, which is why I included it >> > in the error message. >> Then convert it to utf-8, or some encoding you know it will be used by >> your terminal. > Thank you for the suggestion. Remember please that I am asking for a > safe way to pull the unicode object from the exception object (derived > from a Python built-in), so I can't store it as unicode first and then > convert to regular string when I need to print it out-- my exact > question is how to get the unicode. So I take your answer to be to > refuse to put in a unicode-not-ascii in there in the first place. > > It then seems to me that you are saying that the best practice is that > every function definition should contain a parameter, like so. > > def openNewFile(fn,errorEncoding='utf-8'): > : > try: > open(fn,'r') > except Exception, err > raise myException 'unable to open > '+fn.encode(errorEncoding,'replace') > > I guess that beyond that passing those parameters and putting encode > on every variable in my routines that occurs in an error message it is > ugly, it seems to me that it violates the principle that you should do > everything inside the program in unicode and only encode at the > instant you need the output, in that the exception object is carrying > around an ascii-not-unicode object. Printing to a terminal should work: >>> try: ... raise Exception(u"gew?hnlich ?hnlich ?blich") ... except Exception, e: ... print e.message ... gew?hnlich ?hnlich ?blich If you're writing to a file you still have to encode explicitly. Peter From steve at REMOVEME.cybersource.com.au Mon Jan 15 22:02:05 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 16 Jan 2007 14:02:05 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: On Tue, 16 Jan 2007 08:54:09 +1100, Ben Finney wrote: > dickinsm at gmail.com writes: > >> Suppose you're writing a class "Rational" for rational numbers. The >> __init__ function of such a class has two quite different roles to >> play. > > That should be your first clue to question whether you're actually > needing separate functions, rather than trying to force one function > to do many different things. [snip] > All of this points to having a separate constructor function for each > of the inputs you want to handle. [snip] > The alternate constructors are decorated as '@classmethod' since they > won't be called as instance methods, but rather: > > foo = Rational.from_string("355/113") > bar = Rational.from_int(17) > baz = Rational.from_rational(foo) That's one way of looking at it. Another way is to consider that __init__ has one function: it turns something else into a Rational. Why should the public interface of "make a Rational" depend on what you are making it from? Think of built-ins like str() and int(). I suggest that people would be *really* unhappy if we needed to do this: str.from_int(45) str.from_float(45.0) str.from_list([45, 45.5]) etc. Why do you consider that Rationals are different from built-ins in this regard? > def __add__(self, other): > result = perform_addition(self, other) > return result But that could just as easily be written as: def __add__(self, other): return perform_addition(self, other) which then raises the question, why delegate the addition out of __add__ to perform_addition? There is at least three distinct costs: a larger namespace, an extra function to write tests for; and an extra method call for every addition. What benefit do you gain? Why not put the perform_addition code directly in __add__? Just creating an extra layer to contain the complexity of rational addition doesn't gain you anything -- you haven't done anything to reduce the complexity of the problem, but you have an extra layer to deal with. And you still haven't dealt with another problem: coercions from other types. If you want to be able to add Rationals to (say) floats, ints and Rationals without having to explicitly convert them then you need some method of dispatching to different initialiser methods. (You should be asking whether you really do need this, but let's assume you do.) Presumably you create a method Rational.dispatch_to_initialisers that takes any object and tries each initialiser in turn until one succeeds, then returns the resultant Rational. Or you could just call it Rational.__init__. This doesn't mean that __init__ must or even should contain all the initialisation logic -- it could dispatch to from_string, from_float and other methods. But the caller doesn't need to call the individual initialisers -- although of course they are public methods and can be called if you want -- since __init__ will do the right thing. -- Steven D'Aprano From horpner at yahoo.com Thu Jan 11 14:18:29 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Jan 2007 20:18:29 +0100 Subject: passing a variable to an external program References: <1168542633.290682.267570@77g2000hsv.googlegroups.com> Message-ID: On 2007-01-11, Rich wrote: > I want to run an external program using os.system() but I want to > include a variable in the middle of the command line. > > An example of the type of thing I want to be able to do: > pathname = os.path.dirname(sys.argv[0]) > os.system('cscript /nologo ' + pathname + '\test.vbs') Use / instead of \, or \\ instead of \. -- Neil Cerutti Ushers will eat latecomers. --Church Bulletin Blooper From steve at REMOVEME.cybersource.com.au Mon Jan 29 20:59:39 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 30 Jan 2007 12:59:39 +1100 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170088693.768440.26580@h3g2000cwc.googlegroups.com> Message-ID: On Mon, 29 Jan 2007 08:38:13 -0800, Szabolcs Nagy wrote: >>> why use xrange? range is faster and simpler for small ranges That is not true. >>> import timeit >>> timeit.Timer("range(50)", "").repeat() [2.8599629402160645, 2.8296849727630615, 2.8609859943389893] >>> timeit.Timer("xrange(50)", "").repeat() [1.1806831359863281, 1.3563210964202881, 1.1632850170135498] >>> timeit.Timer("range(5)", "").repeat() [1.7963159084320068, 1.5487189292907715, 1.5596699714660645] >>> timeit.Timer("xrange(5)", "").repeat() [1.158560037612915, 1.1807279586791992, 1.1769890785217285] There is very little reason to use range() unless you actually need the entire list in one go. In fact, in Python 3.0, the existing range() will be removed and xrange() will be renamed range(). -- Steven D'Aprano From weekender_ny at yahoo.com Tue Jan 16 00:16:53 2007 From: weekender_ny at yahoo.com (John) Date: 15 Jan 2007 21:16:53 -0800 Subject: installing/maintaining modules for multiple versions of python Message-ID: <1168924613.732835.83570@l53g2000cwa.googlegroups.com> I have a suse box that has by default python 2.4 running and I have a 2.5 version installed in /reg/python2.5. How do I install new modules for only 2.5 without disturbing the 2.4 default installation. Thanks, --j From larry at hastings.org Wed Jan 10 19:40:40 2007 From: larry at hastings.org (Larry Hastings) Date: 10 Jan 2007 16:40:40 -0800 Subject: How to use Mercurial for local source code management with a public Subversion server Message-ID: <1168476040.459124.172200@77g2000hsv.googlegroups.com> I'm working on a patch or two for Python. Now, it's always best to use a source code manager (rcs, whatever) when writing code; in particular it'd make updating to the latest Python trees much easier. But I don't have write access to the Python Subversion repository. So I figured out how to work purely locally with Mercurial. I wrote a long(ish) how-to blog entry about it, . It's currently the top entry, here: http://www.momentaryfascinations.com/ Figuring out *how* to do it was the hard part; it's actually pretty easy to set up and use. And *very* pleasant to work with! If you're working on patches for Python, I highly recommend you work using something like this. (Maybe even if you *do* have write permission!) I considered posting this in the Python-Dev mailing list, as that's really the target audience, but I wasn't sure the message would be happily received by its subscribers. Cheers, /larry/ From karyn at calarts.edu Fri Jan 12 16:14:10 2007 From: karyn at calarts.edu (Karyn Williams) Date: Fri, 12 Jan 2007 13:14:10 -0800 Subject: What is a perl hash in python In-Reply-To: References: <8301441.post@talk.nabble.com> Message-ID: <3.0.1.32.20070112131410.015b67e0@muse.calarts.edu> At 06:54 PM 1/12/07 GMT, you wrote: >On Fri, 12 Jan 2007 09:15:44 -0800, Karyn Williams >declaimed the following in comp.lang.python: > >> I am new to Pyton. I am trying to modify and understand a script someone >> else wrote. I am trying to make sense of the following code snippet. I know > > "someone else" didn't write Python either, looking at that mishmash > Thanks, Marc and Dennis. Actually as I think about it, this operation should be able to be done in one loop, not the ten or so that it is currently taking. Read in a file "*.log" (excluding certain named files "1.log"), total up x number of rows of the 2nd and third columns, push (filename, total col2) (filename, total col 3) to two lists, sort -r and generate one web page each with the top ten. That is what this script is supposed to be doing. >> line 7 would be best coded with regex. I first would like to understand >> what was coded originally. thelistOut looks like a hash to me (I'm more >> familiar with perl). Perhaps someone could translate from perl to python >> for me - not in code but just in concept. >> >> >> Here is the code. This script is reading the list thelistOut and then >> removing any items in RSMlist and taking the remainder and putting them in >> graphAddressOut with the formatting. >> >> This is a SAMPLE of what is in the lists referenced below in the loop: >> >> >> thelistOut = [(632, >> ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_9.log']), (145, >> ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_13.log']), (0, >> ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_5.log'])] >> > > This is a list containing three elements. Each element is a tuple >containing two sub-elements. The first sub-element appears to be an >integer (I have no idea of the significance of the value at this time). >The second sub-element is another list containing a single >sub-sub-element -- that sub-sub-element is a string (file path name). > >> RSMList = ['172.16.0.1_1', '172.16.0.1_2', '172.16.0.1_3', '172.16.0.1_4', >> '172.16.0.1_5'] >> >> >> >> #--------------------------Loop 1 ------------------------- >> >> w = 0 >> while w < 45: >> > for w in xrange(45): > >> fileOut = string.split(thelistOut[w][1][0],".log") >> fileOutSplitedCommon = string.split(fileOut[0], "main/") >> fileOut2D = string.split(fileOutSplitedCommon[1], "/") >> fileOut = string.split(fileOut[0],"data-dist") >> > Direct use of the string module is now frowned upon. For future reference, why is direct use of the string module frowned upon, and what does one use instead ? >Also, since these are file path names, using operations in the os.path module would >be more appropriate... I'll look into os.path, but what this loop should be doing is matching and removing the entries from thelistOut ( and thelistIn ) that are listed in RSMlist. Or as is being done, not writing them to the new list, outputOut (graphAddressOut). Its just a matching operation, not really a path/filename op. This is why I will be changing this to a regex. >> if fileOut2D[1] in RSMList: >> w = w + 1 >> continue > > Confusing logic, having two places where "w" is incremented. Using a >"for" loop would mean neither increment statement is needed. Actually, >"w" isn't even needed, replace the while/for with > > for fid in thelistOut: > fileOut = fid[1][0] #that [1] is getting the second element of > >the tuple, and the [0] gets the string out of that list (why a list of >one element string data?) > >> graphAddressOut = tag1 + logUrl + fileOut[1] + extention1 + tag2 + >> "SWITCH: " + string.swapcase(fileOut2D[0]) + "  & >> nbsp;PORT ID: " + fileOut2D[1] + "
" + imgTitleTag + imgTag1 + >> logUrl + fileOut[1] + extention2 + imgTag2 + tag3 + tag5 > > This could be cleaned up too, but I'll ignore it at the moment. > >> outputOut.append(graphAddressOut) >> strOut = strOut + graphAddressOut >> >> w = w + 1 >> >> #--------------------------Loop 1 ------------------------- > > > I think what you call a "hash" in PERL is a dictionary in Python: > >dct = { key1 : value1, ... , keyn : valuen } > >aval = dct[keyx] > > Nothing of the sort used in the code you show above. -- Karyn Williams Network Services Manager California Institute of the Arts karyn at calarts.edu http://www.calarts.edu/network From wpeloqui at gmail.com Thu Jan 18 20:44:30 2007 From: wpeloqui at gmail.com (Willie) Date: 18 Jan 2007 17:44:30 -0800 Subject: Using lambda with a Pmw.ComboBox In-Reply-To: References: <1169167034.200565.227900@a75g2000cwd.googlegroups.com> Message-ID: <1169171070.474661.9380@l53g2000cwa.googlegroups.com> I will post a sample tomorrow AM. James Stroud wrote: > Can you show us your code? Your question is ambiguous to me. Comboboxes > do not hold widgets but display text. From bj_666 at gmx.net Wed Jan 10 02:53:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 10 Jan 2007 08:53:17 +0100 Subject: Question: Best Practice? (module 'shelve') References: <45A438AE.10105@gmx.net> Message-ID: In , Thomas Ploch wrote: >> I just wanted to know, if there is any best practice concerning >> following code: >> >> [?] >> >> def match(self, src, url): >> self.matchDict = {} >> self.matchDict[url] = {} >> # The next 2 functions just add stuff to self.matchDict >> if self.email: >> self._addEmails(src, url) >> self._addPatterns(src, url) >> # Is it good practice to open, write and close the db straight >> # away? Or is it better to leave it open until the whole program >> # has finished, and close it then? >> self.openDB(self.dbName) >> self.db[url] = self.matchDict[url] >> self.db.close() >> # I want to del the matchDict each time so it can't grow big. >> # Is this good, or should it be left open, too? >> del self.matchDict Opening an closing the DB costs time but makes sure everything is flushed to the file. At least from the applications point of view. The data may be still cached by the operating system before actually being written to the file. Do you have `self.matchDict` just for communicating between those two methods? Why don't you use arguments and return values and a local name? def match(self, src, url): match_dict = dict() if self.email: match_dict.update(self._add_emails(src, url)) match_dict.update(self._addPatterns(src, url)) self.open_db() self.db[url] = match_dict self.db.close() It's a bit shorter and `match_dict` goes out of scope automatically when the method finishes. Clearing `self.matchDict` doesn't buy you much anyway. At least not what the comment suggests because it doesn't grow anymore after the end of the method. The first action in the next call is binding the attribute to a fresh dictionary. >> def openDB(self, dbName=None, modeflag='c'): >> if dbName == None: >> self.db = shelve.open('textmatch.db', flag=modeflag) >> else: >> self.db = shelve.open(dbName, flag=modeflag) def open_db(self, db_name='textmatch.db', modeflag='c'): self.db = shelve.open(db_name, flag=modeflag) Ciao, Marc 'BlackJack' Rintsch From oyekomova at hotmail.com Sun Jan 14 12:56:34 2007 From: oyekomova at hotmail.com (oyekomova) Date: 14 Jan 2007 09:56:34 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168715634.695961.14710@l53g2000cwa.googlegroups.com> <1168728465.178605.218850@q2g2000cwa.googlegroups.com> <1168735174.140171.74930@v45g2000cwv.googlegroups.com> <1168756624.569930.168990@51g2000cwl.googlegroups.com> Message-ID: <1168797394.119395.303060@q2g2000cwa.googlegroups.com> Thank you so much. Your solution works! I greatly appreciate your help. sturlamolden wrote: > oyekomova wrote: > > > Thanks for your note. I have 1Gig of RAM. Also, Matlab has no problem > > in reading the file into memory. I am just running Istvan's code that > > was posted earlier. > > You have a CSV file of about 520 MiB, which is read into memory. Then > you have a list of list of floats, created by list comprehension, which > is larger than 274 MiB. Additionally you try to allocate a NumPy array > slightly larger than 274 MiB. Now your process is already exceeding 1 > GiB, and you are probably running other processes too. That is why you > run out of memory. > > So you have three options: > > 1. Buy more RAM. > > 2. Low-level code a csv-reader in C. > > 3. Read the data in chunks. That would mean something like this: > > > import time, csv, random > import numpy > > def make_data(rows=6E6, cols=6): > fp = open('data.txt', 'wt') > counter = range(cols) > for row in xrange( int(rows) ): > vals = map(str, [ random.random() for x in counter ] ) > fp.write( '%s\n' % ','.join( vals ) ) > fp.close() > > def read_test(): > start = time.clock() > arrlist = None > r = 0 > CHUNK_SIZE_HINT = 4096 * 4 # seems to be good > fid = file('data.txt') > while 1: > chunk = fid.readlines(CHUNK_SIZE_HINT) > if not chunk: break > reader = csv.reader(chunk) > data = [ map(float, row) for row in reader ] > arrlist = [ numpy.array(data,dtype=float), arrlist ] > r += arrlist[0].shape[0] > del data > del reader > del chunk > print 'Created list of chunks, elapsed time so far: ', time.clock() > - start > print 'Joining list...' > data = numpy.empty((r,arrlist[0].shape[1]),dtype=float) > r1 = r > while arrlist: > r0 = r1 - arrlist[0].shape[0] > data[r0:r1,:] = arrlist[0] > r1 = r0 > del arrlist[0] > arrlist = arrlist[0] > print 'Elapsed time:', time.clock() - start > > make_data() > read_test() > > This can process a CSV file of 6 million rows in about 150 seconds on > my laptop. A CSV file of 1 million rows takes about 25 seconds. > > Just reading the 6 million row CSV file ( using fid.readlines() ) takes > about 40 seconds on my laptop. Python lists are not particularly > efficient. You can probably reduce the time to ~60 seconds by writing a > new CSV reader for NumPy arrays in a C extension. From fuzzyman at gmail.com Sat Jan 20 20:46:30 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 20 Jan 2007 17:46:30 -0800 Subject: Py 2.5 on Language Shootout In-Reply-To: References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> Message-ID: <1169343990.225580.227070@s34g2000cwa.googlegroups.com> Carl Friedrich Bolz wrote: > pgarrone at acay.com.au wrote: > >>> Looking over the benchmarks, one gains the impression that Python is a > >>> slow language. > >> What does that even mean - a slow language? > >> > > > > The alioth benchmarks provide a set of numbers by which > > languages may be compared. > > Wrong. The benchmarks provide a set of numbers by which > _implementations_ of languages can be compared. After all, it is > possible that someone implements a magic-pixie-dust-interpreter that > executes Python programs several orders of magnitude fastes than > CPython. Or you could say that C is slow because if you use CINT, a C > interpreter ( http://root.cern.ch/root/Cint.html ) to execute it, it is > slow. If you rephrase your argument to read 'it is never useful to discuss the comparative speed of langauges' then hopefully the error should be obvious. But then to discuss the speed of languages rather than implementations would be a generalisations, and generalisations are always wrong... ;-) Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > > Cheers, > > Carl Friedrich Bolz From deets at nospam.web.de Tue Jan 9 02:55:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Jan 2007 08:55:25 +0100 Subject: Colons, indentation and reformatting. (2) In-Reply-To: <1168327796.187713.107530@38g2000cwa.googlegroups.com> References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> <45a33a24$0$7658$4c368faf@roadrunner.com> <1168327796.187713.107530@38g2000cwa.googlegroups.com> Message-ID: <50h03hF1fgnbpU1@mid.uni-berlin.de> > Won't the following rules work when pasting complete Python statements > and complete lines, after other lines in an editor: > > lets call the line after which the block is to be pasted the paste > line, and the original indent of the first line of the copied block to > be pasted the copy indent. > > If the paste line ends in a colon then the copy indent must be greater > than the paste line indent, or the copy block should be re-indented on > pasting to make it so. > If the paste line does not end in a colon then the copy block indent > should be equal too or less than the paste line indent. If this is not > the case then the user should be asked wether to re-indent the copy > block to be equal to, or de-dented w.r.t. the paste line indent prior > to pasting. Could be done that way - but is it a killer feature? I doubt it, but maybe you convince somebody to implement it. Yet it certainly doesn't justify a wikipedia edit - the FAQ entry is right, and there is no way of auto-indenting python code that for some reason suffered from indention mix-up. Diez From basti.wiesner at gmx.net Wed Jan 3 09:45:37 2007 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Wed, 03 Jan 2007 15:45:37 +0100 Subject: function without brackets ? References: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> Message-ID: Stef Mientki typed > If I call a parameterless function without brackets at the end, > the function is not performed, but ... If you omit the brackets, you don't actually call the function. Instead you get a reference to the function object. Consider this example: cwd = os.getcwd() # cwd now contains a string, denoting the current working directory func = os.getcwd # func now contains a reference to the function os.getcwd print func == os.getcwd # prints True # you can even call it: cwd_2 = func() # cwd_2 now also contains a string with the current directory. print cwd == cwd_2 # prints True, too -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From jhefferon at smcvt.edu Mon Jan 29 21:01:56 2007 From: jhefferon at smcvt.edu (Jim) Date: 29 Jan 2007 18:01:56 -0800 Subject: error messages containing unicode Message-ID: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> Hello, I'm trying to write exception-handling code that is OK in the presence of unicode error messages. I seem to have gotten all mixed up and I'd appreciate any un-mixing that anyone can give me. I'm used to writing code like this. class myException(Exception): pass fn='README' try: f=open(fn,'r') except Exception, err: mesg='unable to open file'+fn+': '+str(err) raise myException, mesg But what if fn is non-ascii? The following code raises the dreaded (to me) UnicodeEncodeError. class myException(Exception): pass def fcnCall(): fn=u'a\N{LATIN SMALL LETTER O WITH DIAERESIS}k' try: # was: f=open(fn,'r') 2/0 # just substitute something that will raise an exception except Exception, err: mesg='unable to open file '+fn+': '+str(err) raise myException, mesg try: fcnCall() except Exception, err: print 'trouble calling fcnCall: '+str(err) Maybe my trouble is the "str()", which is supposed to return a regular string? (BTW, unicode() makes no difference, and help(BaseException) didn't give me any inspirations.) So I looked for an end-around past the str() call. As I understand lib/module-exceptions.html, "For class exceptions, [err] receives the exception instance. If the exception class is derived from the standard root class BaseException, the associated value is present as the exception instance's args attribute.", I should be able to get the string out of err.args. Sure enough, putting the above text into test.py and changing str(err) to repr(err.args) yields this. $ python test.py trouble calling fcnCall: (u'unable to open file a\xf6k: integer division or modulo by zero',) so that changing the above repr(err.args) to err.args[0] gives the desired result. $ python test.py trouble calling fcnCall: unable to open file a?k: integer division or modulo by zero (In case this doesn't show up as I intended on your screen, I see an o with a diaeresis in the filename.) But the documentation "This may be a string or a tuple containing several items of information (e.g., an error code and a string explaining the code)." gives me no reason to believe that all exceptions have the desired unicode string as the 0-th element of the tuple. I confess that I'm unable to confidently read exceptions.c . No doubt I've missed something (I googled around the net and on this group but I didn't have any luck). I'd be grateful if someone could show me striaght. Thanks, Jim From gagsl-py at yahoo.com.ar Sun Jan 28 23:38:39 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Jan 2007 01:38:39 -0300 Subject: Convert from unicode chars to HTML entities References: Message-ID: En Mon, 29 Jan 2007 00:05:24 -0300, Steven D'Aprano escribi?: > I have a string containing Latin-1 characters: > > s = u"? and many more..." > > I want to convert it to HTML entities: > > result => > "© and many more..." > Module htmlentitydefs contains the tables you're looking for, but you need a few transforms: # -*- coding: iso-8859-15 -*- from htmlentitydefs import codepoint2name unichr2entity = dict((unichr(code), u'&%s;' % name) for code,name in codepoint2name.iteritems() if code!=38) # exclude "&" def htmlescape(text, d=unichr2entity): if u"&" in text: text = text.replace(u"&", u"&") for key, value in d.iteritems(): if key in text: text = text.replace(key, value) return text print '%r' % htmlescape(u'hello') print '%r' % htmlescape(u'"?? ??&? ') Output: u'hello' u'"©® áé&ö <²³>' The result is an unicode object, with all known entities replaced. It does not handle missing, unknown entities - as the docs for htmlentitydefs say, "the definition provided here contains all the entities defined by XHTML 1.0 that can be handled using simple textual substitution in the Latin-1 character set (ISO-8859-1)." -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Sat Jan 6 17:27:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Jan 2007 23:27:10 +0100 Subject: still struggling, howto use a list-element as a name ? In-Reply-To: References: Message-ID: <45a01c05$0$319$426a74cc@news.free.fr> rzed a ?crit : (snip) > for k in self.pin.keys(): > self.__dict__[self.pin[k]['Name']] = self.pin[k] for pin self.pin.values(): self.__dict__[pin['name']] = pin From mail at microcorp.co.za Wed Jan 17 01:17:35 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 17 Jan 2007 08:17:35 +0200 Subject: Class data members in C References: Message-ID: <000201c73a17$b0125a00$03000080@hendrik> "Nick Maclaren" wrote: > > Hmm. The extensions documentation describes how to add instance > members to a class (PyMemberDef), but I want to add a class member. > Yes, this is constant for all instances of the class. > > Any pointers? When? - at time of defining base class, between class definition and first instance, at time of creating instance, or after instance creation? After instance creation is not easy, I think you would have to add to each instance... But then, I may be wrong - I often am. - Hendrik From jmike at alum.mit.edu Tue Jan 16 09:17:48 2007 From: jmike at alum.mit.edu (jmike at alum.mit.edu) Date: 16 Jan 2007 06:17:48 -0800 Subject: Command line arguments on Vista In-Reply-To: References: <1168613362.406648.304720@11g2000cwr.googlegroups.com> Message-ID: <1168957067.605303.179260@51g2000cwl.googlegroups.com> Thanks for the answers; that was the problem exactly. --JMike Duncan Booth wrote: > It sounds like the registry entry for running Python files is messed up. > Can you go to a command line and see what the command 'ftype Python.File' > displays? (Assuming that command lines and ftype still work on Vista) > > The output should be: > Python.File="C:\Python25\python.exe" "%1" %* > > but if it only says: > Python.File="C:\Python25\python.exe" "%1" > > then you would get the behaviour you observed (on any version of Windows, > not just Vista). From nil at dev.nul Fri Jan 12 11:51:11 2007 From: nil at dev.nul (Christian Stapfer) Date: Fri, 12 Jan 2007 17:51:11 +0100 Subject: 'LoadFile' not found when invoking Acrobat via wx.lib.pdfwin Message-ID: <4b3c7$45a7bd44$54482de3$30930@news.hispeed.ch> Hi, I get the following traceback when trying to have wx.lib.pdfwin.PDFWindow open a PDF file: E:\Tutoring\Teacher\Flashcards>python pdfwin1.py Traceback (most recent call last): File "pdfwin1.py", line 50, in OnOpenButton self.pdf.LoadFile(dlg.GetPath()) File "C:\Python24\lib\site-packages\wx-2.6-msw-unicode-enthought\wx\lib\pdfwin .py", line 34, in LoadFile return self.CallAXMethod('LoadFile', fileName) File "C:\Python24\lib\site-packages\wx-2.6-msw-unicode-enthought\wx\activex.py ", line 385, in CallAXMethod return self._CallAXMethod(name, args) File "C:\Python24\lib\site-packages\wx-2.6-msw-unicode-enthought\wx\activex.py ", line 378, in _CallAXMethod return _activex.ActiveXWindow__CallAXMethod(*args) KeyError: 'method not found' The code in pdfwin1.py is from http://www.daniweb.com/code/snippet618.html How could the ActiveX control PDFWindow possibly *not* find the 'LoadFile' method, I wonder. - Or am I misinterpreting the message? (I am running Enthought Python 2.4 on Windows XP.) Thank you in advance for any ideas as to what the problem might be, Christian From ljz at asfast.com Sat Jan 6 18:01:04 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Sat, 06 Jan 2007 18:01:04 -0500 Subject: Recommended way to force a thread context switch? References: <1168103258.602286.146100@42g2000cwt.googlegroups.com> <1168104008.910681.46800@38g2000cwa.googlegroups.com> Message-ID: <873b6nlpzj.fsf@asfast.com> Duncan Booth writes: > [ ... ] > > If the context isn't switching enough for you then try calling > sys.setcheckinterval(n) with varying values of n until you find one which > is suitable. Calling it with a lower value of n will increase the frequency > that you switch thread contexts, although of course it will also increase > the overall runtime for your program. Thank you very much. The sys.setcheckinterval function is what I need. It seems that the original writer of the app had set this interval to a high value in a part of the code that I overlooked until you mentioned this right now. > [ ... ] > > Why does it matter whether individual threads are being 'starved'? Surely > you want them all to complete in any case, so does it matter if they run > sequentially or in parallel? Because some of the threads perform monitoring and notification that need to occur in a timely fashion. Since these threads are doing IO, they switch context appropriately, but once one of the big number-crunching threads gets control, it starves out the monitoring threads, which is not a good thing for my app ... or at least it did so with the original large checkinterval. -- Lloyd Zusman ljz at asfast.com God bless you. From rajsdrster at gmail.com Mon Jan 1 15:14:59 2007 From: rajsdrster at gmail.com (rajs) Date: 1 Jan 2007 12:14:59 -0800 Subject: Online Books Message-ID: <1167682499.685563.286510@h40g2000cwb.googlegroups.com> http://languages-books.yourlib.com/index.html From goodidea1950 at hotmail.spam.com Sun Jan 28 22:35:09 2007 From: goodidea1950 at hotmail.spam.com (AKA gray asphalt) Date: Sun, 28 Jan 2007 19:35:09 -0800 Subject: Do I need Python to run Blender correctly? References: <5%4uh.75582$wP1.6882@newssvr14.news.prodigy.net> <9TYuh.3468$4W5.752@newsfe10.phx> Message-ID: I think you're right. I'll find a blender forum. Thanks for your help. : -) "John Nagle" wrote in message news:B47vh.66904$qO4.21051 at newssvr13.news.prodigy.net... > AKA gray asphalt wrote: >> "John Nagle" wrote in message >> news:ssTuh.36083$QU1.26111 at newssvr22.news.prodigy.net... > >> Is the manual you refer to the group project on blender.org or the $ >> manual like the one on Ebay? >> > The "Blender 2.3 Guide" book. Also, if you're going to program the > thing, > the "Blender GameKit" book is a big help. > > Unless you have two screens, the online manual gets in your way. > > This really should go in a Blender newsgroup or forum. > > John Nagle From dummy at dummy.nl Thu Jan 18 10:16:35 2007 From: dummy at dummy.nl (Cecil Westerhof) Date: Thu, 18 Jan 2007 16:16:35 +0100 Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> Message-ID: <45af8f52$0$339$e4fe514c@news.xs4all.nl> Gabriel Genellina wrote: > "Cecil Westerhof" escribi? en el mensaje > news:45af6f47$0$322$e4fe514c at news.xs4all.nl... > >>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse >>I >> can not time the time used to import time, but os and sys do not take >> more as a millisecond. My script itself takes 3 or 4 milliseconds. But >> importing >> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is >> there a way to make this more fast? The import off cgi makes the script >> at least 20 times as slow. Something like mod-python is not a >> possibility. I could use it on my test machine, but not at the osting >> provider. > Surely os was imported earlier, and was already loaded. sys is a builtin > module. But I think your problem is not how much time takes importing cgi, > but how much time takes launching a new python process on each request. Nope, it was certainly cgi. When I fetch time after importing and after the script finishes, the difference is 4 milliseconds. If I import the modules apart from cgi after I fetch the first time, there is added about 1 millisecond to the difference. When I also import cgi after taking the time, the difference grows with 95 milliseconds. So for one reason ore another, cgi is very expensive. From hg at nospam.org Fri Jan 5 05:15:28 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 11:15:28 +0100 Subject: importing / loading a module / class dynamically References: Message-ID: Laszlo Nagy wrote: > >> Thanks, >> >> What I am doing is adding plugin support to PyCrust ... so I'm looking >> for a mechanism where anyone can develop a plugin and have it loaded by >> pycrust. >> >> the .py was a typo >> >> >> why the "...Have at least an empty plugin/name1/__init__.py file..." ? >> > When you do > > import plugins.name1.name1 > > then "plugins" and "plugins/name1" should be a package, not a module. A > package is a special directory that contains package initialization code > in a __init__.py file. If you do not have the file, then the "plugins" > directory will be only a directory, and it cannot be imported. > > For details, see: > > http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > > Laszlo Many thanks Laszlo, it looks like I got it to work ... result will be on www.snakecard.com/PY for those interested ... in the next few days hg From fsck_spam at telenet.be Tue Jan 16 17:49:40 2007 From: fsck_spam at telenet.be (Rikishi 42) Date: Tue, 16 Jan 2007 23:49:40 +0100 Subject: Making a simple script standalone Message-ID: <5d1084-5j7.ln1@whisper.very.softly> Hi, I'm new to this group. I've tried finding my answer in existing messages, but no such luck. What I want to do is to compile/bundle/prepare/whatever_term a simple Python script for deployment on a Windows machine. Installing Python itself on that machine, is not an option. Ideally I would like to obtain a single executable file, but a script+runtime is acceptable. There is nothing graphical, nothing fancy about the script. The only imports are: os, stat, string and time. Any suggestions on an - easy and clear - path to follow ? -- Research is what I'm doing, when I don't know what I'm doing. (von Braun) From bj_666 at gmx.net Fri Jan 5 13:06:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 05 Jan 2007 19:06:59 +0100 Subject: Encoding / decoding strings References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> <1168010144.000928.131920@42g2000cwt.googlegroups.com> <1168018757.397170.216870@11g2000cwr.googlegroups.com> Message-ID: In <1168018757.397170.216870 at 11g2000cwr.googlegroups.com>, oliver at obeattie.com wrote: > Basically, what I am trying to do is display all comments by a > specified user on the website. As the only thing which has =always= > been used to identify users which never changes is their e-mail > addresses, this is the only thing which I can use. Obviously, I can't > display this e-mail address though. Associate a unique random number or string with each e-mail address and use this outside the server to identify users. An MD5 hash of the mail address might be a good candidate for such a string but then it's possible for attackers to verify if someone they know the address of, has made specific comments. So part of the anonymity is gone then. Ciao, Marc 'BlackJack' Rintsch From lrahuel.notgood at voila.fr Mon Jan 15 05:18:28 2007 From: lrahuel.notgood at voila.fr (Laurent Rahuel) Date: Mon, 15 Jan 2007 11:18:28 +0100 Subject: getting the name of hyperlinks in a file References: <1168619296.006209.298990@s34g2000cwa.googlegroups.com> Message-ID: <45ab54f5$0$5087$ba4acef3@news.orange.fr> Hi, I guess you should take a look at BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/). And take a clooser look at the findAll method. http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20basic%20find%20method %20findAll(name,%20attrs,%20recursive,%20text,%20limit,%20**kwargs) Regards, Laurent CSUIDL PROGRAMMEr wrote: > folks, > I am trying to write a script that would open a download server and > download all the files and store them in a list > > for example Download server is > http://download.fedora.redhat.com/pub/fedora/linux/core/updates/5/SRPMS/ > > > is there any way this can be done in python?? From gert.cuykens at gmail.com Sun Jan 21 21:31:05 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Mon, 22 Jan 2007 03:31:05 +0100 Subject: instancemethod In-Reply-To: References: Message-ID: never mind i think i need some sleep lol i did the exact opposite this time .rowcount() -> .rowcount From duncan.booth at invalid.invalid Tue Jan 16 07:41:44 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jan 2007 12:41:44 GMT Subject: Anyone has a nice "view_var" procedure ? References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> Message-ID: Neil Cerutti wrote: > dir( [object]) > > [...] The list is not necessarily > complete. If the object is a module object, the list contains > the names of the module's attributes. If the object is a type > or class object, the list contains the names of its attributes, > and recursively of the attributes of its bases. Otherwise, the > list contains the object's attributes' names, the names of its > class's attributes, and recursively of the attributes of its > class's base classes. The resulting list is sorted > alphabetically. [...] > > It's unclear to me what attributes an object could have that > aren't included in the above list. For a start the potentially infinite list of attributes handled by __getattr__ or __getattribute__: >>> class C(object): def __getattribute__(self, name): if name.startswith('weird'): return 42 >>> c = C() >>> c.weirdattribute 42 >>> dir(c) [] Any objects which are actually implemented as C extensions are quite likely to have attributes that dir() cannot see. From nospam at riddergarn.dk Tue Jan 30 14:07:50 2007 From: nospam at riddergarn.dk (Scripter47) Date: Tue, 30 Jan 2007 20:07:50 +0100 Subject: SQL connecting In-Reply-To: References: Message-ID: <45BF9786.4010309@riddergarn.dk> Dennis Lee Bieber skrev: > On Mon, 29 Jan 2007 19:45:47 GMT, John Nagle > declaimed the following in comp.lang.python: > >> Scripter47 wrote: >>> Hey >>> >>> It got a problem with python to connect to my SQL DBs, that's installed >>> on my apache server. how do i connect to sql? Gettting data? Insert into >>> it? >> You need a third-party open source package called "MySQLdb". >> > Call me a nit, but did the original poster mean "MySQL" databases, > or only that he uses SQL to access "my databases". The spelling is > unclear as to what DBMS engine is actually being used. If it is /not/ > MySQL, then MySQLdb is futile. Sry i didn't said it. it is a MySQL DB on a apache server From oyekomova at hotmail.com Wed Jan 10 14:48:06 2007 From: oyekomova at hotmail.com (oyekomova) Date: 10 Jan 2007 11:48:06 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> Message-ID: <1168458486.538863.316130@k58g2000hse.googlegroups.com> Thanks for your help. I compared the following code in NumPy with the csvread in Matlab for a very large csv file. Matlab read the file in 577 seconds. On the other hand, this code below kept running for over 2 hours. Can this program be made more efficient? FYI - The csv file was a simple 6 column file with a header row and more than a million records. import csv from numpy import array import time t1=time.clock() file_to_read = file('somename.csv','r') read_from = csv.reader(file_to_read) read_from.next() datalist = [ map(float, row[:]) for row in read_from ] # now the real data data = array(datalist, dtype = float) elapsed=time.clock()-t1 print elapsed Robert Kern wrote: > oyekomova wrote: > > I would like to know how to convert a csv file with a header row into a > > floating point array without the header row. > > Use the standard library module csv. Something like the following is a cheap and > cheerful solution: > > > import csv > import numpy > > def float_array_from_csv(filename, skip_header=True): > f = open(filename) > try: > reader = csv.reader(f) > floats = [] > if skip_header: > reader.next() > for row in reader: > floats.append(map(float, row)) > finally: > f.close() > > return numpy.array(floats) > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it had > an underlying truth." > -- Umberto Eco From bjourne at gmail.com Tue Jan 16 11:28:13 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 16 Jan 2007 17:28:13 +0100 Subject: Conflicting needs for __init__ method In-Reply-To: <874pqs7y7y.fsf@benfinney.id.au> References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <874pqs7y7y.fsf@benfinney.id.au> Message-ID: <740c3aec0701160828k1cf64681t3d663a4310f0d339@mail.gmail.com> On 1/15/07, Ben Finney wrote: > The alternate constructors are decorated as '@classmethod' since they > won't be called as instance methods, but rather: > > foo = Rational.from_string("355/113") > bar = Rational.from_int(17) > baz = Rational.from_rational(foo) I agree with you that that method is the right approach. But you can also use module level functions, and sometimes that is even better: def from_string(str): (n, d) = parse_elements_of_string_input(str) return Rational(n, d) That way, you do not even have to expose the class at all to users of the module. I think it depends on how you want users to use your module. If you prefer: import rational rat = rational.from_string("123/456") Then module level functions is best. But if you prefer: from rational import Rational rat = Rational.from_string("123/456") class methods are better. -- mvh Bj?rn From kevin.bell at slcgov.com Fri Jan 26 09:30:50 2007 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Fri, 26 Jan 2007 07:30:50 -0700 Subject: Win XP "Sleep" mode: can Py wake up? Message-ID: <2387F0EED10A4545A840B231BBAAC722F117C8@slcimail1.slcgov.com> Does anyone have any experience having python deal with sleep mode? I'd love to run something that would hear a sleep event coming and pickle some data before sleep, then after coming out of sleep, unpickle... Any thoughts? From smusnmrNOSPAM at yahoo.com Mon Jan 15 06:20:44 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Mon, 15 Jan 2007 12:20:44 +0100 Subject: python and MOV or MPEG References: <510uf3F1i9oo6U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > siggi wrote: > >> Hi all, >> >> does Python support MPEG or MOV videoclips? I couldn't find anything >> about it online. > > Weak in googling today? Must have been a rough weekend. > > There are several options, including pymedia and pygame. > > Diez Thanks, Diez. I forgot to mention that I am learning Python with python 2.5 on WinXP. And both pymedia and pygame require somewhat older versions of python, 1.3 and 2.4, respectively. And the updated binaries are still in the offing. I was naive enough to think MPEG could be done using modules already existing. siggi From arkanes at gmail.com Tue Jan 23 15:13:55 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 23 Jan 2007 14:13:55 -0600 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <1169582795.882496.209750@a75g2000cwd.googlegroups.com> References: <45b6231b$1_2@news.bluewin.ch> <1169582795.882496.209750@a75g2000cwd.googlegroups.com> Message-ID: <4866bea60701231213k1b2458f3uea41b0de42e4dce9@mail.gmail.com> On 23 Jan 2007 12:06:35 -0800, imageguy wrote: > > I am trying to use UI Automation to drive an MS Windows app (with pywinauto). > > > > I need to scrape the app's window contents and use some form of OCR to get at > > the texts (pywinauto can't get at them). > > > > As an alternative to integrating an OCR engine, and since I know the fonts and > > sizes used to write on the app's windows, I reasoned that I could base a simple > > text recognition module on the capability to drive MSWindows text rendering - eg > > to generate pixmaps of texts I expect to find in the driven app's windows, exact > > to the pixel. > > > > The advantage of that approach would be exactitude and self-containment. > > > > I've verified manually inside an Idle window, that indeed I could produce > > pixmaps of expected app texts, exact to the pixel (with Tkinter+screen capture > > at least). > > > > I could use help to turn this into a programmable capability, ie : A simple - > > with Tkinter or otherwise - way to wrap access to the MS Windows UI text > > rendering engine, as a function that would return a picture of rendered text, > > given a string, a font, a size and colors ? > > > > And ideally, without interfering with screen contents ? > > > > Thanks in advance for any guidance, > > > > Boris Borcic > > I was looking for ( and still am searching for) similiar functionality. > Specifically I would like to be able to capture a small area of the > screen (a number or a code) and convert this to text that can be used > in my application. > > When I asked my question, I was directed to the Microsoft Accessibility > tool kit. > Serach on this list for the post titled; > "Reading text labels from a Win32 window" > > I work with wxPython and Win32 applications exclusively. > > So if I can be of any help or assistance, please let me know. > > Geoff. > The OP stated that pywinauto couldn't get at the text, so it's probably drawn directly with GDI methods rather than being a static text control. The accessibility toolkit only works if it's a static text control or the application goes to some lengths to expose the text to screen readers. From exarkun at divmod.com Fri Jan 12 09:51:32 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 12 Jan 2007 09:51:32 -0500 Subject: context managers and generators In-Reply-To: <1168611420.448058.163860@11g2000cwr.googlegroups.com> Message-ID: <20070112145132.11447.624895917.divmod.quotient.14256@ohm> On 12 Jan 2007 06:17:01 -0800, bob.sidebotham at gmail.com wrote: >I'm happily using context managers and co-routines, and would like to >use both at the same time, e.g. Python has generators, not co-routines. > > with foo(): > ... > x = yield y > ... > >In this code multiple copies of this code can be executing at the >"same" time, interleaved by the yield statement. This doesn't work >well, since the context manager is dealing with global state >(specifically, re-routing stdout). > >The problem is that all of my state (local variables, etc.) is nicely >saved over the yield, but the context is not. So I end up having to >write the code like this: > > with foo(): > ... > x = yield y > with foo(): > ... > >which is not so pretty. What I'd like is some way to transparently save >and restore context over a yield, but I don't see an easy way to do >this. Wrap the generator in a function which co-operates with your context managers to clean-up or re-instate whatever they are interacting with whenever execution leaves or re-enters the generator. Jean-Paul From gagsl-py at yahoo.com.ar Sun Jan 7 15:44:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 12:44:36 -0800 Subject: Capturing stderr and stdout of a subprocess as a single stream In-Reply-To: <1168202227.147827.294910@s80g2000cwa.googlegroups.com> References: <1168198435.629380.136080@42g2000cwt.googlegroups.com> <1168201039.867515.35300@38g2000cwa.googlegroups.com> <1168202227.147827.294910@s80g2000cwa.googlegroups.com> Message-ID: <1168202676.409477.50540@42g2000cwt.googlegroups.com> On 7 ene, 17:37, "Fuzzyman" wrote: > Two threads and a queue sounds horrible. But unfortunately it's the only way if you don't control how the child process behaves. (It's not soooo ugly afterwards... certainly would be worse if you had to syncronize both reading threads and the display thread using semaphores by hand.) -- Gabriel Genellina From olsonas at gmail.com Mon Jan 29 16:13:12 2007 From: olsonas at gmail.com (Drew) Date: 29 Jan 2007 13:13:12 -0800 Subject: List Behavior when inserting new items In-Reply-To: <45be5fa3$0$1529$426a34cc@news.free.fr> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> <45be5fa3$0$1529$426a34cc@news.free.fr> Message-ID: <1170105192.167359.265520@s48g2000cws.googlegroups.com> > > Is there any way to produce this kind of behavior easily?Hints: > >>> [None] * 5 > [None, None, None, None, None] > >>> [1, 2, 3, None] + [10] > [1, 2, 3, None, 10] > > HTH That is exactly what I was looking for. I'm actually working on some problems at http://codgolf.com. I find it helps me to learn a language and I'm coming from ruby where arrays have subtle differences from python's lists. Thanks for all the helpful responses. From shejo284 at gmail.com Fri Jan 5 03:49:07 2007 From: shejo284 at gmail.com (Sheldon) Date: 5 Jan 2007 00:49:07 -0800 Subject: PyType_IsSubtype () Message-ID: <1167986947.735415.99970@s34g2000cwa.googlegroups.com> Hi, Can anyone tell me what this error mean: #0 0x4008376e in PyType_IsSubtype () from /usr/lib/libpython2.3.so.1.0 The core file backtrace can be found below. I am using Numeric and Python2.3 on a Linux OS. Any help is appreciated! ********************************* Core was generated by `/usr/bin/python msgppscomp.py'. Program terminated with signal 11, Segmentation fault. warning: current_sos: Can't read pathname for load map: Input/output error Symbols already loaded for /usr/lib/libpython2.3.so.1.0 Symbols already loaded for /lib/tls/libpthread.so.0 Symbols already loaded for /lib/libdl.so.2 Symbols already loaded for /lib/libutil.so.1 Symbols already loaded for /usr/lib/libstdc++.so.5 Symbols already loaded for /lib/tls/libm.so.6 Symbols already loaded for /lib/libgcc_s.so.1 Symbols already loaded for /lib/tls/libc.so.6 Symbols already loaded for /lib/ld-linux.so.2 Symbols already loaded for /usr/lib/python2.3/site-packages/Numeric/multiarray.so Symbols already loaded for /usr/lib/python2.3/site-packages/Numeric/_numpy.so Symbols already loaded for /usr/lib/python2.3/site-packages/Numeric/umath.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/strop.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/math.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/struct.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/binascii.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/cStringIO.so Symbols already loaded for /usr/lib/python2.3/site-packages/Numeric/ranlib.so Symbols already loaded for /usr/lib/python2.3/site-packages/Numeric/lapack_lite.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/time.so Symbols already loaded for /data/proj_ns1/safworks/sheldon/MSG_PPS_COMP/c_codes/msgppsarea.so Symbols already loaded for /usr/lib/libhdf5.so.0 Symbols already loaded for /lib/libz.so.1 Symbols already loaded for /usr/lib/python2.3/lib-dynload/cPickle.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/_bsddb.so Symbols already loaded for /usr/lib/libdb-4.1.so Symbols already loaded for /usr/lib/python2.3/lib-dynload/gdbm.so Symbols already loaded for /usr/lib/libgdbm.so.2 Symbols already loaded for /usr/lib/python2.3/lib-dynload/dbm.so #0 0x4008376e in PyType_IsSubtype () from /usr/lib/libpython2.3.so.1.0 ********************************************************************************** /Sheldon From wccppp at gmail.com Thu Jan 4 01:18:29 2007 From: wccppp at gmail.com (wcc) Date: 3 Jan 2007 22:18:29 -0800 Subject: where to ask questions related to comtypes? Message-ID: <1167891509.842292.125420@i80g2000cwc.googlegroups.com> Hello group, Is there a separate mailing list for comtypes? Or this is the appropriate place to post questions related to this package(from Thomas Heller)? Thanks, -- wcc From dubrovsky at physics.uq.edu.au Tue Jan 16 23:10:31 2007 From: dubrovsky at physics.uq.edu.au (Alejandro Dubrovsky) Date: Wed, 17 Jan 2007 14:10:31 +1000 Subject: How can I write code using FP References: <1169003899.592015.300290@s34g2000cwa.googlegroups.com> Message-ID: kernel1983 wrote: > In Function Program?Language can use like this: > > define a function: > f = lambda x,y:x,y > > then we use f to define another function: > f2 = f(1) > the f2 should equal to: > f2=lambda y:1,y > > we should be able call f2 with one parameter:f2(2) > just return 1,2 > > but how can I implement the characteristic in Python??I think it could > do like this but HOW-TO? If you are using python 2.5, then you can use functools.partial, otherwise lookup one of the many curry implementations, like the ones found in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 One found in the comments of that page by Scott David Daniels: def curry(*args, **kwargs): function, args = args[0], args[1:] def result(*rest, **kwrest): combined = kwargs.copy() combined.update(kwrest) return function(*args + rest, **combined) return result so, in your case: f = lambda x,y: (x,y) f2 = functools.partial(f,1) >>> f2(3) 1,3 From nmm1 at cus.cam.ac.uk Sun Jan 14 08:21:39 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jan 2007 13:21:39 GMT Subject: Fixed-point [was Re: Rational Numbers] References: Message-ID: In article , "Hendrik van Rooyen" writes: |> |> Ok I will throw in a skewed ball at this point - use integer arithmetic, |> and work in tenths of cents or pennies or whatever, and don't be too |> lazy to do your own print formatting... If anyone is interested in doing this, here are a few notes on some of the non-trivial aspects. Please feel free if you want to contact me for more information. All numbers are held as (precision, value). Precision is the number of digits after the decimal point (a small, often constant, integer) and the value is held as an integer. It would be possible to have a separate subclass or context for every precision (like Decimal), but that would be an unnecessary complication. +, - and % return a precision that is the maximum of their input precisions, and // returns a precision of 0. * returns a precision that is the sum of its input precisions. / returns a floating-point number! There is a divide function that takes a divisor, dividend and output precision. It also takes a rounding rule as an optional argument (up, down, in, out, conventional nearest or IEEE 754R nearest). There is a precision conversion function that takes a value and output precision, and a rounding rule as an optional argument. There is a conversion function that takes a string or floating-point number and output precision, and a rounding rule as an optional argument. It raises an exception if a 1 ULP change in the floating- point number would give a different answer; this is needed to make certain operations reliable. The default formatting does the obvious thing :-) Er, that's about it .... Regards, Nick Maclaren. From bignose+hates-spam at benfinney.id.au Sat Jan 20 02:13:46 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 Jan 2007 18:13:46 +1100 Subject: OT Annoying Habits References: <01bc01c73c5f$75e8cfe0$03000080@hendrik> Message-ID: <87zm8e2ms5.fsf@benfinney.id.au> "Hendrik van Rooyen" writes: > "Steven D'Aprano" wrote: > > > .snoitnevnoc > > hsilgnE tpada )ylbissop revenehw( dluohs ew os dna ,naitraM ton ,puorgswen > > egaugnal hsilgnE na no er'ew ,segaugnal hcus era ereht fi neve tuB > > First I thought it was Welsh or Cornish or something. > > Then it was like being in my first year of school again- > reading letter by letter. Never realised how difficult it is. > > I suppose it will improve with practice. Alternatively, you could consider it to be an active impediment to understanding, which, no matter how convenient it may be for the person writing it, is against the norms of written English and inconsiderate of the reader. With that in mind, you might convince those who write their messages that way to conform to the norms of written English for the sake of communication. -- \ "No wonder I'm all confused; one of my parents was a woman, the | `\ other was a man." -- Ashleigh Brilliant | _o__) | Ben Finney From scottballard at hotmail.com Tue Jan 23 16:08:57 2007 From: scottballard at hotmail.com (Scott Ballard) Date: Tue, 23 Jan 2007 13:08:57 -0800 Subject: newbie question: ftp.storbinary() Message-ID: Sorry for the lame question, I'm still trying to pick up Python and new to the list here. Question: I'm trying to write a python script that will access an FTP site and upload some files. I've gotten everything working except for the actual uploading of the files. I'm assuming that I should use storbinary( command, file[, blocksize]) to transfer the files. the documentation says "command should be an appropriate "STOR" command: "STOR filename"." I can't seem to figure out an `appropriate "STOR" command' is??? Thank for reading my post. Cheers, Scott From martin at v.loewis.de Wed Jan 3 14:08:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 20:08:58 +0100 Subject: type classobj not defined? In-Reply-To: References: Message-ID: <459BFF4A.6020002@v.loewis.de> Wesley Brooks schrieb: >> type(b) == classobj > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'classobj' is not defined > > For the time being I'll use b.__name__ == b to ensure I'm getting the > right class. Is there a reason why the other types such as bool are > defined but classobj isn't? In general, only those types which you also use as constructors are builtin. I.e. you would write bool(foo) (where foo is a variable), but you would not write classobj("bar") (to create a class named "bar"). That you can also use it for a type test is a side-effect. Some more types are available in the types module. In this case, you can use types. In this case, types.ClassType would do the trick. Regards, Martin From icius at comcast.net Sun Jan 21 16:55:04 2007 From: icius at comcast.net (icius) Date: 21 Jan 2007 13:55:04 -0800 Subject: SOAPpy and ArrayOfString In-Reply-To: <1169367091.902030.197480@m58g2000cwm.googlegroups.com> References: <1169367091.902030.197480@m58g2000cwm.googlegroups.com> Message-ID: <1169416504.095288.189960@51g2000cwl.googlegroups.com> Figured it out. This works: #!/usr/bin/python import SOAPpy wsdlFile = 'http://localhost:8080/axis/services/USD_R11_WebService?WSDL' server = SOAPpy.WSDL.Proxy(wsdlFile) server.soapproxy.config.dumpSOAPOut = 1 server.soapproxy.config.dumpSOAPIn = 1 SID = server.login('srvcdesk', 'xxxxxxxxx') attr = SOAPpy.structType() attr._addItem('string', 'userid') attr._addItem('string', 'last_name') attr._addItem('string', 'first_name') contacts = server.doSelect(SID, 'cnt', "userid = 'srvcdesk'", 1, attr) print contacts server.logout(SID) The XML generated is very similar, but my web service seems to like this for some reason...weird. icius wrote: > Hello all, > > I am trying to use a web services API with Python and SOAPpy as a > client. Some of the method paramters in this web service's WSDL are > asking for an "ArrayOfString" type. Here is my code so far: > > #!/usr/bin/python > > from SOAPpy import WSDL > > wsdlFile = > 'http://localhost:8080/axis/services/USD_R11_WebService?WSDL' > > server = WSDL.Proxy(wsdlFile) > > server.soapproxy.config.dumpSOAPOut = 1 > server.soapproxy.config.dumpSOAPIn = 1 > > SID = server.login('srvcdesk', 'xxxxxxxx') > > contacts = server.doSelect(SID, 'cnt', "userid = 'abeju01'", 1, > ['last_name', 'first_name', 'userid']) > > > I tried using a simple Python list for the argument that wants > "ArrayOfString". Python generates the following XML for the last > argument of the "doSelect" command above: > > > last_name > first_name > userid > > > > The web service does not like this at all and returns the following > error: > > SOAPpy.Types.faultType: org.xml.sax.SAXException: Bad types (class [Ljava.lang.Object; -> class > usdjws65.ArrayOfString): > > > > I know in Perl I had to do some special gyrations to pass the right > structue for ArrayOfString to this same web service. Is there any way > to force a type in Python or any other ideas on how to do this? From zhzhao at cisco.com Tue Jan 2 12:02:17 2007 From: zhzhao at cisco.com (Jenny Zhao (zhzhao)) Date: Tue, 2 Jan 2007 09:02:17 -0800 Subject: Looking for python SIP/MGCP stacks Message-ID: <1ECA23B17E8AB54C859FA0449B729F0E03428702@xmb-sjc-235.amer.cisco.com> Thanks Anthony. I am wondering where I can get Divmod Sine and Shtoom. Are they open source ? Thanks again Jenny -----Original Message----- From: Anthony Baxter [mailto:anthonybaxter at gmail.com] Sent: Saturday, December 30, 2006 2:38 AM To: Jenny Zhao (zhzhao) Cc: python-list at python.org Subject: Re: Looking for python SIP/MGCP stacks > I am using python to write a testing tools, currently this tool only > supports skinny protocol. I am planning to add SIP and MGCP support as > well, wondering if you have written these protocol stacks before which > can be leveraged from. There's two I know of - shtoom and Divmod Sine. The latter is a more complete implementation of SIP and probably what you want to use. From tiedon_jano at hotmail.com Thu Jan 4 04:14:40 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Thu, 04 Jan 2007 09:14:40 GMT Subject: question on creating class In-Reply-To: <1167895677.041759.230190@42g2000cwt.googlegroups.com> References: <1167895677.041759.230190@42g2000cwt.googlegroups.com> Message-ID: <4A3nh.56$0c7.26@read3.inet.fi> wcc kirjoitti: > Hello, > > How do I create a class using a variable as the class name? > > For example, in the code below, I'd like replace the line > > class TestClass(object): > with something like > class eval(className) (object): > > Is it possible? Thanks for your help. > > className = "TestClass" > > class TestClass(object): > def __init__(self): > print "Creating object of TestClass..." > > def method1(self): > print "This is a method." > > if __name__ == "__main__": > o = TestClass() > o.method1() > > -- > wcc > I'm curious: what is the original problem that you are trying to solve? The following works, but note that I'm no Python expert and if any of the regular wizards around here says that doing these kind of things is sick, I'm gonna agree 100% ;) className = "TestClass2" class TestClass(object): def __init__(self): print "Creating object of TestClass..." def method1(self): print "This is a method." exec('class ' + className + '''(object): def __init__(self): print "Creating object of TestClass2..." def method1(self): print "This is a method1 of TestClass2." ''') if __name__ == "__main__": o = TestClass() o.method1() o2 = TestClass2() o2.method1() o2 = locals()[className]() o2.method1() From paddy3118 at netscape.net Sat Jan 20 17:11:10 2007 From: paddy3118 at netscape.net (Paddy) Date: 20 Jan 2007 14:11:10 -0800 Subject: Does eval has the same features as Perl's? In-Reply-To: References: Message-ID: <1169331070.665344.261280@a75g2000cwd.googlegroups.com> Jm lists wrote: > Hello members, > > I want to know does the "eval" in python have the same features as in > Perl (capture errors)? > > For example,in perl I can wrote: > > $re = eval { 1 / 0 }; > > Though 1/0 is a fatal error but since it's in "eval" block so the perl > interpreter doesn't get exit. > > Thanks again. Hi Jim, If your new to Python and coming from Perl then your question above needs knowledge of Python Exceptions, and the try statement. if you had variables x and y and wanted to compute x/y but if y was zero print some message and continue, then you would most likely do something like: x = 1 y = 0 try: z = x / y except ZeroDivisionError: print "This leads to a divide by zero error!" There is more info in the tutorial chapter 8. - Paddy. From bdesth.quelquechose at free.quelquepart.fr Wed Jan 24 16:12:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Jan 2007 22:12:58 +0100 Subject: Re-thinking my if-thens - a software engineering question In-Reply-To: <1169668287.517657.24450@l53g2000cwa.googlegroups.com> References: <1169668287.517657.24450@l53g2000cwa.googlegroups.com> Message-ID: <45b7c521$0$25888$426a74cc@news.free.fr> metaperl a ?crit : > Ok, I have a module called textgen.py. The point of this module is to > generate a csv file from an array of dictionaries. Err... You know there's a csv module in the stdlib, don't you ? > As I iterate through > each dictionary, I "massage" the dictionary values before writing them > out to csv. Now, for one dictionary entry, I have the following code: > > if dict_key == 'PCN': > fields = dict_val.split("/") > mo = re.match( '(\w{2})(\d{2})(\d{2})' , fields[1] ) > if mo: > dict_val = "%s/%s%s/%s" % (fields[0], mo.group(1), mo.group(3), > fields[2][1:]) > else: > dict_val = dict_val FWIW, you could as well skip this else clause > Ok, so now here is what has happened. This code was based on the > assumption that dict_val would have 2 forward slashes in it. It turns > out that I need to follow a different process of massaging when no > slashes are present. A naive solution would be something like: > > if dict_key == 'PCN': > fields = dict_val.split("/") > if fields == 3: if len(fields) == 3: > dict_val = pcn_three(fields) # where pcn_three > is the code above > else: > # new logic > > But I am wondering if I should abstract the flow of control into a > class or something. Depends... If your code is starting to smell, then yes, it's probably time to refactor a bit. Note that you don't necessarily needs OO to clean up a mess. Python functions are objects on their own, so you can use them like any other variable. A common idiom is to use a dict as a dispatch table: def test1(arg): print "test1", arg def test2(arg): print "test2", arg def test3(arg): print "test3", arg dispatch = { 'TEST_ONE': test1, 'TEST_TWO': test2, 'TEST_THREE': test3, } default = lambda arg: arg #... func = dispatch(dict_key) dict_val = func(fields) And using lambdas you can even come close to Perl !-) dispatch = { 'PCN' : lambda arg: \ (new_logic, pcn_three)[arg.count('/') == 2](arg.split('/')), 'XXX' : code_here, ... } Or you could write some "dispatcher helper" functions, like: def dispatch_on_arg_count(default, *funcs): def _dispatcher(*args): try: func = funcs[len(args)] except IndexError: func =default return func(*args) return _dispatcher dispatch = { 'PCN': dispatch_on_arg_count( default, default, pcn_one, pcn_two, pcn_three ), 'XXX' : code_here, } Or you could check Philip Eby's dispatch package... And of course, since Python classes are themselves callables (no 'new' operator, you just call the class to instanciate it), and instances can be callable too (just define a __call__(self, ...) method), you can throw OO in the mix too !-) Now weither it will make your code more readable is another question... > Ideas welcome. > HTH From mhellwig at xs4all.nl Thu Jan 18 05:09:49 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 18 Jan 2007 11:09:49 +0100 Subject: Would a Dutch speaker please check this wiki page please? In-Reply-To: References: Message-ID: <45af4735$0$322$e4fe514c@news.xs4all.nl> Stef Mientki wrote: > skip at pobox.com wrote: >> Got a note about a new page on the Python Wiki: >> >>>>>>> "Wade" == Wade McDaniel writes: >> >> http://wiki.python.org/moin/Selcuk_Altun >> >> I suspect it's junk since it doesn't seem to mention Python and the >> website >> it mentions doesn't seem to exist. Still, just in case... > The only (incorrect) Dutch sentence on the whole site is: > "Welkom op me site www.keriwar.nl", > which should have been > "Welkom op mijn site www.keriwar.nl" > but that could be explained, while his name "Selcuk Altun" is not > orginated from the Netherlands. > I just expect that he is trying to setup a wiki, > but that's too soon to give it a judgement. > > cheers, > Stef Mientki >> >> Thx, >> >> Skip Could be Afrikaans too, but the page is gone now so I can't check. -- mph From gagsl-py at yahoo.com.ar Thu Jan 25 19:31:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 21:31:30 -0300 Subject: MIME text attachment question In-Reply-To: References: Message-ID: <7.0.1.0.0.20070125212716.04421838@yahoo.com.ar> At Thursday 25/1/2007 08:41, Neal Becker wrote: >I want to send a file (plain text) as an attachment. > >I'm using MIMEText. This attaches text OK, but I would like to have a >filename attached to it, so that the recipient could save it without having >to specify a filename. part = MIMEText("Hello world!") part.add_header('Content-Disposition', 'attachment', filename='x.txt') -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Tue Jan 2 13:20:41 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Jan 2007 15:20:41 -0300 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167757137.942280.32270@42g2000cwt.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <1167757137.942280.32270@42g2000cwt.googlegroups.com> Message-ID: <7.0.1.0.0.20070102151720.05bfe578@yahoo.com.ar> At Tuesday 2/1/2007 13:58, Ben Sizer wrote: > > Notice that there is NO need to alter the system path. You just have > > to tell Windows where python.exe resides; there is a per-application > > path located at > > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths. > > >From what I can tell, that is solely for file associations. If so, it >will work if you type "setup.py install" but not if you type "python >setup.py install". For instance, I have an entry for Firefox in that >part of the registry, but if you try executing "firefox" at the command >line, it fails. Typing "start firefox" at the command line should work. It appears that cmd.exe does *not* use ShellExecute to find the executable, so this approach doesn't work as expected :( -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From klappnase at web.de Mon Jan 15 13:02:35 2007 From: klappnase at web.de (klappnase) Date: 15 Jan 2007 10:02:35 -0800 Subject: Segfault with tktreectrl on python-2.5 on linux Message-ID: <1168884154.116074.308720@s34g2000cwa.googlegroups.com> Hello, I use the tktreectrl Tk extension (http://tktreectrl.sourceforge.net) through the python wrapper module (http://klappnase.zexxo.net/TkinterTreectrl/index.html). With python-2.5 it seems that each time some text is inserted into the treectrl widget a segfault occurs (on linux, on windows2000 it seemed to work). Some people sent me mail describing the same problem, so I think it is not a problem with my installation of python-2.5. The treectrl widget itself works well when running from Tcl or from python2.4, so i suspect that it is a bug in python-2.5. Below the output from gdb when running the dirtree demo from the TkinterTreectrl package: (gdb) run Starting program: /usr/local/bin/python2.5 /home/pingu/projekte/TkinterTreectrl/TkinterTreectrl-0.6/demo/dirtree.py [Thread debugging using libthread_db enabled] [New Thread -1209842944 (LWP 21831)] Program received signal SIGSEGV, Segmentation fault. [Switching to Thread -1209842944 (LWP 21831)] block_alloc (b=0x1, size=16) at Python/pyarena.c:109 109 if (b->ab_offset + size > b->ab_size) { (gdb) bt #0 block_alloc (b=0x1, size=16) at Python/pyarena.c:109 #1 0x080d829e in PyArena_Malloc (arena=0x82b2790, size=16) at Python/pyarena.c:192 #2 0x081129ca in Ellipsis (arena=0x10) at Python/Python-ast.c:1764 #3 0xb77731ef in DisplayProcText () from /usr/lib/treectrl2.2/libtreectrl2.2.so Any ideas? Regards Michael From rweth at cisco.com Sat Jan 6 14:49:17 2007 From: rweth at cisco.com (rweth) Date: Sat, 06 Jan 2007 11:49:17 -0800 Subject: search mail by date with imaplib In-Reply-To: <1168112128.062140.308400@v33g2000cwv.googlegroups.com> References: <1168112128.062140.308400@v33g2000cwv.googlegroups.com> Message-ID: <1168112957.946721@sj-nntpcache-1.cisco.com> csselo at gmail.com wrote: > Hi > I am looking for a code sample which searches mail by date with imaplib > > example: > get email from 01.01.2007 to now > > how can I change imaplib search parameters? > So I had to do the same thing a few years back. I love python but seriously every author spends less than 1/10 of 1% on doc ! Well So do I .. so take it with a grain of salt. Here is what I did, MANY YEARS AGO .. I don't even have a IMAP account anymore t,data = M.uid("SEARCH",None,'(FROM blahblah)') luid = string.split(data[0]) for uid in luid: t,d = M.uid("FETCH",uid,"(BODY[HEADER.FIELDS (DATE SUBJECT TO)])") date = d[0][1] This will get you the dates .. and you can write your own filter off that .. it's trivial. What isn't so great is getting every piece of mail and then searching for the needle's in the haystack. So I guess this is plan c (just in case you don't get a better answer). I will watch this one for a "plan a | b" answer. From S.Mientki-nospam at mailbox.kun.nl Sat Jan 6 05:20:54 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 06 Jan 2007 11:20:54 +0100 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: <4b389$459f77f1$d443bb3a$7521@news.speedlinq.nl> Steven Bethard wrote: > Stef Mientki wrote: >> Not sure I wrote the subject line correct, >> but the examples might explain if not clear > [snip] >> class pin2: >> def __init__ (self, naam): >> self.Name = naam >> >> aap2 = pin2('aap2') # seems completely redundant to me. >> print aap2.Name > > You can use class statements to create your instances with some > metaclass trickery. Unlike normal assignments, class statements get > access to the name being assigned. So you could write your class like:: thank you all guys, this gives me a lot to study, for the moment I'm satisfied with the fact that it "is possible". cheers, Stef Mientki From justinjohnson at gmail.com Wed Jan 10 13:15:01 2007 From: justinjohnson at gmail.com (Justin Johnson) Date: 10 Jan 2007 10:15:01 -0800 Subject: Building Python 2.5.0 on AIX 5.3 - Undefined symbol: .__floor In-Reply-To: <1168442952.063392.225160@p59g2000hsd.googlegroups.com> References: <1168442952.063392.225160@p59g2000hsd.googlegroups.com> Message-ID: <1168452900.904960.114980@77g2000hsv.googlegroups.com> It looks like I just need to upgrade my compiler version. See http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?message=13876484&cat=72&thread=124105&treeDisplayType=threadmode1&forum=905#13876484 for more information. Justin Johnson wrote: > Hello, > > I'm trying to build Python 2.5.0 on AIX 5.3 using IBM's compiler > (VisualAge C++ Professional / C for AIX Compiler, Version 6). I run > configure and make, but makes fails with undefined symbols. See the > output from configure and make below. > > svnadm /svn/build/python-2.5.0>env CC=cc CXX=xlC ./configure > --prefix=$base_dir \ > > --disable-ipv6 \ > > --enable-shared=yes \ > > --enable-static=no > checking MACHDEP... aix5 > checking EXTRAPLATDIR... > checking for --without-gcc... > checking for gcc... cc_r > checking for C compiler default output file name... a.out > checking whether the C compiler works... yes > checking whether we are cross compiling... no > checking for suffix of executables... > checking for suffix of object files... o > checking whether we are using the GNU C compiler... no > checking whether cc_r accepts -g... yes > checking for cc_r option to accept ANSI C... none needed > checking for --with-cxx-main=... no > checking how to run the C preprocessor... cc_r -E > checking for egrep... grep -E > checking for AIX... yes > checking for --with-suffix... > checking for case-insensitive build directory... no > checking LIBRARY... libpython$(VERSION).a > checking LINKCC... $(srcdir)/Modules/makexp_aix Modules/python.exp . > $(LIBRARY); $(PURIFY) $(MAINCC) > checking for --enable-shared... yes > checking for --enable-profiling... > checking LDLIBRARY... libpython$(VERSION).a > checking for ranlib... ranlib > checking for ar... ar > checking for svnversion... found > checking for a BSD-compatible install... ./install-sh -c > checking for --with-pydebug... no > checking whether cc_r accepts -OPT:Olimit=0... no > checking whether cc_r accepts -Olimit 1500... no > checking whether pthreads are available without options... yes > checking whether xlC also accepts flags for thread support... no > checking for ANSI C header files... yes > checking for sys/types.h... yes > checking for sys/stat.h... yes > checking for stdlib.h... yes > checking for string.h... yes > checking for memory.h... yes > checking for strings.h... yes > checking for inttypes.h... yes > checking for stdint.h... yes > checking for unistd.h... yes > checking asm/types.h usability... no > checking asm/types.h presence... no > checking for asm/types.h... no > checking conio.h usability... no > checking conio.h presence... no > checking for conio.h... no > checking curses.h usability... yes > checking curses.h presence... yes > checking for curses.h... yes > checking direct.h usability... no > checking direct.h presence... no > checking for direct.h... no > checking dlfcn.h usability... yes > checking dlfcn.h presence... yes > checking for dlfcn.h... yes > checking errno.h usability... yes > checking errno.h presence... yes > checking for errno.h... yes > checking fcntl.h usability... yes > checking fcntl.h presence... yes > checking for fcntl.h... yes > checking grp.h usability... yes > checking grp.h presence... yes > checking for grp.h... yes > checking shadow.h usability... no > checking shadow.h presence... no > checking for shadow.h... no > checking io.h usability... no > checking io.h presence... no > checking for io.h... no > checking langinfo.h usability... yes > checking langinfo.h presence... yes > checking for langinfo.h... yes > checking libintl.h usability... no > checking libintl.h presence... no > checking for libintl.h... no > checking ncurses.h usability... no > checking ncurses.h presence... no > checking for ncurses.h... no > checking poll.h usability... yes > checking poll.h presence... yes > checking for poll.h... yes > checking process.h usability... no > checking process.h presence... no > checking for process.h... no > checking pthread.h usability... yes > checking pthread.h presence... yes > checking for pthread.h... yes > checking signal.h usability... yes > checking signal.h presence... yes > checking for signal.h... yes > checking stropts.h usability... yes > checking stropts.h presence... yes > checking for stropts.h... yes > checking termios.h usability... yes > checking termios.h presence... yes > checking for termios.h... yes > checking thread.h usability... yes > checking thread.h presence... yes > checking for thread.h... yes > checking for unistd.h... (cached) yes > checking utime.h usability... yes > checking utime.h presence... yes > checking for utime.h... yes > checking sys/audioio.h usability... no > checking sys/audioio.h presence... no > checking for sys/audioio.h... no > checking sys/bsdtty.h usability... no > checking sys/bsdtty.h presence... no > checking for sys/bsdtty.h... no > checking sys/file.h usability... yes > checking sys/file.h presence... yes > checking for sys/file.h... yes > checking sys/loadavg.h usability... no > checking sys/loadavg.h presence... no > checking for sys/loadavg.h... no > checking sys/lock.h usability... yes > checking sys/lock.h presence... yes > checking for sys/lock.h... yes > checking sys/mkdev.h usability... no > checking sys/mkdev.h presence... no > checking for sys/mkdev.h... no > checking sys/modem.h usability... no > checking sys/modem.h presence... no > checking for sys/modem.h... no > checking sys/param.h usability... yes > checking sys/param.h presence... yes > checking for sys/param.h... yes > checking sys/poll.h usability... yes > checking sys/poll.h presence... yes > checking for sys/poll.h... yes > checking sys/select.h usability... yes > checking sys/select.h presence... yes > checking for sys/select.h... yes > checking sys/socket.h usability... yes > checking sys/socket.h presence... yes > checking for sys/socket.h... yes > checking sys/statvfs.h usability... yes > checking sys/statvfs.h presence... yes > checking for sys/statvfs.h... yes > checking for sys/stat.h... (cached) yes > checking sys/time.h usability... yes > checking sys/time.h presence... yes > checking for sys/time.h... yes > checking sys/times.h usability... yes > checking sys/times.h presence... yes > checking for sys/times.h... yes > checking for sys/types.h... (cached) yes > checking sys/un.h usability... yes > checking sys/un.h presence... yes > checking for sys/un.h... yes > checking sys/utsname.h usability... yes > checking sys/utsname.h presence... yes > checking for sys/utsname.h... yes > checking sys/wait.h usability... yes > checking sys/wait.h presence... yes > checking for sys/wait.h... yes > checking pty.h usability... no > checking pty.h presence... no > checking for pty.h... no > checking libutil.h usability... no > checking libutil.h presence... no > checking for libutil.h... no > checking sys/resource.h usability... yes > checking sys/resource.h presence... yes > checking for sys/resource.h... yes > checking netpacket/packet.h usability... no > checking netpacket/packet.h presence... no > checking for netpacket/packet.h... no > checking sysexits.h usability... yes > checking sysexits.h presence... yes > checking for sysexits.h... yes > checking bluetooth.h usability... no > checking bluetooth.h presence... no > checking for bluetooth.h... no > checking bluetooth/bluetooth.h usability... no > checking bluetooth/bluetooth.h presence... no > checking for bluetooth/bluetooth.h... no > checking for dirent.h that defines DIR... yes > checking for library containing opendir... none required > checking whether sys/types.h defines makedev... no > checking for sys/mkdev.h... (cached) no > checking sys/sysmacros.h usability... yes > checking sys/sysmacros.h presence... yes > checking for sys/sysmacros.h... yes > checking for term.h... yes > checking for linux/netlink.h... no > checking for clock_t in time.h... yes > checking for makedev... no > checking Solaris LFS bug... no > checking for mode_t... yes > checking for off_t... yes > checking for pid_t... yes > checking return type of signal handlers... void > checking for size_t... yes > checking for uid_t in sys/types.h... yes > checking for ssize_t... yes > checking for int... yes > checking size of int... 4 > checking for long... yes > checking size of long... 4 > checking for void *... yes > checking size of void *... 4 > checking for short... yes > checking size of short... 2 > checking for float... yes > checking size of float... 4 > checking for double... yes > checking size of double... 8 > checking for fpos_t... yes > checking size of fpos_t... 4 > checking for size_t... (cached) yes > checking size of size_t... 4 > checking for long long support... yes > checking for long long... yes > checking size of long long... 8 > checking for uintptr_t support... no > checking size of off_t... 4 > checking whether to enable large file support... no > checking size of time_t... 4 > checking for pthread_t... yes > checking size of pthread_t... 4 > checking for --enable-toolbox-glue... no > checking for --enable-framework... no > checking for dyld... no > checking SO... .so > checking LDSHARED... $(BINLIBDEST)/config/ld_so_aix $(CC) > -bI:$(BINLIBDEST)/config/python.exp > checking CCSHARED... > checking LINKFORSHARED... -Wl,-bE:Modules/python.exp -lld > checking CFLAGSFORSHARED... > checking SHLIBS... $(LIBS) > checking for dlopen in -ldl... yes > checking for shl_load in -ldld... no > checking for library containing sem_init... none required > checking for textdomain in -lintl... yes > checking for genuine AIX C++ extensions support... no > checking for t_open in -lnsl... no > checking for socket in -lsocket... no > checking for --with-libs... no > checking for --with-system-ffi... no > checking for --with-signal-module... yes > checking for --with-dec-threads... no > checking for --with-threads... yes > checking if PTHREAD_SCOPE_SYSTEM is supported... yes > checking for pthread_sigmask... yes > checking if --enable-ipv6 is specified... no > checking for --with-doc-strings... yes > checking for --with-tsc... no > checking for --with-pymalloc... yes > checking for --with-wctype-functions... no > checking for dlopen... yes > checking DYNLOADFILE... dynload_shlib.o > checking MACHDEP_OBJS... MACHDEP_OBJS > checking for alarm... yes > checking for bind_textdomain_codeset... no > checking for chown... yes > checking for clock... yes > checking for confstr... yes > checking for ctermid... yes > checking for execv... yes > checking for fork... yes > checking for fpathconf... yes > checking for ftime... yes > checking for ftruncate... yes > checking for gai_strerror... yes > checking for getgroups... yes > checking for getlogin... yes > checking for getloadavg... no > checking for getpeername... yes > checking for getpgid... yes > checking for getpid... yes > checking for getpriority... yes > checking for getpwent... yes > checking for getspnam... no > checking for getspent... no > checking for getsid... yes > checking for getwd... yes > checking for kill... yes > checking for killpg... yes > checking for lchown... yes > checking for lstat... yes > checking for mkfifo... yes > checking for mknod... yes > checking for mktime... yes > checking for mremap... no > checking for nice... yes > checking for pathconf... yes > checking for pause... yes > checking for plock... yes > checking for poll... yes > checking for pthread_init... yes > checking for putenv... yes > checking for readlink... yes > checking for realpath... yes > checking for select... yes > checking for setegid... yes > checking for seteuid... yes > checking for setgid... yes > checking for setlocale... yes > checking for setregid... yes > checking for setreuid... yes > checking for setsid... yes > checking for setpgid... yes > checking for setpgrp... yes > checking for setuid... yes > checking for setvbuf... yes > checking for snprintf... yes > checking for sigaction... yes > checking for siginterrupt... yes > checking for sigrelse... yes > checking for strftime... yes > checking for sysconf... yes > checking for tcgetpgrp... yes > checking for tcsetpgrp... yes > checking for tempnam... yes > checking for timegm... no > checking for times... yes > checking for tmpfile... yes > checking for tmpnam... yes > checking for tmpnam_r... no > checking for truncate... yes > checking for uname... yes > checking for unsetenv... yes > checking for utimes... yes > checking for waitpid... yes > checking for wait3... yes > checking for wait4... yes > checking for wcscoll... yes > checking for _getpty... no > checking for chroot... yes > checking for link... yes > checking for symlink... yes > checking for fchdir... yes > checking for fsync... yes > checking for fdatasync... yes > checking for ctermid_r... no > checking for flock... no > checking for getpagesize... yes > checking for true... true > checking for inet_aton in -lc... yes > checking for inflateCopy in -lz... yes > checking for hstrerror... no > checking for inet_aton... yes > checking for inet_pton... yes > checking for setgroups... yes > checking for openpty... no > checking for openpty in -lutil... no > checking for openpty in -lbsd... no > checking for forkpty... no > checking for forkpty in -lutil... no > checking for forkpty in -lbsd... no > checking for fseek64... no > checking for fseeko... yes > checking for fstatvfs... yes > checking for ftell64... no > checking for ftello... yes > checking for statvfs... yes > checking for dup2... yes > checking for getcwd... yes > checking for strdup... yes > checking for strerror... yes > checking for memmove... yes > checking for getpgrp... yes > checking for setpgrp... (cached) yes > checking for gettimeofday... yes > checking for major... yes > checking for getaddrinfo... yes > checking getaddrinfo bug... buggy > checking for getnameinfo... yes > checking whether time.h and sys/time.h may both be included... yes > checking whether struct tm is in sys/time.h or time.h... time.h > checking for struct tm.tm_zone... no > checking for tzname... yes > checking for struct stat.st_rdev... yes > checking for struct stat.st_blksize... yes > checking for struct stat.st_flags... no > checking for struct stat.st_gen... yes > checking for struct stat.st_birthtime... no > checking for struct stat.st_blocks... yes > checking for time.h that defines altzone... no > checking whether sys/select.h and sys/time.h may both be included... > yes > checking for addrinfo... yes > checking for sockaddr_storage... yes > checking whether char is unsigned... yes > checking for an ANSI C-conforming const... yes > checking for working volatile... yes > checking for working signed char... yes > checking for prototypes... yes > checking for variable length prototypes and stdarg.h... yes > checking for socketpair... yes > checking if sockaddr has sa_len member... yes > checking whether va_list is an array... no > checking for gethostbyname_r... yes > checking gethostbyname_r with 6 args... no > checking gethostbyname_r with 5 args... no > checking gethostbyname_r with 3 args... yes > checking for __fpu_control... no > checking for __fpu_control in -lieee... no > checking for --with-fpectl... no > checking for --with-libm=STRING... default LIBM="-lm" > checking for --with-libc=STRING... default LIBC="" > checking for hypot... yes > checking wchar.h usability... yes > checking wchar.h presence... yes > checking for wchar.h... yes > checking for wchar_t... yes > checking size of wchar_t... 2 > checking for UCS-4 tcl... no > checking whether wchar_t is signed... no > checking what type to use for unicode... wchar_t > checking whether byte ordering is bigendian... yes > checking whether right shift extends the sign bit... yes > checking for getc_unlocked() and friends... yes > checking for readline in -lreadline... yes > checking for rl_callback_handler_install in -lreadline... yes > checking for rl_pre_input_hook in -lreadline... no > checking for rl_completion_matches in -lreadline... yes > checking for broken nice()... no > checking for broken poll()... no > checking for struct tm.tm_zone... (cached) no > checking for tzname... (cached) yes > checking for working tzset()... yes > checking for tv_nsec in struct stat... no > checking for tv_nsec2 in struct stat... no > checking whether mvwdelch is an expression... yes > checking whether WINDOW has _flags... yes > checking for is_term_resized... no > checking for resize_term... no > checking for resizeterm... no > checking for /dev/ptmx... no > checking for /dev/ptc... yes > checking for %zd printf() format support... yes > checking for socklen_t... yes > checking for build directories... done > configure: creating ./config.status > config.status: creating Makefile.pre > config.status: creating Modules/Setup.config > config.status: creating pyconfig.h > config.status: pyconfig.h is unchanged > creating Modules/Setup > creating Modules/Setup.local > creating Makefile > svnadm /svn/build/python-2.5.0>make > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Modules/python.o ./Modules/python.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Modules/_typesmodule.o Modules/_typesmodule.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/acceler.o Parser/acceler.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/grammar1.o Parser/grammar1.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/listnode.o Parser/listnode.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/node.o Parser/node.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/parser.o Parser/parser.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/parsetok.o Parser/parsetok.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/bitset.o Parser/bitset.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/metagrammar.o Parser/metagrammar.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/firstsets.o Parser/firstsets.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/grammar.o Parser/grammar.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/pgen.o Parser/pgen.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/myreadline.o Parser/myreadline.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/tokenizer.o Parser/tokenizer.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/abstract.o Objects/abstract.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/boolobject.o Objects/boolobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/bufferobject.o Objects/bufferobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/cellobject.o Objects/cellobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/classobject.o Objects/classobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/cobject.o Objects/cobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/codeobject.o Objects/codeobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/complexobject.o Objects/complexobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/descrobject.o Objects/descrobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/enumobject.o Objects/enumobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/exceptions.o Objects/exceptions.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/genobject.o Objects/genobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/fileobject.o Objects/fileobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/floatobject.o Objects/floatobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/frameobject.o Objects/frameobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/funcobject.o Objects/funcobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/intobject.o Objects/intobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/iterobject.o Objects/iterobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/listobject.o Objects/listobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/longobject.o Objects/longobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/dictobject.o Objects/dictobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/methodobject.o Objects/methodobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/moduleobject.o Objects/moduleobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/object.o Objects/object.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/obmalloc.o Objects/obmalloc.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/rangeobject.o Objects/rangeobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/setobject.o Objects/setobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/sliceobject.o Objects/sliceobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/stringobject.o Objects/stringobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/structseq.o Objects/structseq.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/tupleobject.o Objects/tupleobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/typeobject.o Objects/typeobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/weakrefobject.o Objects/weakrefobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/unicodeobject.o Objects/unicodeobject.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Objects/unicodectype.o Objects/unicodectype.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/Python-ast.o Python/Python-ast.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/asdl.o Python/asdl.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Python/ast.o > Python/ast.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/bltinmodule.o Python/bltinmodule.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/ceval.o Python/ceval.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/mysnprintf.o Python/mysnprintf.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/tokenizer_pgen.o Parser/tokenizer_pgen.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/printgrammar.o Parser/printgrammar.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Parser/pgenmain.o Parser/pgenmain.c > cc_r -DNDEBUG -O Parser/acceler.o Parser/grammar1.o Parser/listnode.o > Parser/node.o Parser/parser.o Parser/parsetok.o Parser/bitset.o > Parser/metagrammar.o Parser/firstsets.o Parser/grammar.o Parser/pgen.o > Objects/obmalloc.o Python/mysnprintf.o Parser/tokenizer_pgen.o > Parser/printgrammar.o Parser/pgenmain.o -ldl -o Parser/pgen > Parser/pgen ./Grammar/Grammar ./Include/graminit.h ./Python/graminit.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/compile.o Python/compile.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/codecs.o Python/codecs.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/errors.o Python/errors.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/frozen.o Python/frozen.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/frozenmain.o Python/frozenmain.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/future.o Python/future.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/getargs.o Python/getargs.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/getcompiler.o Python/getcompiler.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/getcopyright.o Python/getcopyright.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/getmtime.o Python/getmtime.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE > -DPLATFORM='"aix5"' -o Python/getplatform.o ./Python/getplatform.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/getversion.o Python/getversion.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/graminit.o Python/graminit.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/import.o Python/import.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -I. -o > Python/importdl.o ./Python/importdl.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/marshal.o Python/marshal.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/modsupport.o Python/modsupport.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/mystrtoul.o Python/mystrtoul.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/pyarena.o Python/pyarena.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/pyfpe.o Python/pyfpe.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/pystate.o Python/pystate.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/pythonrun.o Python/pythonrun.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/structmember.o Python/structmember.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/symtable.o Python/symtable.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/sysmodule.o Python/sysmodule.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/traceback.o Python/traceback.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/getopt.o Python/getopt.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/pystrtod.o Python/pystrtod.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/dynload_shlib.o Python/dynload_shlib.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Python/thread.o Python/thread.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Modules/config.o Modules/config.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE > -DPYTHONPATH='":plat-aix5:lib-tk"' \ > -DPREFIX='"/svn"' \ > -DEXEC_PREFIX='"/svn"' \ > -DVERSION='"2.5"' \ > -DVPATH='""' \ > -o Modules/getpath.o ./Modules/getpath.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Modules/main.o Modules/main.c > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o > Modules/gcmodule.o Modules/gcmodule.c > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/threadmodule.c -o Modules/threadmodule.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/signalmodule.c -o Modules/signalmodule.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/posixmodule.c -o Modules/posixmodule.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/errnomodule.c -o Modules/errnomodule.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/pwdmodule.c -o Modules/pwdmodule.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/_sre.c -o Modules/_sre.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/_codecsmodule.c -o Modules/_codecsmodule.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/zipimport.c -o Modules/zipimport.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/symtablemodule.c -o Modules/symtablemodule.o > cc_r -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -c > ./Modules/xxsubtype.c -o Modules/xxsubtype.o > cc_r -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE > -DSVNVERSION=\"`LANG=C svnversion .`\" -o Modules/getbuildinfo.o > ./Modules/getbuildinfo.c > rm -f libpython2.5.a > ar cr libpython2.5.a Modules/getbuildinfo.o > ar cr libpython2.5.a Modules/_typesmodule.o > ar cr libpython2.5.a Parser/acceler.o Parser/grammar1.o > Parser/listnode.o Parser/node.o Parser/parser.o Parser/parsetok.o > Parser/bitset.o Parser/metagrammar.o Parser/firstsets.o > Parser/grammar.o Parser/pgen.o Parser/myreadline.o Parser/tokenizer.o > ar cr libpython2.5.a Objects/abstract.o Objects/boolobject.o > Objects/bufferobject.o Objects/cellobject.o Objects/classobject.o > Objects/cobject.o Objects/codeobject.o Objects/complexobject.o > Objects/descrobject.o Objects/enumobject.o Objects/exceptions.o > Objects/genobject.o Objects/fileobject.o Objects/floatobject.o > Objects/frameobject.o Objects/funcobject.o Objects/intobject.o > Objects/iterobject.o Objects/listobject.o Objects/longobject.o > Objects/dictobject.o Objects/methodobject.o Objects/moduleobject.o > Objects/object.o Objects/obmalloc.o Objects/rangeobject.o > Objects/setobject.o Objects/sliceobject.o Objects/stringobject.o > Objects/structseq.o Objects/tupleobject.o Objects/typeobject.o > Objects/weakrefobject.o Objects/unicodeobject.o Objects/unicodectype.o > ar cr libpython2.5.a Python/Python-ast.o Python/asdl.o Python/ast.o > Python/bltinmodule.o Python/ceval.o Python/compile.o Python/codecs.o > Python/errors.o Python/frozen.o Python/frozenmain.o Python/future.o > Python/getargs.o Python/getcompiler.o Python/getcopyright.o > Python/getmtime.o Python/getplatform.o Python/getversion.o > Python/graminit.o Python/import.o Python/importdl.o Python/marshal.o > Python/modsupport.o Python/mystrtoul.o Python/mysnprintf.o > Python/pyarena.o Python/pyfpe.o Python/pystate.o Python/pythonrun.o > Python/structmember.o Python/symtable.o Python/sysmodule.o > Python/traceback.o Python/getopt.o Python/pystrtod.o > Python/dynload_shlib.o Python/thread.o > ar cr libpython2.5.a Modules/config.o Modules/getpath.o Modules/main.o > Modules/gcmodule.o > ar cr libpython2.5.a Modules/threadmodule.o Modules/signalmodule.o > Modules/posixmodule.o Modules/errnomodule.o Modules/pwdmodule.o > Modules/_sre.o Modules/_codecsmodule.o Modules/zipimport.o > Modules/symtablemodule.o Modules/xxsubtype.o > ranlib libpython2.5.a > ./Modules/makexp_aix Modules/python.exp . libpython2.5.a; cc_r > -Wl,-bE:Modules/python.exp -lld -o python \ > Modules/python.o \ > libpython2.5.a -ldl -lm > ld: 0711-317 ERROR: Undefined symbol: .__floor > ld: 0711-317 ERROR: Undefined symbol: .__ceil > ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more > information. > make: *** [python] Error 8 > svnadm /svn/build/python-2.5.0> > > I ran the last line again adding the -bloadmap option. The results of > this are below. > > (ld): halt 4 > (ld): setfflag 4 > (ld): savename python > (ld): filelist 9 2 > (ld): i /lib/crt0.o > (ld): lib /usr/lib/libld.a > (ld): i Modules/python.o > (ld): i libpython2.5.a > (ld): lib /usr/lib/libdl.a > (ld): lib /usr/lib/libm.a > (ld): lib /usr/lib/libxlopt.a > (ld): lib /usr/lib/libpthreads.a > (ld): lib /usr/lib/threads/libc.a > LIBRARY: Shared object libdl.a[shr.o]: 4 symbols imported. > LIBRARY: Shared object libpthreads.a[shr_comm.o]: 173 symbols imported. > LIBRARY: Shared object libpthreads.a[shr_xpg5.o]: 152 symbols imported. > LIBRARY: Shared object libc.a[shr.o]: 2800 symbols imported. > LIBRARY: Shared object libc.a[meth.o]: 2 symbols imported. > LIBRARY: Shared object libc.a[posix_aio.o]: 20 symbols imported. > LIBRARY: Shared object libc.a[aio.o]: 14 symbols imported. > LIBRARY: Shared object libc.a[pse.o]: 5 symbols imported. > LIBRARY: Shared object libc.a[dl.o]: 4 symbols imported. > LIBRARY: Shared object libc.a[pty.o]: 1 symbols imported. > FILELIST: Number of previously inserted files processed: 9 > (ld): exports Modules/python.exp > EXPORTS: Symbols exported: 1034 > (ld): resolve > RESOLVE: 5597 of 15450 symbols were kept. > (ld): addgl /usr/lib/glink.o > ADDGL: Glink code added for 178 symbols. > (ld): er full > ld: 0711-318 ERROR: Undefined symbols were found. > The following symbols are in error: > Symbol Inpndx TY CL Source-File(Object-File) OR > Import-File{Shared-object} > RLD: Address Section Rld-type > Referencing Symbol > > ---------------------------------------------------------------------------------------------- > .__floor [392] ER PR > Objects/floatobject.c(libpython2.5.a[floatobject.o]) > 00000b80 .text R_RBR [38] > <.float_pow> > 00000c28 .text R_RBR [38] > <.float_pow> > 00000ff4 .text R_RBR [42] > <.float_divmod> > .__floor [404] ER PR > Objects/complexobject.c(libpython2.5.a[complexobject.o]) > 0000179c .text R_RBR [42] > <.complex_divmod> > 00001a2c .text R_RBR [44] > <.complex_remainder> > .__floor [552] ER PR > Python/bltinmodule.c(libpython2.5.a[bltinmodule.o]) > 00000bec .text R_RBR [24] > <.builtin_round> > .__ceil [554] ER PR > Python/bltinmodule.c(libpython2.5.a[bltinmodule.o]) > 00000c2c .text R_RBR [24] > <.builtin_round> > ER: The return code is 8. > > I noticed the following in /usr/include/math.h, but am not sure how > this relates. > > #ifdef __IBMC__ > #if (__xlC__ >= 0x0600) /* VAC version 6 and above */ > #define floor(__x) __floor(__x) > #define ceil(__x) __ceil(__x) > #endif /* __xlC__ >= 0x0600 */ > #endif /* __IBMC__ */ > > Does anyone know what I am doing wrong here. Any help is appreciated. > > Justin From gatis.tomsons at gmail.com Tue Jan 16 06:54:28 2007 From: gatis.tomsons at gmail.com (Gacha) Date: 16 Jan 2007 03:54:28 -0800 Subject: pyExcelerator big integer values In-Reply-To: <1168432294.206654.308670@77g2000hsv.googlegroups.com> References: <1168349446.381187.65810@11g2000cwr.googlegroups.com> <45a42e7c@news.eftel.com> <1168422401.594651.278390@i39g2000hsf.googlegroups.com> <1168432294.206654.308670@77g2000hsv.googlegroups.com> Message-ID: <1168948466.943438.273040@v45g2000cwv.googlegroups.com> John Machin wrote: > Here's a possible replacement -- I say possible because you have been > rather coy about what you are actually trying to do. > > value = values[(row_idx, col_idx)]) > if isinstance(value, float): > v = repr(value) > else: > v = unicode(value) > > HTH > John My final result: value = values[(row_idx, col_idx)] if isinstance(value, float) and re.match('^\d+\.\d+e\+\d+$',unicode(value)): v = repr(value) else: v = unicode(value) From smusnmrNOSPAM at yahoo.com Mon Jan 22 03:28:16 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Mon, 22 Jan 2007 09:28:16 +0100 Subject: Win GUI application: avoiding DOS console References: Message-ID: "Jarek Zgoda" wrote: > Siggi napisa?(a): > >> how do I avoid the DOS console show-up when starting a WinXP GUI >> application >> with mouseclick on the respective Python file? >> >> I had this with my previous Python installation; it is very simple, >> something with a "-i" somewhere in the open command of the MS Windows >> data >> types "PY" and "PYW". But after a new Python installation, this was lost, >> and I cannot find the instruction what to do. > > Run it using pythonw.exe instead of python.exe (check in file types > properties window). > > -- > Jarek Zgoda > http://jpa.berlios.de/ Thanks! siggi From exarkun at divmod.com Tue Jan 30 12:52:34 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Jan 2007 12:52:34 -0500 Subject: Help me understand this In-Reply-To: Message-ID: <20070130175234.25807.1326599968.divmod.quotient.3655@ohm> On Tue, 30 Jan 2007 14:39:28 -0300, Gabriel Genellina wrote: >En Tue, 30 Jan 2007 06:34:01 -0300, Beej escribi?: > >> But here's one I still don't get: >> >>>>> type(2) >> >>>>> type((2)) >> >>>>> (2).__add__(1) >> 3 >>>>> 2.__add__(1) >> File "", line 1 >> 2.__add__(1) >> ^ >> SyntaxError: invalid syntax > >It appears to be a bug, either in the grammar implementation, or in the >grammar documentation. >These are the relevant rules: > >attributeref ::= primary "." identifier > >primary ::= atom | attributeref | subscription | slicing | call > >atom ::= identifier | literal | enclosure > >literal ::= stringliteral | integer | longinteger | floatnumber | >imagnumber > >An integer is a primary so 2.__add(1) should be valid. A float is, too. 2.__add is a float followed by an identifier. Not legal. As pointed out elsewhere in the thread, (2). forces it to be an integer followed by a ".". Jean-Paul From MrJean1 at gmail.com Thu Jan 18 21:04:54 2007 From: MrJean1 at gmail.com (MrJean1) Date: 18 Jan 2007 18:04:54 -0800 Subject: Match 2 words in a line of file References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> Message-ID: <1169172293.938820.103400@51g2000cwl.googlegroups.com> Without using re, this may work (untested ;-): def lines_with_words(file, word1, word2): """Print all lines in file that have both words in it.""" for line in file: words = line.split() if word1 in words and word2 in words: print line /Jean Brouwers Rickard Lindberg wrote: > elrondrules at gmail.com wrote: > > Hi > > > > Am pretty new to python and hence this question.. > > > > I have file with an output of a process. I need to search this file one > > line at a time and my pattern is that I am looking for the lines that > > has the word 'event' and the word 'new'. > > > > Note that i need lines that has both the words only and not either one > > of them.. > > > > how do i write a regexp for this.. or better yet shd i even be using > > regexp or is there a better way to do this.... > > > > thanks > > Maybe something like this would do: > > import re > > def lines_with_words(file, word1, word2): > """Print all lines in file that have both words in it.""" > for line in file: > if re.search(r"\b" + word1 + r"\b", line) and \ > re.search(r"\b" + word2 + r"\b", line): > print line > > Just call the function with a file object and two strings that > represent the words that you want to find in each line. > > To match a word in regex you write "\bWORD\b". > > I don't know if there is a better way of doing this, but I believe that > this should at least work. From nmm1 at cus.cam.ac.uk Mon Jan 8 12:08:22 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 8 Jan 2007 17:08:22 GMT Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> Message-ID: In article , Fredrik Lundh writes: |> Nick Maclaren wrote: |> |> > The use of different precisions for the two cases is not, however, |> > and it is that I was and am referring to. |> |> that's by design, of course. maybe you should look "repr" up in the |> documentation ? I think that you should. Where does it say that tuple's __str__ is the same as its __repr__? The obvious interpretation of the documentation is that a sequence type's __str__ would call __str__ on each sub-object, and its __repr__ would call __repr__. Regards, Nick Maclaren. From bearophileHUGS at lycos.com Mon Jan 22 16:09:09 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Jan 2007 13:09:09 -0800 Subject: Best way to document Python code... In-Reply-To: References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: <1169500149.885333.170320@s34g2000cwa.googlegroups.com> Boris Ozegovic: > Does Python has API just like in Java, for example > http://java.sun.com/j2se/1.5.0/docs/api/allclasses-noframe.html ctrl-f and > than click on class you are searching for, and finally you get clean list > of all fields and methods. Where can I find similar in Python, for > example, if I would like to see which methods list/dictionary has. You can do that from the shell, with help(name) or dir(name), where name can be a class, object, most things. Bye, bearophile From fdelente at mail.cpod.fr Sat Jan 27 07:51:24 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 27 Jan 2007 12:51:24 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> Message-ID: <45bb4acc$0$25898$426a74cc@news.free.fr> It's solved, it was a locale problem: I put import locale locale.setlocale(locale.LC_ALL,"fr_FR.iso8859-1") at the beginning of the script, and now the 8-bit-chars show up correctly. Thanks all for your help. -- Fabrice DELENTE From sean at seanodonnell.com Fri Jan 5 02:57:17 2007 From: sean at seanodonnell.com (Sean O'Donnell) Date: Thu, 04 Jan 2007 23:57:17 -0800 Subject: Problem installing MySQLdb/1.2.1_p2 with Python/2.4.1 and MySQL/5.0.18 Message-ID: <459e0752$0$17009$4c368faf@roadrunner.com> Hi, I can't seem to get MySQLdb/1.2.1p2 to install on Slackware/10.2, with Python/2.4.1, and MySQL/5.0.18. The following command: $ python setup.py build 2> setup.err returns the following errors: http://pastebin.com/851624 Any suggestions? Thanks! Sean From tomas at fancy.org Mon Jan 1 13:58:30 2007 From: tomas at fancy.org (Tom Plunket) Date: Mon, 01 Jan 2007 10:58:30 -0800 Subject: DOS, UNIX and tabs References: <1167243140.687557.93320@f1g2000cwa.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > I think there should be a single environment variable, perhaps > called "TABS", which specifies the tab settings across all relevant tools > that work with text, including less and diff. So for example setting this > as > > export TABS=4 > > will cause these tools to treat tabs as equivalent to stepping to the next > multiple of four columns from the start of the line. Maybe I'm also weird, but I use a variable-pitch font when programming in Python. So a "tab equals some number of spaces" really isn't useful to me. My setup is, "tab equals this much space". -tom! -- From webraviteja at gmail.com Thu Jan 18 22:57:02 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 18 Jan 2007 19:57:02 -0800 Subject: Making a simple script standalone In-Reply-To: <3c8584-6mc.ln1@whisper.very.softly> References: <5d1084-5j7.ln1@whisper.very.softly> <3c8584-6mc.ln1@whisper.very.softly> Message-ID: <1169179022.000434.219030@38g2000cwa.googlegroups.com> On Jan 18, 2:19 pm, Rikishi 42 wrote: > On Thursday 18 January 2007 10:13, robert wrote: > > > stay with py23 for "a script" (and more) and make <700kB > > independent distros - UPX and 7zip involved: > > >http://groups.google.com/group/comp.lang.python/msg/edf469a1b3dc3802Thanks, that might be an option. But I might just convince the person to > let me install Python. :-( Like you note, it is far simpler to just install Python. Rarely does a proper cost benefit analysis show any advantage for all the time you put in for saving a few MB off the installer (since you noted that you got it working with Py2Exe), especially when you seem to be installing the app for just one person. How big is your Exe with Py2Exe? Say 3MB? Is making it 1 MB worth maybe 2 hrs of your time for 1 install? But just for kicks, check out ShedSkin. Since you mentioned that you were using very few modules (ShedSkin supports os, stat, string, time), it might just work. ShedSkin translates your Python code to fast C++ code that can be compiled to a tight app. http://sourceforge.net/projects/shedskin/ Ravi Teja. From __peter__ at web.de Fri Jan 26 10:36:26 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Jan 2007 16:36:26 +0100 Subject: how to remove c++ comments from a cpp file? References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> <1169805244.879280.235660@v45g2000cwv.googlegroups.com> <45ba1cfe$0$5084$ba4acef3@news.orange.fr> Message-ID: Laurent Rahuel wrote: > And using the codecs module Why would you de/encode at all? Peter From gagsl-py at yahoo.com.ar Sat Jan 20 22:38:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Jan 2007 00:38:00 -0300 Subject: Code reformater? In-Reply-To: References: Message-ID: <7.0.1.0.0.20070121002325.057ece08@yahoo.com.ar> At Sunday 21/1/2007 00:15, Steven D'Aprano wrote: >On Sat, 20 Jan 2007 23:51:24 -0300, Gabriel Genellina wrote: > > > As the indentation *is* significant in python, none of the above can > > help if you lose the indentation. Try to reconstruct this: > > > > def foo(): > > if a>0: > > if b>0: > > print 1 > > print 2 > > else: > > return 3 > > return 4 > > > > The tools may help to make the indentation consistent (tabs/8 > > spaces/4 spaces/2 spaces mixed) or look better, but not to make it right. > > >Sure -- but a heuristic that gets it right *sometimes* may still be >useful, provided the user knows that the code may not be indented >correctly. > >There are lots of legal Python blocks where the indentation CAN be >reconstructed correctly, and only a relatively small proportion where it >can't -- I'd say absolutely the opposite. Try the example above. Or this one, simpler: def foo(): if a>0: if b>0: print 1 print 2 Which level should be 'print 2' assigned to? There are 3 choices. What if there is a third print? There are 3, 2, or 1 possibilities, depending on where you put the previous one. The same for any other statement below. The problem is, after a colon, you know that a new block begins and you must indent, but you don't know when that block ends except in a few cases (an else clause, by example, and only if there was a single preceding if). >the tool could do its best, and warn the user when there are >indents that can't be dealt with. Or even refuse the temptation to guess, >but re-indent whatever parts of the code it is sure about. ...almost nothing, I'm afraid... :( >Still, it is better not to lose the indentation in the first place. Sure! -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From PrinsRoy at gmail.com Tue Jan 16 15:31:35 2007 From: PrinsRoy at gmail.com (Snirp) Date: 16 Jan 2007 12:31:35 -0800 Subject: mysqldb, file _mysql.so needed Message-ID: <1168979495.057528.271820@m58g2000cwm.googlegroups.com> Good day to you all! I am trying to get mysqldb working on an ISP webserver. They will not not help me, but I think it will be possible. The thing is that there is one binary file necessary for this to work (found in python site-packages): _mysql.so (on linux) I am a poor soul stuck with windows, so i have the _mysql.pyd variant. Can anyone point me out how to acquire the _mysql.so file? Or, if possible, can any linux user share it with me or compile this file from source for me? It is found at: http://surfnet.dl.sourceforge.net/sourceforge/mysql-python/MySQL-python-1.2.1_p2.tar.gz I do not know if it will make any difference, but the ISP system is a Fedora core 4 system. Thanks in advance. BTW will a webserver even allow me to run this .so file? From laurent.pointal at limsi.fr Tue Jan 23 03:10:03 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 23 Jan 2007 09:10:03 +0100 Subject: Python Windows Editors In-Reply-To: References: Message-ID: W. Watson a ?crit : > I downloaded python-2.5.msi and installed it. I believe its editor is > IDE. I understand there's a Win editor called pythonwin. I believe it's > in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this > exe file has just the editor or all of Python. Comments? If not how do I > get the PythonWin editor by itself? > > BTW, one of the features I did not like of IDE is the limited file Print > command. It puts everything in 16pt type, and gives no choice over what > pages should be printed. Maybe there's an option? > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Two laws Newton and Einstein didn't discover: > 1. Time is money. > 2. Matter will be damaged in direct proportion > to its value. Have you take a look at the IDEs page in the Python Wiki (python.org)? http://wiki.python.org/moin/IntegratedDevelopmentEnvironments A+ Laurent. From skip at pobox.com Tue Jan 2 09:54:54 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 2 Jan 2007 08:54:54 -0600 Subject: python2.5 frameobject - how to upgrade? In-Reply-To: <459a6894$0$9322$ba620e4c@news.skynet.be> References: <459a6894$0$9322$ba620e4c@news.skynet.be> Message-ID: <17818.29246.802532.12101@montanaro.dyndns.org> Helmut> I'd like to install a package ('rekall') which uses Helmut> frame->f_nlocals which is no longer contained in frameobject.h. Helmut> What's the recommended way to upgrade such an application? I suspect PySequence_Length(frame->f_locals) will do the trick. Skip From joel at rosdahl.net Mon Jan 1 16:25:51 2007 From: joel at rosdahl.net (Joel Rosdahl) Date: Mon, 01 Jan 2007 22:25:51 +0100 Subject: are there Tomboy and F-Spot equivalents? In-Reply-To: <857993970612210901h5e56acf6lc726fc7a6315555a@mail.gmail.com> (Tshepang Lekhonkhobe's message of "Thu, 21 Dec 2006 19:01:36 +0200") References: <857993970612210901h5e56acf6lc726fc7a6315555a@mail.gmail.com> Message-ID: <87zm92wiao.fsf@rosdahl.net> "Tshepang Lekhonkhobe" writes: > I dislike installing the entire Mono stack simply to take notes and > manage photos, and am totally biased towards Python. At least for > search I got Tracker, instead of Beagle. Are there equvalents > applications for Tomboy and F-Spot which are written in Python. Kofoto is not exactly equivalent to F-Spot but quite similar in some aspects; it's focused on organizing and viewing photos, not editing them. It's written in Python using PyGTK. -- Regards, Joel Rosdahl Key BB845E97; fingerprint 9F4B D780 6EF4 5700 778D 8B22 0064 F9FF BB84 5E97 From exogen at gmail.com Mon Jan 8 13:35:28 2007 From: exogen at gmail.com (Brian Beck) Date: Mon, 08 Jan 2007 13:35:28 -0500 Subject: More Efficient fnmatch.fnmatch for multiple patterns? References: <1168279822.921033.267210@v33g2000cwv.googlegroups.com> Message-ID: abcd wrote: > I am using fnmatch.fnmatch to find some files. The only problem I have > is that it only takes one pattern...so if I want to search using > multiple patterns I have to do something like.... > > patterns = ['abc*.txt', 'foo*'] > > for p in patterns: > if fnmatch.fnmatch(some_file_name, p): > return True I don't see anything in the fnmatch and glob modules... but I didn't look very hard because what the heck is wrong with the four line solution you have? Looks fine to me. -- Brian Beck Adventurer of the First Order From dingbat at codesmiths.com Wed Jan 31 11:11:22 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 31 Jan 2007 08:11:22 -0800 Subject: Python tools to manipulate JARs ? Message-ID: <1170259882.613769.118210@v45g2000cwv.googlegroups.com> I run build processes for a Java shop using Python (and some Ant). Would anyone care to suggest favoured tools for manipulating the innards of JARs? Or do I just treat them as plain zipfiles and get stuck right in there? Mainly I'm trying to query lists of classes and their embedded versions and do some library dependency reporting. Performance speed is starting to be an issue, as there's 1500+ classes in this bucket and it's an interactive query. Thanks for any suggestions From Thomas.Ploch at gmx.net Fri Jan 5 12:31:08 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 18:31:08 +0100 Subject: Dividing integers...Convert to float first? In-Reply-To: <1168017342.255981.134400@11g2000cwr.googlegroups.com> References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> Message-ID: <459E8B5C.6020804@gmx.net> redefined.horizons at gmail.com schrieb: > I'm still pretty new to Python. I'm writing a function that accepts > thre integers as arguments. I need to divide the first integer by te > second integer, and get a float as a result. I don't want the caller of > the function to have to pass floats instead of integers. How do I > convert the arguments passed to the function into floats before I do > the division? Is this necessary, or is their a better way? > > Thanks, > > Scott Huey > Yes, it is necessary. If you divide two integers, the result will be an integer. >>> 1/2 0 You need the function float() -> float because a division between integers and floats will have floats as their results >>> float(1)/2 0.5 From tsuraan at gmail.com Mon Jan 8 10:59:34 2007 From: tsuraan at gmail.com (tsuraan) Date: Mon, 8 Jan 2007 09:59:34 -0600 Subject: Suitability for long-running text processing? In-Reply-To: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> Message-ID: <84fb38e30701080759p3d080a3fx93244c839d6d0d5d@mail.gmail.com> After reading http://www.python.org/doc/faq/general/#how-does-python-manage-memory, I tried modifying this program as below: a=[] > for i in xrange(33,127): > for j in xrange(33,127): > for k in xrange(33,127): > for l in xrange(33, 127): > a.append(chr(i)+chr(j)+chr(k)+chr(l)) import sys sys.exc_clear() sys.exc_traceback = sys.last_traceback = None del(a) > import gc > gc.collect() And it still never frees up its memory. -------------- next part -------------- An HTML attachment was scrubbed... URL: From palmem at gmail.com Wed Jan 17 23:36:21 2007 From: palmem at gmail.com (palmem at gmail.com) Date: 17 Jan 2007 20:36:21 -0800 Subject: Socket Error 106: 'Transport endpoint is already connected' Message-ID: <1169094981.335679.179430@l53g2000cwa.googlegroups.com> I am trying to write a simple FTP server in order to learn about sockets This is my first time trying sockets This code should take a connection on port 8110, dump it to a client "thread" (not a thread yet), print "Test\n" to the thread, and close everything. It fails on creating the client thread with error 106: 'Transport endpoint is already connected' On running the code: dftp starting getting the socket at 127.0.0.1 at port 8110 listening for 5 connections entering main loop ####pause here until telnet#### found a client @ addr: ('127.0.0.1', 58643) Creating a new client socket Trying to connect Traceback (most recent call last): File "./dftpd.py", line 46, in ? main() File "./dftpd.py", line 41, in main clientThread = Connection(clientsocket, address); File "/home/palmer/prog/dftp/dftpd/connection.py", line 29, in __init__ self.sock.connect(a); File "", line 1, in connect socket.error: (106, 'Transport endpoint is already connected') Telnet output: $ telnet localhost 8110 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Connection closed by foreign host. Here's my code: config is a stand-in for a config-file reader, now it just runs localhost:8110 and 5 connections debug just prints to standard out (the number afterwords is the level, but now everything is printed) #################dftpd.py######################### import debug import socket import config from connection import Connection shouldRun=True; def main(): debug.stdout("dftp starting", 1) debug.stdout("getting the socket at " + str(config.listenAddress()) + " at port " + str(config.listenPort()), 10); sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); sock.bind((config.listenAddress(), config.listenPort())); debug.stdout("listening for " + str(config.listenConnections()) + " connections", 10); sock.listen(config.listenConnections()); debug.stdout("entering main loop", 10); while shouldRun: (clientsocket, address) = sock.accept(); debug.stdout("found a client @ " + str(clientsocket) + " addr: " + str(address), 10); clientThread = Connection(clientsocket, address); print clientThread.write("Test\n"); clientThread.close; sock.close(); main() ########################connection.py######################## import debug; import socket; class Connection: def __init__(self, s, a): debug.stdout("Creating a new client socket", 15); self.sock = s; debug.stdout("Trying to connect", 15); self.sock.connect(a); debug.stdout("Making the file over the socket", 15); self.file = self.sock.makefile(); def read(): return file.read(); def write(out): file.write(out); def close(): file.close(); sock.close(); From gandalf at designaproduct.biz Wed Jan 31 13:50:20 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 31 Jan 2007 19:50:20 +0100 Subject: Python tools to manipulate JARs ? In-Reply-To: <1170259882.613769.118210@v45g2000cwv.googlegroups.com> References: <1170259882.613769.118210@v45g2000cwv.googlegroups.com> Message-ID: <45C0E4EC.5030206@designaproduct.biz> Andy Dingley ?rta: > I run build processes for a Java shop using Python (and some Ant). > > Would anyone care to suggest favoured tools for manipulating the > innards of JARs? Or do I just treat them as plain zipfiles and get > stuck right in there? > > Mainly I'm trying to query lists of classes and their embedded > versions and do some library dependency reporting. Performance speed > is starting to be an issue, as there's 1500+ classes in this bucket > and it's an interactive query. > I believe that you can rename any jar file to .zip and use zip tools to list its contents. Laszlo From removethis.kartic.krishnamurthy at gmail.com Fri Jan 12 12:31:18 2007 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Fri, 12 Jan 2007 12:31:18 -0500 Subject: Any python based "Live Web Chat Support" In-Reply-To: <1168618282.128710.52500@l53g2000cwa.googlegroups.com> References: <1168618282.128710.52500@l53g2000cwa.googlegroups.com> Message-ID: <45A7C5E6.1040303@gmail.com> johnny sayeth, on 01/12/2007 11:11 AM: > Is there any open source "live web chat support" program or script out > there? Any you can recommend? Why don't you install ejabberd (a Jabber server implemented in erlang) and install Muckl (http://zeank.in-berlin.de/muckl/), an AJAX client for multi-user chat (or Jwchat for one on one chat). Both Muckl and JWChat are embeddable in a web page, as they use just HTML/Javascript, with some work. Other than that, if you want to stick to a Python solution, I do believe Nevow project comes with a live chat demo, which you can customize. --Kartic From nagle at animats.com Thu Jan 4 03:06:48 2007 From: nagle at animats.com (John Nagle) Date: Thu, 04 Jan 2007 08:06:48 GMT Subject: C/C++, Perl, etc. to Python converter In-Reply-To: <5034u9F1dg9r9U1@mid.uni-berlin.de> References: <1167839629.435980.311750@k21g2000cwa.googlegroups.com> <5034u9F1dg9r9U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > >> >> I think that it *is* possible to do it, but a whole lot of work had to >> be done to achieve this. It is all about how many rules (like how to >> convert this block of unreadable code of language X into a readable >> python block) you are willing to find/program (and these are a lot). It >> is a almost gigantic task to make this work proper, but it definitely >> *is* possible. > > > It is definitely _not_ possible. There are so many design decisions that > are differing based on what a language offers - e.g. generators, garbage > collection, precise control over memory layout and so on. Inter-language translators have been written. There's usually a performance penalty, which can be severe when the idioms of the languages are quite different. Perl to Python translation might be worth doing. The languages have quite different syntax, but roughly the same functionality. You'd probably have to write a set of libraries in Python with the equivalent definitions to their Perl counterparts, but that's just time-consuming, not difficult. John Nagle From horpner at yahoo.com Thu Jan 11 08:58:17 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Jan 2007 14:58:17 +0100 Subject: Print message with Colors References: <1168500252.143831.235250@i56g2000hsf.googlegroups.com> Message-ID: On 2007-01-11, Laurent Pointal wrote: > prk a ?crit : >> Hi Folks, >> >> Is there any procesure for print messages with colors. > > Yes, see: > > http://www.google.fr/search?q=python+print+color > http://groups.google.fr/groups?as_q=python+print+color&num=100&as_ugroup=comp.lang.python > > See also ANSI escape sequences for the more general subject of > color printing on terminals. If you're using Windows NT, 2000, or XP don't bother reading about ANSI escape sequences. They will not work at all with Python on those platforms, even if you use the crummy old COMMAND.COM. I believe it's because Python on those platforms in a console application, which on NT, 2000 and XP doesn't support ANSI escape sequences. It makes IPython's appearance less cool. :-( Try http://effbot.org/downloads/#console for color output that works. -- Neil Cerutti We're going to be exciting. Of course, it was exciting when the Titanic went down. --Bob Weiss From dickey at saltmine.radix.net Sat Jan 27 08:36:19 2007 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Sat, 27 Jan 2007 13:36:19 -0000 Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> <12rl5mq4nnqoea0@corp.supernews.com> <45bafda7$0$2417$426a74cc@news.free.fr> Message-ID: <12rmlajpjkq6i2e@corp.supernews.com> Fabrice DELENTE wrote: > My system is Linux, and the distribution is Slackware 10.1. > I have > /lib/libncurses.so.5.4 > /lib/libncursesw.so.5.4 > so I even have the wide-chars version available. Any hint on the python > configuration? I didn't find any function that would allow the unrestricted > display of 8-bit chars. It's more complicated than that: python's loading "ncurses" dynamically. It doesn't matter much (to python) which one it loads, but it's specifying the library name explicitly. At the same time, some other packages (such as readline) are _separately_ loading the ncurses library - and they also specify a library name. Rather than abstracting that stuff out to another (more easily changed) level, it's embedded in the code. If the initialization script is changed to load "ncursesw" then python can use ncursesw without further change. There are a few patches to the configuration that I've seen mentioned in the bug reports to enable python to do this. Those are patches to python of course... (this was a topic of discussion on this newsgroup about a year ago). -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From Bulkan at gmail.com Fri Jan 5 06:53:52 2007 From: Bulkan at gmail.com (placid) Date: 5 Jan 2007 03:53:52 -0800 Subject: Calculating Download Rate Message-ID: <1167998032.425050.264280@i15g2000cwa.googlegroups.com> Hi all, I want be able to work the download rate for downloading HTML pages using the urllib.urlopen(url). The way i thought i would do this is start a timer (or log the current time) just before calling this function and the stopping the timer (logging the current time again and the working out the difference) this would give me duration that it took to retrieve the web-page, not the download rate? Thanks in advance. From borntonetwork at gmail.com Wed Jan 17 09:44:33 2007 From: borntonetwork at gmail.com (borntonetwork) Date: 17 Jan 2007 06:44:33 -0800 Subject: The proper use of QSignalMapper Message-ID: <1169045073.138626.60770@l53g2000cwa.googlegroups.com> Hi. I am trying to implement QTCore.QSignalMapper using PyQT. I finally got to a point where I don't receive any compile or runtime error messages, but I also do not see the final slot function fire off. Here is a snippet of the code: self.signalMapper = QtCore.QSignalMapper(window) # Use qsignalmapper to use of one slot function for multiple # widgets. The map() function sends the slot an extra param # that identifies the sender. for idx in range(1, maxIngredients+1): wName = 'chkProductIngredientsDelete_'+str(idx) w = self.__dict__[wName] self.app.connect(w, QtCore.SIGNAL("stateChanged(int)"), self.signalMapper, QtCore.SLOT("self.signalMapper.map")) self.signalMapper.setMapping(w, idx) self.app.connect(self.signalMapper, QtCore.SIGNAL( "self.signalMapper.mapped(int)"), self.deleteProductIngredient) def deleteProductIngredient(self, state, widgetIdx): """Delete a product ingredient.""" print "INSIDE FUNCTION\n" The idea here is to iterate through several checkbox widgets (named "chkProductIngredientsDelete_1, _2, etc.) and connect each object's "stateChanged" signal to the mapper's map() function, then connect the map() function to the actual slot, deleteProductIngredient(). By the way, I've checked to ensure the statements inside the loop are being executed. From apotheos at gmail.com Tue Jan 30 18:55:52 2007 From: apotheos at gmail.com (apotheos at gmail.com) Date: 30 Jan 2007 15:55:52 -0800 Subject: Sorting a List of Lists Message-ID: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> I can't seem to get this nailed down and I thought I'd toss it out there as, by gosh, its got to be something simple I'm missing. I have two different database tables of events that use different schemas. I am using python to collate these records for display. I do this by creating a list of lists that look roughly like this: events = [['Event URL as String', 'Event Title as String ', Event Date as Datetime], ...] I then thought I'd just go events.sort(lambda x,y: x[2]y: return 1 elif x==y: return 0 else: # x References: <1170171317.866549.261060@a34g2000cwb.googlegroups.com> Message-ID: <1170172528.635977.172030@v45g2000cwv.googlegroups.com> On Jan 30, 10:47 am, Peter Otten <__pete... at web.de> wrote: > jeremito wrote: > > I have created a class that inherits from the list object. I want to > > override the append function to allow my class to append several > > copies at the same time with one function call. I want to do > > something like: > > > import copy > > > class MyList(list): > > __init__(self): > > pass > > > def append(self, object, n=1): > > for i in xrange(n): > > self.append(copy.copy(object)) > > > Now I know this doesn't work because I overwrite append, but want the > > original functionality of the list object. Can someone help me?Use list.append(self, obj) or super(MyList, self).append(obj), e. g.: > > >>> import copy > >>> class List(list):... def append(self, obj, n=1): > ... for i in xrange(n): > ... super(List, self).append(copy.copy(obj)) > ...>>> items = List() > >>> items.append(42, 3) > >>> items[42, 42, 42] > > Peter Thank you so much. I'm glad it is so easy. Jeremy From miladmovie at gmail.com Fri Jan 19 04:11:10 2007 From: miladmovie at gmail.com (Milad Rastian) Date: Fri, 19 Jan 2007 12:41:10 +0330 Subject: error when import gtk.glade Message-ID: <56f73e4e0701190111g7e7ca405g67c8d023c86e75fe@mail.gmail.com> hello when I import gtk.glade I got this error : Traceback (most recent call last): File "MainWindow.py", line 20, in ? import gtk.glade ImportError: DLL load failed: The specified module could not be found. I setup gtk and when I create my interface in my code my gtk window open correctly tnx -- /-------------------- Milad Rastian -------------- next part -------------- An HTML attachment was scrubbed... URL: From nmm1 at cus.cam.ac.uk Sat Jan 13 05:40:22 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 13 Jan 2007 10:40:22 GMT Subject: Rational Numbers References: Message-ID: In article , "Simon Brunning" writes: |> > |> > Financial calculations need decimal FIXED-point, with a precisely |> > specified precision. It is claimed that decimal FLOATING-point |> > helps with providing that, but that claim is extremely dubious. |> > I can explain the problem in as much detail as you want, but would |> > very much rather not. |> |> Sorry, Nick, you might have to. ;-) |> |> I'm not educated in these matters, so I'd genuinely like to know why |> you say that. Not educated, but I do have some experience; I've used |> both fixed and floating point Decimal types extensively, and I've |> found floating types superior. More fiddly, certainly, 'cos you have |> to explicitly round back down to the precision that you want when you |> want. But explicit is better than implicit - the number of subtle |> rounding bugs that I've had to fix 'cos someone didn't realise where |> rounding was occurring is, uh, well, it happens from time to time. ;-) |> |> What am I missing? I will try to give a simple explanation, but I need to gloss over a hell of a lot. The precision is the number of digits after the decimal point. Financial calculations are defined in terms of decimal fixed-point, with precisely specified precisions and rounding rules (though both may vary with context, even in one expression). Now, let's ignore the arcana (especially as I know only a little of them) and note only the following: The traditional way of implementing fixed-point is as scaled integers, and this is easy and reliable. It is tricky if the USER is expected to do it, but it is trivial to excapsulate. Hell, even PLAN (the ICL 1900 assembler) did it! If a number is calculated in floating-point, decimal or otherwise, and needs any rounding, then it will NOT follow the right rules and no reasonable amount of post-operation munging will enable it to do so. Fixing up double rounding problems is inherently foul, so it is ESSENTIAL that no operation is approximate. In true fixed-point, the result of multiplication has a precision that is the sum of the input precisions, and addition, subtraction and remainder the maximum of the two. Division is required to specify a target precision and rounding rule. Overflow is raised when the total number of digits exceeds the space available. A typical financial multiplication is a monetary amount multiplied by a rate (say VAT, interest or a conversion rate). That typically has up to 5 digits, but there is no reason that it can't be more, and it is possible that some calculations multiply several rates together. When emulated in floating-point, the exception raised when the number of digits exceeds the space available is Inexact (there is a slightly different one for decimal, but the differences don't matter here). So, to get correct fixed-point flag handling, Inexact must be mapped to Overflow. Except for division, where there is no way to use the floating-point primitive as a basis for the fixed-point one, so it has to be done by hand, tediously and slowly. But, in scientific (and current Python) usage, Inexact is always ignored and Overflow is almost always an error. If we do that mapping, it will break ALL scientific code. But, if we DON'T do that mapping, we will abandon any attempt at getting reliable fixed-point overflow detection. So you can't mix the two in the same program - which was one of the main objectives of using decimal floating-point! The counter-argument is that everyone will use 128-bit arithmetic for all purposes. Well, that is hooey, because it will cause MAJOR problems for both the embedded people (logic, power and performance) and HPC people (performance, mainly bandwidth). Python could, probably. However, that isn't what the Decimal module does anyway. People will specify more digits than they possibly need, not realising that they need to specify many MORE if they are going to support multiplication. Coming back to the start, is fixing that little lot up REALLY easier than encapsulating scaled integers to give a proper fixed-point type? I think that you will find that it is much harder! Regards, Nick Maclaren. From soyouthinkimgonnalikethis at hotmail.com Thu Jan 4 11:42:00 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Thu, 04 Jan 2007 11:42:00 -0500 Subject: what is this? Message-ID: Hello; I'm studying some code examples from the python cookbook site. I came across this: def colsplit(l, cols): rows = len(l) / cols if len(l) % cols: rows += 1 m = [] for i in range(rows): m.append(l[i::rows]) return m What I'd like to know is what is the double colon? What does it do? m.append(l[i::rows]) Thanks, Eric _________________________________________________________________ Type your favorite song.? Get a customized station.? Try MSN Radio powered by Pandora. http://radio.msn.com/?icid=T002MSN03A07001 From tpawley at gmail.com Fri Jan 12 02:27:29 2007 From: tpawley at gmail.com (Torabisu) Date: 11 Jan 2007 23:27:29 -0800 Subject: General Question About Python In-Reply-To: <1168337298.574881.121470@i15g2000cwa.googlegroups.com> References: <1168254451.098796.144790@42g2000cwt.googlegroups.com> <1168336603.962731.5470@11g2000cwr.googlegroups.com> <1168337298.574881.121470@i15g2000cwa.googlegroups.com> Message-ID: <1168586849.047301.301680@s34g2000cwa.googlegroups.com> billie wrote: > Torabisu wrote: > > > Its quite weird, we're looking for Python skills but are battling to > > find at the moment... Normally Python on its own will probably not > > land you a job, but the last two companies I've worked for are doing > > indepth Python development, so hopefully the tables are turning a bit. > > I can tell the same for Italy. > Where are you from? Cape Town, South Africa. There is a strong Unix following here, but more on the System Administration side, not really the software development side with regards to Python. Python more being used for task automation and shell scripting. From __peter__ at web.de Thu Jan 18 05:51:48 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Jan 2007 11:51:48 +0100 Subject: One more regular expressions question References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> Message-ID: Victor Polukcht wrote: > I have a couple of strings like: > > Unassigned Number (1) 32 > No Route To Destination (3) 12 > Normal call clearing (16) 2654 > User busy (17) 630 > No user respond (18) 5 > User alerting no answer (19) 16 > Call rejected (21) 3 > Destination out of order (27) 1 > Invalid number format (28) 32 > Normal unspecified (31) 32 > No channel available (34) 2 > Temporary failure (41) 11 > Switching equipment congestion (42) 4 > Resource unavailable unspecified (47) 2 > Bearer capability not authorized (57) 73 > Incomp. dest. / Non-existent CUG (88) 1 > Recovery on timer expiry (102) 2 > Interworking, unspecified (127) 5 > > I need to get: > Error code (value in brackets) - Value - Message. > > My actual problem is i can't get how to include space, comma, slash. The following solution is 100% regex-free :-) >>> print lines Unassigned Number (1) 32 No Route To Destination (3) 12 Normal call clearing (16) 2654 User busy (17) 630 No user respond (18) 5 User alerting no answer (19) 16 Call rejected (21) 3 Destination out of order (27) 1 Invalid number format (28) 32 Normal unspecified (31) 32 No channel available (34) 2 Temporary failure (41) 11 Switching equipment congestion (42) 4 Resource unavailable unspecified (47) 2 Bearer capability not authorized (57) 73 Incomp. dest. / Non-existent CUG (88) 1 Recovery on timer expiry (102) 2 Interworking, unspecified (127) 5 >>> [int(line.rsplit("(", 1)[1].split(")", 1)[0]) for line in lines.splitlines()] [1, 3, 16, 17, 18, 19, 21, 27, 28, 31, 34, 41, 42, 47, 57, 88, 102, 127] Peter From simon at brunningonline.net Tue Jan 9 14:25:15 2007 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 9 Jan 2007 19:25:15 +0000 Subject: Maths error In-Reply-To: References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <8c7f10c60701091125w570a52ebj16301a5b7dfa1d0b@mail.gmail.com> On 1/9/07, Tim Peters wrote: > Well, just about any technical statement can be misleading if not qualified > to such an extent that the only people who can still understand it knew it > to begin with <0.8 wink>. +1 QTOW -- Cheers, Simon B simon at brunningonline.net From bignose+hates-spam at benfinney.id.au Thu Jan 18 20:10:54 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 Jan 2007 12:10:54 +1100 Subject: Iterator length References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> <1169167258.553202.190130@m58g2000cwm.googlegroups.com> <1169168139.350836.79790@s34g2000cwa.googlegroups.com> Message-ID: <87r6tr6ctd.fsf@benfinney.id.au> bearophileHUGS at lycos.com writes: > But sometimes you don't need the elements of a given iterator, you > just need to know how many elements it has. AFAIK, the iterator protocol doesn't allow for that. Bear in mind, too, that there's no way to tell from outside that an iterater even has a finite length; also, many finite-length iterators have termination conditions that preclude knowing the number of iterations until the termination condition actually happens. -- \ "When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic." -- Dresden James | Ben Finney From tundra at tundraware.com Mon Jan 8 11:29:05 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 08 Jan 2007 10:29:05 -0600 Subject: Walking The Right Path In-Reply-To: <1168252155.427645.316470@38g2000cwa.googlegroups.com> References: <1168252155.427645.316470@38g2000cwa.googlegroups.com> Message-ID: Jakub Stolarski wrote: > Tim Daneliuk napisal(a): >> Ah yes, moral philosophy and python all come together... Er, that is to day: >> >> Imagine you have this situation on a *nix filesystem: >> >> Symlink A: /foo -> /usr/home >> Symlink B: /bar -> /foo/username >> >> >> If I do this: >> >> import os >> print os.path.realpath("/bar") >> >> I get this (as one would expect): >> >> /usr/home/username >> >> However, what if I want to get back the result in this form: >> >> /foo/username >> >> >> IOW, is there a way to return a symlink-based path which contains >> the symlink pointer as is was *defined* not as it expands? >> > > One way (but very ugly): > print os.path._resolve_link('/bar') > Yup, that does just what I want. By why, pray tell, do you consider it ugly ...? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From gagsl-py at yahoo.com.ar Sun Jan 28 18:23:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Jan 2007 20:23:26 -0300 Subject: ftplib and retrbinary or retrlines (losing newline characters in my log files) In-Reply-To: <7d1760310701260447u5cbed71fr46cb32f9378bd6ac@mail.gmail.co m> References: <7d1760310701242205u6e6b4706ja20e3c07406a8064@mail.gmail.com> <7.0.1.0.0.20070125031353.0452a4f8@yahoo.com.ar> <7d1760310701260447u5cbed71fr46cb32f9378bd6ac@mail.gmail.com> Message-ID: <7.0.1.0.0.20070128201547.04449590@yahoo.com.ar> At Friday 26/1/2007 09:47, aus stuff wrote: >Hi, im not sure if this is how i reply to the mail-list, excuse me >if incorrect. Forwarding now to the list. >Gabriels' solution works fine > ftp.retrlines('RETR ' + fl, lambda >line:fileObj.write('%s\n' % line)) > >But lambda's confuse me (newbie here) how could i do the same with a >normal function? lambda args: whatever is the same as: def anonymous_function(args): return whatever So, the above example could be written as: def writeline(line): fileObj.write('%s\n' % line) [...] ftp.retrlines('RETR ' + fl, writeline) (the write method has no return value, so we omit the return statement) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tiedon_jano at hotmail.com Fri Jan 5 15:41:32 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Fri, 05 Jan 2007 20:41:32 GMT Subject: where is Microsoft Speech Object Library 5.1 option inPythonWin 2.5? In-Reply-To: References: Message-ID: <0Kynh.432$sE.358@read3.inet.fi> Siggi kirjoitti: > Gabriel Genellina wrote: > >> After you download and install version 5.1, it should appear on the list. > > It should, but it does not! Shutting down and starting the WinXP Home system > anew did not help. > The SDK 5.1 installation went smoothly, however. What can I do to find out > what is wrong? > > siggi > (Sorry for the long post!) Unfortunately I can't comment on this 5.0/5.1 issue but if you look at page http://www.cs.unc.edu/~parente/tech/tr02.shtml you'll find the pyTTS system. I've used it and everything works. The funny thing is that the page has a link named "Microsoft SAPI 5.1 redistributable" which links to http://www.cs.unc.edu/Research/assist/packages/SAPI5SpeechInstaller.msi ie. a SAPI 5 installer. So I'm starting to wonder if it matters at all whether the speech kit is a version 5 or 5.1. Anyway: pyTTS works with Python 2.4 as advertized in the accompanying examples. I've used it to resolve the following dilemma: how to guarantee that I'm aware of new mail appearing on my ISP. I had an unfortunate experience where a guy I was working with sent me (to my home) mail that I didn't expect to receive just at the moment and to which I would have liked to react immediately. Why I didn't notice the mail coming: I was outside my house pumping more air to my wife's bicycle tires! The mail notification was shown and erased and one more icon among the more than dozen icons on my Windows System Tray didn't account for much. So I figured out that a voice to remind me would be nice. I have a low rate inbox, usually only a maximum of hald a dozen messages per day so I wouldn't have to listen the voice all day long. So the voice keeps repeating that I have new mail at my ISP until I download the mail and otherwise keeps quiet. So here is my program and a skeleton of the INI file it uses. The program is not finished (I have a few ideas still) but it runs all day long on my computer keeping me happy. ========================== New Email Notifier.py ========================== #!/usr/bin/python ''' License: MIT License. See License.txt. If that file is not attached, the license is http://www.opensource.org/licenses/mit-license.php, where = 2006 and = Jussi Salmela, Turku, Finland ''' # This program checks for new email at ISP and notifies if new email is found import win32serviceutil import win32service import win32event import pyTTS, sys, os, poplib, logging, time import ConfigParser,pywintypes print '\nThis is the New Mail Notifier window\n' notifierDirectory = r'C:\Python\OMAT___PROJEKTIT\New Email Notifier Service' logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', filename=notifierDirectory+r'\error.log') logging.info('=========================================================') logging.info('New Email Notifier Service started') config = ConfigParser.ConfigParser() config.readfp(open(notifierDirectory+r'\New Email Notifier.INI')) POP3Server = config.get('POP3','server') POP3Account = config.get('POP3','account') POP3Password = config.get('POP3','password') totalMessagesFormat = config.get('messages','total_message') newMessagesFormat = config.get('messages','new_message') wakeupMessageFormat = config.get('messages','wakeup_message') tts = pyTTS.Create() #set the speech volume percentage (0-100%) tts.Volume = 100 #explicitly set a voice tts.SetVoiceByName(u'MSMary') uidDict = {} # We wait to be stopped and check for new email every maxTimeToWait seconds maxTimeToWait = 1 # First check after 1 second while True: time.sleep(maxTimeToWait) maxTimeToWait = 60 # Rest of the checks after 60 second try: # Connect to the ISP a = poplib.POP3(POP3Server,110) answer = a.getwelcome() if answer[0:3] != '+OK': raise ValueError,'a.getwelcome returned: ' + answer answer = a.user(POP3Account) if answer[0:3] != '+OK': raise ValueError,'a.user returned: ' + answer if answer[4:] == 'Password required': answer = a.pass_(POP3Password) if answer[0:3] != '+OK': raise ValueError,'a.pass_ returned: ' + answer answer = a.uidl() if answer[0][0:3] != '+OK': raise ValueError,'a.uidl returned: ' + repr(answer) a.quit() # Connection closed. Start handling the unique message identifiers #logging.info('Connection succesfully opened, used and closed!') print 'answer', answer, time.asctime() uidList = [e.split()[1] for e in answer[1]] print 'uidList', uidList totalMessages = len(uidList) uidDictNew = {} for e in uidList: uidDictNew[e] = True uidList = [e for e in uidList if e not in uidDict] uidDict = uidDictNew if totalMessages: tts.Speak(totalMessagesFormat % totalMessages) newMessages = len(uidList) if newMessages: tts.Speak(newMessagesFormat % newMessages) except Exception,inst: errorMsg = 'Unexpected error: %s' % sys.exc_info()[0] logging.error(errorMsg) logging.error(inst) try: tts.Speak(wakeupMessageFormat) tts.Speak('I repeat: ' + wakeupMessageFormat) tts.Speak(errorMsg) tts.Speak(inst) except pywintypes.com_error,inst: errorMsg = 'Unexpected error: %s' % sys.exc_info()[0] logging.error(errorMsg) logging.error(inst) ========================== New Email Notifier.INI ========================== [POP3] server: myPOPserver account: myAcoount password: myPassword [messages] total_message: Your eemail server has. a total of %d messages. for you to download new_message: The number of new messages. since the last check. is %d wakeup_message: Wake up, Youssi! This is your new eemail notifier, reporting the following error! HTH, Jussi From CedricCicada at gmail.com Fri Jan 19 13:59:14 2007 From: CedricCicada at gmail.com (CedricCicada at gmail.com) Date: 19 Jan 2007 10:59:14 -0800 Subject: My first try using logger didn't work. Why? In-Reply-To: <1169224835.820468.316040@v45g2000cwv.googlegroups.com> References: <1169221734.071338.107190@11g2000cwr.googlegroups.com> <1169224835.820468.316040@v45g2000cwv.googlegroups.com> Message-ID: <1169233154.076956.231540@q2g2000cwa.googlegroups.com> Beautiful! Thank you very much! One of the problems I was laboring under was that I did not know where to go to find the official documentation. Thanks for that link too! Rob From pythonnews at nospam.jmbc.fr Tue Jan 30 04:04:38 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Tue, 30 Jan 2007 10:04:38 +0100 Subject: wxPython StatusBar Help In-Reply-To: <45bdfdc3$0$6722$426a74cc@news.free.fr> References: <45bdfdc3$0$6722$426a74cc@news.free.fr> Message-ID: <45bf0a45$0$21150$7a628cd7@news.club-internet.fr> Hi, > I'm working with wxPython 2.8.1.1. > > Does anybody know how to change the foreground colors in a wx.StatusBar You can get inspiration from the following code, but the problem is you will have also to draw all the status bar stuff, not only the foreground color. I don't know any other way. However, I'm used to 2.6 and I could miss something existing in 2.8 (I think to OnCreateStatusBar which exists and don't work in 2.6 and was supposed to work with the next release ; it could be a clue). Regards, jm import wx class MyStatusBar(wx.StatusBar): def __init__(self,*args,**kargs): wx.StatusBar.__init__(self,*args,**kargs) self.Bind(wx.EVT_PAINT,self.OnPaint) def OnPaint(self,event): dc = wx.PaintDC(self) self.Draw(dc) def Draw(self,dc): dc.BeginDrawing() dc.SetBackground( wx.Brush("White") ) dc.Clear() dc.SetPen(wx.Pen('BLACK')) dc.DrawText(self.GetStatusText(),0,0) dc.EndDrawing() if __name__ == "__main__": app = wx.PySimpleApp() frame= wx.Frame(None,wx.ID_ANY,'test frame') statusBar= MyStatusBar(frame,wx.ID_ANY) statusBar.SetStatusText("status text..") frame.SetStatusBar(statusBar) frame.Show(True) app.MainLoop() From justin.mailinglists at gmail.com Mon Jan 29 21:50:15 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 29 Jan 2007 18:50:15 -0800 Subject: Convert raw data to XML In-Reply-To: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> Message-ID: <1170125415.883023.316950@s48g2000cws.googlegroups.com> On Jan 30, 10:42 am, elrondru... at gmail.com wrote: > For example the raw data is as follows > > SomeText Description>PassorFail > > without spaces or new lines. I need this to be written into an XML > file as > > > > > > > SomeText > > > PassorFail > > > > raw = r'SomeText PassorFail' import xml.dom.ext import xml.dom.minidom doc = xml.dom.minidom.parseString(raw) xml.dom.ext.PrettyPrint(doc) SomeText PassorFail From dwoogle at gmail.com Wed Jan 3 13:48:47 2007 From: dwoogle at gmail.com (dwelden) Date: 3 Jan 2007 10:48:47 -0800 Subject: Sorting on multiple values, some ascending, some descending Message-ID: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> I have successfully used the sort lambda construct described in http://mail.python.org/pipermail/python-list/2006-April/377443.html. However, how do I take it one step further such that some values can be sorted ascending and others descending? Easy enough if the sort values are numeric (just negate the value), but what about text? Is the only option to define an external sorting function to loop through the list and perform the comparisons one value at a time? From jim at none Mon Jan 29 23:44:41 2007 From: jim at none (Jim) Date: Mon, 29 Jan 2007 21:44:41 -0700 Subject: Python 2.5 Tkinter not configured Message-ID: I compiled Python 2.5 from python.org and I get an error message when I try to import the Tkinter module. Python reports that there is no such module. It says my Python isn't configured for Tkinter. How do I configure it? I'm using GCC 4.1.1 to compile the tarball. Thanks for any help with this. Jim From http Tue Jan 23 17:37:18 2007 From: http (Paul Rubin) Date: 23 Jan 2007 14:37:18 -0800 Subject: My python programs need a GUI, wxPython or PyQt4? References: Message-ID: <7xac09cqu9.fsf@ruckus.brouhaha.com> "Daniel Jonsson" writes: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! I've always found tkinter to be adequate so far. The widgets look a little bit crude compared with other toolkits, and there's less fancy functionality, but it's fairly easy to program and it's included with Python. For internal use where you don't need a lot of visual slickness to sell the product, it may be ok. Another possibility is embed a web server in your application and use a browser interface for your gui. That makes it easy to run the application on a separate machine from the user, among other things, even if you don't try to support multiple simultaneous users like a real web server normally would have to. From steve at REMOVE.THIS.cybersource.com.au Thu Jan 11 15:10:02 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 12 Jan 2007 07:10:02 +1100 Subject: dot operations References: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> <1168522658.128216.199310@77g2000hsv.googlegroups.com> <1168524399.307074.192080@i56g2000hsf.googlegroups.com> Message-ID: On Thu, 11 Jan 2007 06:06:39 -0800, jm.suresh at no.spam.gmail.com wrote: >> jm.suresh at no.spam.gmail.com wrote: >> > Hi, >> > Frequently I get to do like this: >> > a = (1, 2, 3, 4) # some dummy values >> > b = (4, 3, 2, 1) >> > import operator >> > c = map(operator.add, a, b) >> > >> > I am finding the last line not very readable especially when I combine >> > couple of such operations into one line. Is it possible to overload >> > operators, so that, I can use .+ for element wise addition, as, >> > c = a .+ b >> > which is much more readable. [snip] > I just found this from : > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122 > > class Infix(object): [snip code] > c = a |dotplus| b Personally, I find that to be the least readable of all the alternatives. It is also slow, so slow that using it is (in my opinion) a pessimation rather than an optimization. Let me make the usual warnings about premature optimization being the root of all evil, blah blah blah. Readability counts, and nobody cares if you shave one hundredth of a millisecond off some code that your program runs once. But, having said that, map is *fast*, especially with the functions from operator. >>> import timeit >>> timeit.Timer("map(operator.add, a, b)", ... "import operator; a = (1, 2, 3, 4); b = (4, 3, 2, 1)").timeit() 4.0072550773620605 It is even faster if you get rid of the dot lookup: >>> timeit.Timer("map(add, a, b)", "from operator import add; " ... "a = (1, 2, 3, 4); b = (4, 3, 2, 1)").timeit() 3.6557090282440186 Using lambda can be much slower: >>> timeit.Timer("map(lambda x,y: x+y, a, b)", ... "a = (1, 2, 3, 4); b = (4, 3, 2, 1)").timeit() 6.1221940517425537 A list comprehension is in the middle, speed-wise: >>> timeit.Timer("[x+y for x,y in zip(a,b)]", ... "a = (1, 2, 3, 4); b = (4, 3, 2, 1)").timeit() 5.0318419933319092 But the Infix recipe is slower than a wet week: >>> timeit.Timer("a|dotplus|b", ... "a = (1, 2, 3, 4); b = (4, 3, 2, 1); " ... "from __main__ import dotplus").timeit() 15.195909976959229 Speaking for myself, I find list comprehensions to be the most readable of the alternatives and the most Pythonic. -- Steven. From sturlamolden at yahoo.no Sun Jan 7 12:16:09 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 7 Jan 2007 09:16:09 -0800 Subject: c# application calling Scipy In-Reply-To: <1168108637.270801.155950@42g2000cwt.googlegroups.com> References: <1168108637.270801.155950@42g2000cwt.googlegroups.com> Message-ID: <1168190167.079723.25160@51g2000cwl.googlegroups.com> dongarbage at hotmail.com wrote: > Hi, > > Novice here. :) > > I'm building a c# application and I want to call functions in SciPy > from that application. > > What's the best way to call SciPy methods from a C# program? You need to: 1. Embed a Python interpreter in your C# app. That is, importing from a DLL with a Python interpreter and defining a few structs. 2. Define a NumPy ndarray as a C# struct. Or: 1. Write a proxy DLL in C and embed Python in that. This is the preferred way, as I see it. You are relieved of having to redefine Python and NumPy's C structs in C#. 2. Import your proxy in C# and marshal a C# array to a IntPtr. That will allow you to map a C# array to a NumPy ndarray C struct in your proxy. The latter method is less hassle. In any case you also need to make sure you are using a .NET runtime that are linked to the same CRT as Python (.NET 1.1 should work). Using IronPython will not work, as neither NumPy nor SciPy is ported to IronPython (and porting is not trivial either; but if you take the task upon yourself, many will be happy if you succeeed.) From skip at pobox.com Sun Jan 14 23:08:08 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 14 Jan 2007 22:08:08 -0600 Subject: How naive is Python? In-Reply-To: References: Message-ID: <17834.65064.411286.935369@montanaro.dyndns.org> John> How naive (in the sense that compiler people use the term) is the John> current Python system? For example: John> def foo() : John> s = "This is a test" John> return(s) John> s2 = foo() John> How many times does the string get copied? Never. s and s2 just refer to the same object (strings are immutable). Executing this: def foo() : print id("This is a test") s = "This is a test" print id(s) return(s) s2 = foo() print id(s2) prints the same value three times. John> Or, for example: John> s1 = "Test1" John> s2 = "Test2" John> s3 = "Test3" John> s = s1 + s2 + s3 John> Any redundant copies performed, or is that case optimized? Not optimized. You can see that using the dis module: 4 0 LOAD_CONST 1 ('Test1') 3 STORE_FAST 0 (s1) 5 6 LOAD_CONST 2 ('Test2') 9 STORE_FAST 1 (s2) 6 12 LOAD_CONST 3 ('Test3') 15 STORE_FAST 2 (s3) 7 18 LOAD_FAST 0 (s1) 21 LOAD_FAST 1 (s2) 24 BINARY_ADD 25 LOAD_FAST 2 (s3) 28 BINARY_ADD 29 STORE_FAST 3 (s) 32 LOAD_CONST 0 (None) 35 RETURN_VALUE The BINARY_ADD opcode creates a new string. John> How about this? John> kcount = 1000 John> s = '' John> for i in range(kcount) : John> s += str(i) + ' ' John> Is this O(N) or O(N^2) because of recopying of "s"? O(N). Here's a demonstration of that: #!/usr/bin/env python from __future__ import division def foo(kcount): s = '' for i in xrange(kcount) : s += str(i) + ' ' import time for i in xrange(5,25): t = time.time() foo(2**i) t = time.time() - t print 2**i, t, t/2**i On my laptop t roughly doubles for each iteration and prints around 5e-06 for t/2**i in all cases. Skip From basti.wiesner at gmx.net Wed Jan 3 06:59:27 2007 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Wed, 03 Jan 2007 12:59:27 +0100 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: Piet van Oostrum typed >>>>>> Sebastian 'lunar' Wiesner (SW) wrote: > >>SW> Linux seems to ignore SUID bit on scripts: > > The reason is that obeying SUID bits on scripts would be a security > risk. I don't see a problem with SUID on scripts. If you restrict write access to the owner, modification is hardly possible. However, if you allow world-wide write access to your binaries and scripts, both can easily be modified... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From jarausch at skynet.be Tue Jan 2 06:48:56 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 02 Jan 2007 12:48:56 +0100 Subject: mutable numeric type In-Reply-To: <1167735454.604184.110630@i12g2000cwa.googlegroups.com> References: <1167735454.604184.110630@i12g2000cwa.googlegroups.com> Message-ID: <459A46A8.3050706@skynet.be> pgarrone at acay.com.au wrote: > Way to go. > Try doing this. > x = MutableNumeric(42) ^^^^^^^^^^^^^^ where is this defined? > y = x > x += 42 > print y > -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From tim at tdw.net Tue Jan 16 11:50:50 2007 From: tim at tdw.net (Tim Williams) Date: Tue, 16 Jan 2007 16:50:50 +0000 Subject: Python web app. (advice sought) In-Reply-To: References: <45aae51b.0@entanet> Message-ID: <9afea2ac0701160850m6bb1badcw318bb738536cf49@mail.gmail.com> On 16/01/07, Ralf Sch?nian wrote: > > I would also like to vote for Karrigell. > > BTW: Does anyone knows how to avoid stopping/starting of the webserver > after changing external libraries? I have some own modules under > /opt/local/python/lib and import them by extending the path with > sys.path.append() After changing any file here, I have to restart > Karrigell. > Ralf, you should ask this on the Karrigell list :) From farproc at gmail.com Tue Jan 9 23:59:54 2007 From: farproc at gmail.com (Kevin Yuan) Date: Wed, 10 Jan 2007 12:59:54 +0800 Subject: where is python on linux? In-Reply-To: References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> Message-ID: <45A472CA.7020600@gmail.com> Frank Potter wrote: >> ... where is the executable python file? ... >> > > does > > whereis python "whereis" is cool! From persed at princeton.edu Mon Jan 22 08:51:19 2007 From: persed at princeton.edu (Per B. Sederberg) Date: Mon, 22 Jan 2007 08:51:19 -0500 Subject: Program eating memory, but only on one machine? Message-ID: <6b7179780701220551v7765c05apd73052112ff06ded@mail.gmail.com> Hi Everybody: I'm having a difficult time figuring out a a memory use problem. I have a python program that makes use of numpy and also calls a small C module I wrote because part of the simulation needed to loop and I got a massive speedup by putting that loop in C. I'm basically manipulating a bunch of matrices, so nothing too fancy. That aside, when the simulation runs, it typically uses a relatively small amount of memory (about 1.5% of my 4GB of RAM on my linux desktop) and this never increases. It can run for days without increasing beyond this, running many many parameter set iterations. This is what happens both on my Ubuntu Linux machine with the following Python specs: Python 2.4.4c1 (#2, Oct 11 2006, 20:00:03) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> numpy.version.version '1.0rc1' and also on my Apple MacBook with the following Python specs: Python 2.4.3 (#1, Apr 7 2006, 10:54:33) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> numpy.version.version '1.0.1.dev3435' >>> Well, that is the case on two of my test machines, but not on the one machine that I really wish would work, my lab's cluster, which would give me 20-fold increase in the number of processes I could run. On that machine, each process is using 2GB of RAM after about 1 hour (and the cluster MOM eventually kills them). I can watch the process eat RAM at each iteration and never relinquish it. Here's the Python spec of the cluster: Python 2.4.4 (#1, Jan 21 2007, 12:09:48) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-49)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> numpy.version.version '1.0.1' It also showed the same issue with the April 2006 2.4.3 release of python. I have tried using the gc module to force garbage collection after each iteration, but no change. I've done many newsgroup/google searches looking for known issues, but none found. The only major difference I can see is that our cluster is stuck on a really old version of gcc with the RedHat Enterprise that's on there, but I found no suggestions of memory issues online. So, does anyone have any suggestions for how I can debug this problem? If my program ate up memory on all machines, then I would know where to start and would blame some horrible programming on my end. This just seems like a less straightforward problem. Thanks for any help, Per From sean at datafly.net Sun Jan 21 19:03:55 2007 From: sean at datafly.net (Sean Schertell) Date: Mon, 22 Jan 2007 09:03:55 +0900 Subject: PyMeld for html templates? In-Reply-To: References: <1169241497.610167.130580@a75g2000cwd.googlegroups.com> <2EA54772-B695-435B-950C-3A15DE8B7135@datafly.net> Message-ID: <42641607-532B-40FB-8C15-518CB21EA1C2@datafly.net> Thanks Richie! That's exactly the reply I was hoping for. Hooray! Sean On Jan 20, 2007, at 9:50 PM, Richie Hindle wrote: > Hi Sean, > >> Thanks Richie -- but actually, what I had in mind was slightly >> different. I want for my CONTENT pages to only contain the content. >> So to modify your example: >> >> LAYOUT = """The Title >>
The page information goes here.
>>

Here is the info, which would in the real >> world >> be read from a file.

""" >> >> Can I do this just as easily? > > Yes, of course, just the same way: > > from PyMeld import Meld > > LAYOUT = """The Title >
The page information goes here.
>

Here is the info, which would in the real > world be read from a file.

""" > > page = Meld(LAYOUT) > info = Meld(INFO) > page.info = info.info._content > print page > > There's nothing that says a Meld has to be a complete HTML document. > >> One other unrelated question... Let's say I have a table with a >> template row with id="myRow". I want to use PyMeld to clone that row >> n number of times (depending on database results). So here's my >> stoopid question: Does that mean that my XHTML will contain n rows >> all with the same id="myRow" thereby making my XHTML invalid? > > Yes, it does, but you can simply delete the 'id' attributes from > the rows, > with `del row.id`, before adding them back into the document. > > -- > Richie Hindle > richie at entrian.com From pretoriano_2001 at hotmail.com Mon Jan 8 08:29:58 2007 From: pretoriano_2001 at hotmail.com (vizcayno) Date: 8 Jan 2007 05:29:58 -0800 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <50ehtmF1fh46iU1@mid.uni-berlin.de> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <50ehtmF1fh46iU1@mid.uni-berlin.de> Message-ID: <1168262998.765702.38760@i15g2000cwa.googlegroups.com> Diez B. Roggisch ha escrito: > vizcayno schrieb: > > Hello: > > Need your help in the "correct" definition of the next function. If > > necessary, I would like to know about a web site or documentation that > > tells me about best practices in defining functions, especially for > > those that consider the error exceptions management. > > I have the next alternatives but I think there are better: > > > > IMHO none of them is good. Python has exceptions. Use them. There is no > need to awkwardly communicate error conditions using return-values. Use > return values to return values. Use exceptions in case of errors. > > Diez Diez, in that case I woul prefer not to use exceptions and wait for Python to abort itself and wait to see the message it issues. From baur79 at gmail.com Tue Jan 2 12:06:31 2007 From: baur79 at gmail.com (baur79) Date: 2 Jan 2007 09:06:31 -0800 Subject: how to use execfile with argument under windows Message-ID: <1167757591.465076.314700@h40g2000cwb.googlegroups.com> Hi everybody i need to execute this command line (different source for n times) filename.exe -type png -source sourcearg -file filename.png i try with python (python script and filename.exe in same directory) import os ...... ...... execfile("filename.exe -type png -source sourcearg -file filename.png") error output IOError: [Errno 2] No such file or directory:"filename.exe -type png -source sourcearg -file filename.png" try execfile("d:\pathto\filename.exe -type png -source sourcearg -file filename.png") error output IOError: [Errno 2] No such file or directory:"d:\pathto\filename.exe filename.exe -type png -source sourcearg -file filename.png" please help to solve problem thanks From weekender_ny at yahoo.com Mon Jan 22 03:30:20 2007 From: weekender_ny at yahoo.com (John) Date: 22 Jan 2007 00:30:20 -0800 Subject: class explorer for automating IE In-Reply-To: References: <1169448532.869501.190530@v45g2000cwv.googlegroups.com> <1169449585.832667.325370@11g2000cwr.googlegroups.com> Message-ID: <1169454620.313191.263020@m58g2000cwm.googlegroups.com> The problem is that this does not run javascript code it seems. I got started with pamie, which seems to work till now. Thanks, --j On Jan 22, 2:42 am, Peter Otten <__pete... at web.de> wrote: > John wrote: > > Is there an analogue of IE Mechanize in python?http://www.google.com/search?q=python%20mechanize&btnI=I%27m+Feeling+... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 10 12:50:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 10 Jan 2007 18:50:49 +0100 Subject: Question about compiling. References: Message-ID: <50knbpF1g9rt9U1@mid.individual.net> Steven W. Orr wrote: > I *just* read the tutorial so please be gentle. I created a file > called fib.py which works very nicely thank you. When I run it it > does what it's supposed to do but I do not get a resulting .pyc > file. .pyc files are created only if you import a .py file. Regards, Bj?rn -- BOFH excuse #77: Typo in the code From nagle at animats.com Thu Jan 25 01:12:07 2007 From: nagle at animats.com (John Nagle) Date: Thu, 25 Jan 2007 06:12:07 GMT Subject: Catching floating point errors from linked C code In-Reply-To: <1169702669.027065.65990@v33g2000cwv.googlegroups.com> References: <1169696243.262973.188540@s48g2000cws.googlegroups.com> <1169702669.027065.65990@v33g2000cwv.googlegroups.com> Message-ID: John Pye wrote: > Hi John, > > On Jan 25, 3:43 pm, John Nagle wrote: > >>Python is probably running with floating point exceptions disabled, >>but you can enable them in your C code, and restoring the floating >>point mode when you leave, if you want. This is probably >>only worth doing under a debugger, because otherwise you just end >>up with an aborted instance of Python. > > > So as far as you know, Python doesn't switch stuff like > feenableexcept(FE_EXCEPT_ALL)? Does Python use the > internally, or are all its FPEs detected by explicit checks beforehand? I have no idea what state Python leaves the FPU in, but whatever the state is, you can read it, set your own state, and restore the previous state before returning to Python. The last time I had to do this, I used unsigned int oldstate = // make almost all FPU errors fatal _controlfp ((~_EM_INVALID) & _CW_DEFAULT, _MCW_EM); ... _controlfp(oldstate); // restore old state on Windows 2000. John Nagle From jairodsl at gmail.com Thu Jan 11 20:22:52 2007 From: jairodsl at gmail.com (jairodsl) Date: 11 Jan 2007 17:22:52 -0800 Subject: Parallel Python In-Reply-To: <1168561780.317156.268880@42g2000cwt.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <7x8xga215f.fsf@ruckus.brouhaha.com> <1168516936.890690.235300@p59g2000hsd.googlegroups.com> <1168561780.317156.268880@42g2000cwt.googlegroups.com> Message-ID: <1168564971.999278.135120@a75g2000cwd.googlegroups.com> Hi, You guys forgot pyMPI, http://pympi.sourceforge.net/ It works fine !!! A little hard installation and configuration but finally works !!! Cordially, Jairo Serrano Bucaramanga, Colombia parallelpyt... at gmail.com wrote: > > > > Thus there are different levels of parallelization: > > > > 1 file/database based; multiple batch jobs > > 2 Message Passing, IPC, RPC, ... > > 3 Object Sharing > > 4 Sharing of global data space (Threads) > > 5 Local parallelism / Vector computing, MMX, 3DNow,... > > > > There are good reasons for all of these levels. > > Yet "parallel python" to me fakes to be on level 3 or 4 (or even 5 :-) ), while its just a level 2 > > system, where "passing", "remote", "inter-process" ... are the right vocables. > In one of the previous posts I've mentioned that ppsmp is based on > processes + IPC, which makes it a system with level 2 parallelization, > the same level where MPI is. > Also it's obvious from the fact that it's written completely in python, > as python objects cannot be shared due to GIL (POSH can do sharing > because it's an extension written in C). From matej.cepl at gmail.com Tue Jan 9 18:57:50 2007 From: matej.cepl at gmail.com (matej) Date: 9 Jan 2007 15:57:50 -0800 Subject: maildir->mbox conversion script review Message-ID: <1168387070.443728.287210@p59g2000hsd.googlegroups.com> Hi, I am writing a script to convert couple of thousand emails (in couple of hundred folders) and before I will get to the hard part -- maintaing structure folders and subfolders, and maintaing record of the status of the message, I would like to be sure that I have at least maildir->mbox conversion right. Could anybody comment on the below shown code please? Thanks a lot Mat?j --------------------------------------------------------------------------------------------------------------------- #!/usr/bin/env python """mdir2mbx: yet another maildir -> mbox converter mdir2mbx [maildirName] [mboxName] TODO: * convert all (or as many as possible) status flags from KMail to Thunderbird. * testing, testing, testing """ __version__ = "$Revision: 1.2 $" __author__ = "Matej Cepl " __copyright__ = "(C) 2007 Matej Cepl. MIT/X11." __date__ = "$Date: 2007/01/08 23:56:29 $" ___contributors__ = [] import email, email.Errors, email.Header, email.Generator, mailbox import codecs, sys, cStringIO class Mailbox(mailbox.UnixMailbox): def __init__(self,filename): mailbox.UnixMailbox.__init__(self,filename,email.message_from_file) self.boxname=filename self.content = "" def add(self,msg): fp = cStringIO.StringIO() g = email.Generator.Generator(fp, mangle_from_=True, maxheaderlen=65) g.flatten(msg,unixfrom=True) self.content += "%s\n\n" % fp.getvalue() def write(self): outfile=file(self.boxname,"wb") outfile.write("%s\n" % self.content) outfile.close() class MyMaildir(mailbox.Maildir): def __init__(self,dirname): mailbox.Maildir.__init__(self,dirname,email.message_from_file) self.dirname = dirname self.decfunc = email.Header.decode_header self.msg = "" def __translateHeader(self,headerName): header = email.Header.decode_header(self.msg[headerName]) string = header[0][0] encoding = header[0][1] if not(encoding): encoding = "ascii" outstr = string.decode(encoding,'ignore') return outstr def listHeaders(self): for self.msg in self: hdrfrom = self.__translateHeader("From") #hdrto = self.__translateHeader("To") hdrdate = self.__translateHeader("Date") hdrsubject = self.__translateHeader("Subject") print "%s;%s;%s" % (hdrfrom,hdrdate,hdrsubject) #header = email.Header.decode_header(self.msg["Message-Id"])[0][0] #print "%s;%s" % (self.dirname,header) def writeMBox(self,filename): mbox = Mailbox(filename) for self.msg in self: mbox.add(self.msg) mbox.write() if __name__=="__main__": obj = MyMaildir(sys.argv[1]) obj.writeMBox(sys.argv[2]) From horpner at yahoo.com Sat Jan 27 02:18:21 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 27 Jan 2007 07:18:21 GMT Subject: Convert String to list of chars References: Message-ID: <11Duh.1840$G23.1501@newsreading01.news.tds.net> On 2007-01-27, juanefren at gmail.com wrote: > How can I convert a string to a char list? > for example > > "hello" --> ['h','e','l','l','o'] > > I have been searching but I can't find my answers list("hello") From jeff.dyke at gmail.com Thu Jan 4 10:03:48 2007 From: jeff.dyke at gmail.com (jeff.dyke at gmail.com) Date: 4 Jan 2007 07:03:48 -0800 Subject: connection hangs Message-ID: <1167923027.937816.12880@q40g2000cwq.googlegroups.com> I am using ftplib in some code that does exactly what you would expect. It ftp's files. Its running inside a service running on windows xp and windows 2003 servers, approximately 20 installations each installation sends between 100 and 1000 files per day. Occasionally the process will hang completely and the only way to restart the service is to kill the pythonservice.exe (via End Process in Task Manager) service and start it. I have turned on the full debugging, ftpobject.debug(1), and redirected that stdout to a file and when the process hangs i see hundreds of identical lines (*cmd* 'TYPE I') in the debug files. See log except below. This command i see is only executed in two places, during the storbinary and retrbinary methods. When it hangs, it never gets a response from the server and eventually locks up. The connection does have a socket timeout of 10 seconds on the connection, modifying the length of time has no affect on this issue. Everything will work fine for weeks/months and then all of a sudden a network issue will occur and the process will hang. The process ONLY hangs when transferring over the internet, it has never happened on a LAN connection, even when i have removed all connectivity from the FTP server mid upload. Has anyone ever seen this? or have any ideas how i could code around it. Thanks Jeff --- debug log ---- *resp* '227 Entering Passive Mode (##.##.##.##,173,244).' *cmd* 'NLST *filematch*.xml' *resp* '125 Data connection already open; Transfer starting.' *resp* '226 Transfer complete.' *cmd* 'USER username' *resp* '331 Password required for username.' *cmd* 'PASS ********' *resp* '230 User username logged in.' *cmd* 'TYPE I' *resp* '200 Type set to I.' *cmd* 'PASV' *resp* '227 Entering Passive Mode (##.##.##.##,174,4).' *cmd* u'STOR /path/to/filename.ext' *resp* '125 Data connection already open; Transfer starting.' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' *cmd* 'TYPE I' .... you get the idea From Thomas.Ploch at gmx.net Wed Jan 3 18:02:40 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Thu, 04 Jan 2007 00:02:40 +0100 Subject: static object In-Reply-To: <459c306c$0$314$426a74cc@news.free.fr> References: <459c306c$0$314$426a74cc@news.free.fr> Message-ID: <459C3610.7020703@gmx.net> meelab schrieb: > Dear All, > > I am looking for a way to create a "static object" or a "static class" - > terms might be inappropriate - having for instance: > > class StaticClass: > . > . > > and then > staticObject1 = StaticClass() > staticObject2 = StaticClass() > > so that staticObject1 and staticObject2 refers exactly to the same > instance of object. > > In other words, that is a class which would result in only 1 instance > always the same no matter how many times I will "instantiate" it. > > My purpose is to permit this class to initialize a massive amount of > data that I need to access from different points of my program without > duplicating this data in memory and without loosing time in reloading it > each time I need it. > > I noticed the staticmethods, and the __new__ method which could , but I > always get stuck in actually creating static DATA without having global > data. > > Does anyone have a start of a clue to this ? > > Many thanks in advance > > Emmanuel. class DataStorage: def __init__(self, data): self.data = data dataVault = DataStorage(data) dataVault1 = dataVault dataVault2 = dataVault ... but why not use a static_data.py (put your data in there) file and do: >>> from static_data.py import DATA This way you only load it once and it will be accessible throughout your program. Thomas From fsck_spam at telenet.be Thu Jan 18 17:19:15 2007 From: fsck_spam at telenet.be (Rikishi 42) Date: Thu, 18 Jan 2007 23:19:15 +0100 Subject: Making a simple script standalone References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: <3c8584-6mc.ln1@whisper.very.softly> On Thursday 18 January 2007 10:13, robert wrote: > stay with py23 for "a script" (and more) and make <700kB > independent distros - UPX and 7zip involved: > > http://groups.google.com/group/comp.lang.python/msg/edf469a1b3dc3802 Thanks, that might be an option. But I might just convince the person to let me install Python. :-( -- Research is what I'm doing, when I don't know what I'm doing. (von Braun) From facundo at taniquetil.com.ar Fri Jan 12 10:46:32 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 12 Jan 2007 15:46:32 +0000 (UTC) Subject: ValueError from dict - some detail would be helpful References: <1168529175.794131.109390@77g2000hsv.googlegroups.com> Message-ID: metaperl wrote: > File "/sw/lib/python2.5/csv.py", line 120, in _dict_to_list > raise ValueError, "dict contains fields not in fieldnames" > > > --- it would be nice if it said what field it was Yeap, nice and useful... but, for example, what'd happen if the fields that are not in fieldnames are 10, or 100? How the message could be? -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From S.Mientki-nospam at mailbox.kun.nl Tue Jan 2 06:50:57 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 02 Jan 2007 12:50:57 +0100 Subject: Difference between __init__ (again) and nothing ... In-Reply-To: References: Message-ID: Marc 'BlackJack' Rintsch wrote: > In , Stef Mientki wrote: > >> What's the difference between using __init__ and using nothing, >> as the examples below. >> >> class cpu: >> PC = 4 > > This is a *class attribute*. It's the same for all instances of `cpu`. > >> class cpu: >> def __init__: >> self.PC = 4 > > This is an *instance attribute* which is set in every instance of `cpu`. > thanks Marc, Oh so obvious, why didn't I discovered that myself ;-) cheers, Stef From pavlovevidence at gmail.com Tue Jan 23 23:25:42 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 23 Jan 2007 20:25:42 -0800 Subject: free variables /cell objects question In-Reply-To: <1169563580.634000.122540@v45g2000cwv.googlegroups.com> References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> Message-ID: <1169612742.833333.239870@d71g2000cwa.googlegroups.com> On Jan 23, 9:46 am, "gangesmaster" wrote: > ugliness :) > > so this is why [lambda: i for i in range(10)] will always return 9. > imho that's a bug, not a feature. It's a feature. If you were to write a nested function like this, where a, b, c, and d, are cell variables: print_values(): print a,b,c,d then it wouldn't work as intended if you passed the variable itself to the cell rather than a reference. Nested functions have to support this as well as to create lexical closures. The thing is, newbies are very likely to use nested functions like I've shown above, whereas few newbies are likely to use closures. Python has correctly, IMHO, chosen the way that minimizes surprises for newbies. Carl Banks From xah at xahlee.org Mon Jan 22 00:34:13 2007 From: xah at xahlee.org (Xah Lee) Date: 21 Jan 2007 21:34:13 -0800 Subject: Xah's Edu Corner: Introduction to 3D Graphics Programing In-Reply-To: <1166836083.084101.25870@73g2000cwn.googlegroups.com> References: <1166836083.084101.25870@73g2000cwn.googlegroups.com> Message-ID: <1169444053.559779.233100@s34g2000cwa.googlegroups.com> Xah Lee wrote in 2006-12-22: > Of Interest: > > Introduction to 3D Graphics Programing > http://xahlee.org/3d/index.html Folks, i have expanded my tutorial to several pages in the past nearly two months, and thank you very much for those who have given encouragement. I had plans to write pages that actually contained Python or Perl and elisp code to demonstrate the mingled use of common languages with POV-RAY and other tools for doing algorithmic mathematical art... However, i'm posting now for one in-credible discovery that amazed me, and believe it is a revolutionary both with respect to technology, as well as its social impact. Following is my brief introduction. The web version is at: Introduction to Second Life http://xahlee.org/sl/sl.html ------- Introduction to Second Life Xah Lee, 2007-01-09 above: A screenshot of a location in Second Life. This place is called ?The Future?, it is a place built by Henry Segerman ? built. Second Life is a online virtual world with 2 million accounts as of 2006-12, and reportedly 10 thousand users logged in at any moment. Basically, you operate a software that is a 3D world much like 3D games, but everything in the ?game? is built by users, and you can interact with other users, including buying and selling virtual land with real money. What people do inside Second Life is entirely up to them (as in real life). And, as it happens, what people do mostly in Second Life are pretty much what people do in real life. The major activities are: sex, shopping, socializing, dancing. My mathematician friend Henry Segerman introduced me to 2nd life. (also because it appeared in Time Mag in 2006-12.) Henry has a 2nd life page that contains many math objects made in Second Life: http://www.stanford.edu/~segerman/2ndlife.html. Part of my interest in Second Life is to build geometric models. (See Introduction to 3D Graphics Programing) I have for the past couple years sought for a software platform/system where i can build 3D objects, with abilities to do interactive adjustment (such as moving a slide to change a surface's parameter), dynamic rotation (viewing from different angles), animations (such as morphing that shows geometric processes), and most of all, walk-thru in it as if it is a building. As far as my experiences goes, no software platform for 3D graphics are close to the ideal of what i need to do. They lack one feature or the other, or otherwise requires the programer to be a specialist with years of dedication in learning the tool. For example, Mathematica? has great collection of math functions but no dynamic graphics. POV-RAY? and 3D-modelers like AutoCAD? can do great in building 3D objects but they are not designed for interactivity, animations, or walk-thru. Java the programming language? allows one to write applets that does rotation and interactive manipulation but programing in Java is extremely unnecessarily complex and yet it is still not possible to do walk-thrus. The one class of platform that does all these, is 3D game engines. But alas, they take a dedicated game programing specialist to be able to use it. Second Life changed all this. (Note: Just for completness, my requirement for a 3D-graphics programing software system is this: ? easy to use for average programers or scientists. ? Easy to build geometry models, such as basic shapes like spheres and blocks, as well as surfaces or meshes of triangles. ? designed for interactivity. That is, the programer can easily build buttons and sliders that changes parameters and have the object reflect these changes visually right away. ? the user can easily change viewing angles or rotate the object. ? The programer can easily do animations. For example, morph a sphere into a cube, or a bunch of spheres flying in space as a swarm of flies. ? The ability to do walk-thru (or fly-thru). For example, if i build a fancy 3D-maze or architecture, i should be able to ? say ? become a ant, and walk inside the object, so as to view the object from inside and as well as getting the real experience of perceiving such a building. (Before my discover of Second Life, the platform that i was considering nearly ideal and preparing to learn, are VPython? and Macromedia Flash? (i do still plan to learn these technologies) )) Second Life is not just the answer to my mathematical fantasies, but because of its Real-World nature, being run and build by real people, and with scarily real money market of the virtual dollars it uses, is nothing but a technological revolution with great social impact. It is essentially the virtual-3D-world-wide-web dream of VRML? envisioned around 1995. Anshe Chung? is famouly known for being the first to become a (real world) millionaire by selling entirely virtual items and virtual services inside Second Life. For a encyclopedic introduction, see: Second Life? Here are some articles about Second Life. (note that there are a lot linked at the bottom of the Wikipedia article.) * Time Mag: ?My So-Called Second Life?, By Joel Stein, 20061216.? * businessWeek online: INSIDE INNOVATION ? IN SIDE. Second Life Lessons. By Reena Jana and Aili McConnon. 2006-11-27.? 2007-01-21, Addendum Recently i heard of Entropia Universe?. I haven't taken a closer look but i think it is a competitor to Second Life. Note that Second Life may not be and is probably not the first virtual world. And, when virtual world like Second Life becomes household activity as the internet is today, it will probably not be known as Second Life or run by one single company, but diverse companies with servers all over the world, where there is a unified virtual world all the world's people can be in. (This situation may be likened to the internet circa 1995. Or, perhaps also similar when telephone was in its pioneering days.) ---- Xah xah at xahlee.org ? http://xahlee.org/ From mail at microcorp.co.za Thu Jan 11 00:41:12 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 11 Jan 2007 07:41:12 +0200 Subject: Is there a way to protect a piece of critical code? References: <7xac0rovp4.fsf@ruckus.brouhaha.com> Message-ID: <004e01c73543$1a9c99a0$03000080@hendrik> "Paul Rubin" wrote: > "Hendrik van Rooyen" writes: > > I would like to do the following as one atomic operation: > > > > 1) Append an item to a list > > 2) Set a Boolean indicator > > You could do it with locks as others have suggested, but maybe you > really want the Queue module. > > Please see my reply to Robert - am aware of queue, using it in fact. From could.net at gmail.com Fri Jan 26 03:46:37 2007 From: could.net at gmail.com (Frank Potter) Date: 26 Jan 2007 00:46:37 -0800 Subject: how to remove c++ comments from a cpp file? Message-ID: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> I only want to remove the comments which begin with "//". I did like this, but it doesn't work. r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) f=file.open("mycpp.cpp","r") f=unicode(f,"utf8") r.sub(ur"",f) Will somebody show me the right way? Thanks~~ From "trades\" at (none) Tue Jan 30 08:56:41 2007 From: "trades\" at (none) (none) Date: Tue, 30 Jan 2007 07:56:41 -0600 Subject: deepcopy alternative? In-Reply-To: <1170117161.953913.276600@v33g2000cwv.googlegroups.com> References: <45be808e$0$27074$4c368faf@roadrunner.com> <1170117161.953913.276600@v33g2000cwv.googlegroups.com> Message-ID: <45bf4e99$0$28076$4c368faf@roadrunner.com> Szabolcs Nagy wrote: >> I believe the only thing stopping me from doing a deepcopy is the >> function references, but I'm not sure. If so is there any way to >> transform a string into a function reference(w/o eval or exec)? > > what's your python version? > for me deepcopy(lambda:1) does not work in py2.4 but it works in py2.5 > (in py2.4 i tried to override __deepcopy__ but it had no effect) > Thanks that fixed the problem real quick :) Jack Trades From Thomas.Ploch at gmx.net Sun Jan 7 15:01:29 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 21:01:29 +0100 Subject: Python re expr from Perl to Python In-Reply-To: <20070107210940.1596.4.NOFFLE@dieschf.news.arcor.de> References: <20070107210940.1596.4.NOFFLE@dieschf.news.arcor.de> Message-ID: <45A15199.9040906@gmx.net> Florian Diesch schrieb: > "Michael M." wrote: > >> In Perl, it was: >> >> >> ## Example: "Abc | def | ghi | jkl" >> ## -> "Abc ghi jkl" >> ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st >> pipe). >> $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; >> >> ## -- remove [ and ] in text >> $na =~ s/\[//g; >> $na =~ s/\]//g; >> # print "DEB: \"$na\"\n"; >> >> >> # input string >> na="Abc | def | ghi | jkl [gugu]" >> # output >> na="Abc ghi jkl gugu" >> >> >> How is it done in Python? > >>>> import re >>>> na="Abc | def | ghi | jkl [gugu]" >>>> m=re.match(r'(\w+ )\| (\w+ )\| (\w+ )\| (\w+ )\[(\w+)\]', na) >>>> na=m.expand(r'\1\2\3\5') >>>> na > 'Abc def ghi gugu' I'd rather have the groups grouped without the whitespaces >>> import re >>> na="Abc | def | ghi | jkl [gugu]" >>> m=re.match(r'(\w+) \| (\w+) \| (\w+) \| (\w+) \[(\w+)\]', na) >>> na=m.expand(r'\1 \3 \4 \5') >>> na 'Abc ghi jkl gugu' Thomas From robert.kern at gmail.com Fri Jan 5 05:09:19 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 05 Jan 2007 04:09:19 -0600 Subject: where to find wx package In-Reply-To: References: Message-ID: siggi wrote: > Hi all, > > a newbie question: > > I have a program gui03A.py using wxPython, importing it such: > "from wxPython.wx import *" > > The program works, but I get the warning message: > > "gui03A.py:4: DeprecationWarning: The wxPython compatibility package is no > longer automatically generated or activly maintained. Please switch to the > wx package as soon as possible." > > However, after extensive searching on www.python.org and Googling the web, I > do not find any package with "wx" as its only name. > > Where can I get the wx package (for win32 XP)? It's the same project (from the people at www.wxpython.org), they just renamed the package. You already have it installed. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From harry.g.george at boeing.com Wed Jan 24 05:54:04 2007 From: harry.g.george at boeing.com (Harry George) Date: Wed, 24 Jan 2007 10:54:04 GMT Subject: My python programs need a GUI, wxPython or PyQt4? References: <45b69f63$0$24463$88260bb3@free.teranews.com> Message-ID: "Chris Mellon" writes: > On 1/24/07, Giovanni Bajo wrote: [snip] > > > > That page is legal babble, trying to trick you into buying (or making your > > boss buy) a commercial license. The Qt Open Source edition *IS* GPL and thus > > it falls under all the normal GPL clauses and uses, irrespective of what > > Trolltech may or may not think. > > > > For instance, see this FAQ: > > http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic > > > > which makes pretty clear that a "company"/"organization" is basically the same > > of an "individual". "Releasing a software within a company for internal usage" > > is by no means the same of "releasing it to the public". Basically, for what > > the GPL is concerned, it is *not* a "release" or a "distribution" at all. > > > > I should point out that the FSFs position in this regard is not > supported by copyright law and that the fact that Trolltech takes a > different position is something that you should consider strongly. If > the FSFs position were true, there would be no need for per-seat > licensing of commercial software (because internal distribution > wouldn't be). US copyright law does not draw a distinction between > "internal distribution" and any other kind, and I'm not aware of any > case law that does so either. This distinction is also not codified in > the GPL itself anywhere, so it's not a necessary condition of the > license - it is an interpretation by the FSF and that is all. [snip] It is all interpretation -- even after some cases have wandered through the courts. Mostly the trolltech statements indicate their intent to sue. That right there tells me I want to go elsewhere. -- Harry George PLM Engineering Architecture From ramdaz at gmail.com Tue Jan 2 01:42:35 2007 From: ramdaz at gmail.com (Ramdas) Date: 1 Jan 2007 22:42:35 -0800 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> Message-ID: <1167720155.296077.233010@42g2000cwt.googlegroups.com> Well, I need to add users from a web interface for a web server, which runs only Python. I need to add users, set quotas and in future even look at managing ip tables to limit bandwidth. I know os.system(), but this has to be done through a form entry through a web interface. Anyways thanks, do advise if there more pythonic solutions Ramdas Hari Sekhon wrote: > That is shell scripting with a python layer on top. Is there a > specific reason you have to use python? Why not just use shell, that's > what it's designed for? Unless you have some complex maths/networking > requirement or something on top. > > -h > > On 01/01/07, Daniel Klein wrote: > > On 1 Jan 2007 11:33:42 -0800, "Ramdas" wrote: > > > > >How do I add users using Python scripts on a Linux machine? > > > > > >Someone has a script? > > > > This should be as easy as something like: > > > > os.system("/usr/sbin/useradd -m -d /home/newuser -s /bin/ksh") > > > > Dan > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Hari Sekhon From bruno.desthuilliers at websiteburo.com Thu Jan 25 07:43:43 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Thu, 25 Jan 2007 13:43:43 +0100 Subject: While loop with "or"? Please help! In-Reply-To: References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> <45b8a31d$0$2401$426a74cc@news.free.fr> Message-ID: <45b8a5fd$0$27474$426a74cc@news.free.fr> Peter Otten a ?crit : > Bruno Desthuilliers wrote: > >> and simplified again thanks to Python 'in' operator: >> while not usrinp.lower() in "yn": > > But note that 'in' performs a substring search and therefore "yn" and "" > would be accepted as valid answers, too. Mmm, right. Thanks for the correction. => while not usrinp.lower() in ['y', 'n']: From bsg075 at gmail.com Fri Jan 26 14:35:55 2007 From: bsg075 at gmail.com (Matt) Date: 26 Jan 2007 11:35:55 -0800 Subject: Editor with visual SCC / TFS support ? Message-ID: <1169840155.437260.90080@j27g2000cwj.googlegroups.com> Company has switched to MS Team Foundation Server from VSS. Need a programmers text editor that interfaces with TFS or SCC providers to visually provide checkin/out status on project files. So far, in all of the editors I have used, some support SCC interfaces, but do not show the file status. The current alternative is to load Visual Studio (or the TFS client which is simply a subset of VS), simply to manage checkins. Using command line calls is also an options, but visualizing the file status would be more helpful. Suggestions? From guettli.usenet at thomas-guettler.de Wed Jan 17 10:31:03 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 17 Jan 2007 15:31:03 GMT Subject: Newbie: Capture traceback message to string? References: Message-ID: <516tpnF1ic39jU1@mid.individual.net> Sean Schertell wrote: > Hello! > > I'm new to Python and this is my first post to the list. > > I'm trying to simply capture exception text to a few strings which > can be passed to a PSP page to display a pretty error message. The > problem is that I just can't seem to figure out how to get the basic > components of the traceback message into strings. Here's what I want > to do: > # http://www.thomas-guettler.de/vortraege/python/beispiele.py.txt def foo(): raise("Das ist eine Exception") try: foo() except: import traceback import cStringIO (exc_type, exc_value, tb) = sys.exc_info() exc_file = cStringIO.StringIO() traceback.print_exception(exc_type, exc_value, tb, file=exc_file) exc_string=exc_file.getvalue() print exc_string Why don't you use cgitb? It is one reason why I like this language. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From raymond.zhou.ecnumstc at gmail.com Thu Jan 4 05:07:29 2007 From: raymond.zhou.ecnumstc at gmail.com (Raymond) Date: Thu, 4 Jan 2007 18:07:29 +0800 Subject: Draw rectangle on a Window DC Message-ID: <459cd1e4.0232d77c.0893.ffff821d@mx.google.com> Hi? I want to Draw rectangle on Dc when gived a position. Can you teach me? Let me view your code? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Sat Jan 27 21:29:17 2007 From: nagle at animats.com (John Nagle) Date: Sat, 27 Jan 2007 18:29:17 -0800 Subject: Do I need Python to run Blender correctly? In-Reply-To: References: <5%4uh.75582$wP1.6882@newssvr14.news.prodigy.net> Message-ID: AKA gray asphalt wrote: > "John Nagle" wrote in message > news:5%4uh.75582$wP1.6882 at newssvr14.news.prodigy.net... > >>AKA gray asphalt wrote: >> >>>I downloaded Blender but there was no link for python. Am I on the right >>>track? >> >> Blender doesn't require Python, but if you have Python, you can >>write plug-ins for Blender. Get "The Blender Book"; otherwise >>you'll never figure Blender out. >> >>John Nagle > > > I'm thinking about not upgrading "Strata 3D" because it still doesn't export > textures with obj files and it just created an undo of more than one action, > believe it or not... Am I expectiong too much of a $400+ program, to export > textures with obj files? Does Blender do this? I see the BBook on Amazon for > $30. That's probably my best bet, no? Blender has considerable power, but ease of use is a problem. The hotkey listing in the manual is 29 pages. From no-spam at no-spam-no-spam.invalid Wed Jan 17 13:41:59 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 17 Jan 2007 19:41:59 +0100 Subject: predefined empty base class ?? In-Reply-To: References: <1169053011.399278.290980@a75g2000cwd.googlegroups.com> Message-ID: robert wrote: > iwl wrote: >> Hi, >> >> is there an predefined empty base class >> which I can instanziate to have an container i can copy attributes in? >> > > you are not the only one missing such class > > http://groups.google.com/group/comp.lang.python/msg/3ff946e7da13dba9 > > RFE SF #1637926 > ( and x=Exception();x.a=1 will do it preliminary ) Robert From istvan.albert at gmail.com Mon Jan 15 09:21:38 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 15 Jan 2007 06:21:38 -0800 Subject: Python web app. (advice sought) References: <45aae51b.0@entanet> Message-ID: <1168870898.693882.44980@s34g2000cwa.googlegroups.com> Duncan Smith wrote: > I've had a look at Django, Turbogears and Plone, and at the moment I am > torn between Turbogears and Plone. I Plone is not suited for the type of application you are building (as others have pointed out in this thread). Take a second look at TurboGears (or CherryPy for that matter). You might have discounted Django a bit too soon. It has the best documentation and it is the most consistent framework. You might end up bringing in new people into your project and that will go a lot easier when you have good docs to help them as well. i. From steve at holdenweb.com Sun Jan 28 09:09:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Jan 2007 14:09:48 +0000 Subject: Ip address In-Reply-To: <1169990510.352536.4760@a34g2000cwb.googlegroups.com> References: <1169990510.352536.4760@a34g2000cwb.googlegroups.com> Message-ID: Adam wrote: > Hey, > > This will get your IP address: > > #######Code######## > print socket.gethostbyaddr(socket.gethostname()) > ('compname', [], ['192.168.1.2']) > ########End Code######## > > If you are wanting to to communicate over the internet you will have > to get the IP of you rounter. So you will have to either find a way to > talk to your router or try and use an online service like these other > guys suggest. There is absolutely no need to know the IP address of "your router" to communicate with Internet devices. Either your IP layer is configured to know the addresses of one or more routers, or it has discovered those address by dynamic means, or you can't get off-net because there aren't any routers. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From vedran at v-programs.com Thu Jan 4 14:32:25 2007 From: vedran at v-programs.com (Croteam) Date: 4 Jan 2007 11:32:25 -0800 Subject: py2exe setup strange error Message-ID: <1167939145.491799.68670@s80g2000cwa.googlegroups.com> Hello, I was trying to install my script (.py) to (.exe) and when I run setup script with cmd I get the error: python mysetup.py py2exe error: COREDLL.dll: No such file or directory Thanks!!!!!!! From toby at tobiah.org Mon Jan 22 16:49:00 2007 From: toby at tobiah.org (Tobiah) Date: Mon, 22 Jan 2007 13:49:00 -0800 Subject: How to convert a string into an integer In-Reply-To: <1169502340.434227.224820@11g2000cwr.googlegroups.com> References: <1169502340.434227.224820@11g2000cwr.googlegroups.com> Message-ID: <45b524a3$0$24475$88260bb3@free.teranews.com> > count = sys.argv[2] > for i in range(count): > #do some stuff for i in range(int(count)): -- Posted via a free Usenet account from http://www.teranews.com From alain.walter at thalesgroup.com Wed Jan 31 03:47:13 2007 From: alain.walter at thalesgroup.com (awalter1) Date: 31 Jan 2007 00:47:13 -0800 Subject: thread and processes with python/GTK In-Reply-To: <5297euF1ndifjU1@mid.individual.net> References: <1170151634.019690.320310@k78g2000cwa.googlegroups.com> <5297euF1ndifjU1@mid.individual.net> Message-ID: <1170233233.710517.65870@v33g2000cwv.googlegroups.com> HI, I launch my application by 'python script.py' I've already add a sys.stdout.flush with no effect. if the idle_add is an alternative to thread, where to get details about its use (no reference in http://www.pygtk.org/docs/pygtk/ index.html, but very brief information in GTK+ documentation) In my case how to implement the system call 'ps -def' through idle_add Thanks On 30 jan, 16:44, Thomas Guettler wrote: > Hi, > > how do you start the python app? Goes stdout > to a terminal or a pipe? > > "python script.py" > and "python script.py | cat" behave different. > > Maybe "sys.stdout.flush()" helps you. > > BTW, I switched from threads to idle_add for pygtk > applications. > > > > > > awalter1 wrote: > > Hello, > > > I'm developping an application with python, pyGTK and GTK+. > > I've performed many tests by using methods as Popen, popen2, > > os.system ... to communicate with Unix (HPUX), > > The last attempt is this code written in a thread : > > fin,fout = popen2.popen2('ps -def') > > line = fin.readline() > > while 1 : > > if not line : break > > print "line=",line > > line = fin.readline() > > fin.close() > > In that case, lines are printed only when I exit my application. > > Usually the behavior is not as expected and I cannot understand why. I > > am wondering that it could be a constraint from the use of GTK > > (mainloop() existence ???). > > Is somebody aware about conflict between GTK use and unix mechanism. > > > Thanks for you help > > -- > Thomas G?ttler,http://www.thomas-guettler.de/http://www.tbz-pariv.de/ > E-Mail: guettli (*) thomas-guettler + de > Spam Catcher: niemand.leerm... at thomas-guettler.de- Masquer le texte des messages pr?c?dents - > > - Afficher le texte des messages pr?c?dents - From no-spam at no-spam-no-spam.invalid Sun Jan 7 16:16:50 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 07 Jan 2007 22:16:50 +0100 Subject: Python cheatsheets In-Reply-To: References: Message-ID: gonzlobo wrote: > Curious if anyone has a python cheatsheet* published? I'm looking for > something that summarizes all commands/functions/attributes. Having > these printed on a 8" x 11" double-sided laminated paper is pretty > cool. > > * cheatsheet probably isn't the right word, but you get the idea. :) search: python quick reference e.g.: http://www.benyoonline.com/pqr/pqr24/PQR2.4.html Robert From olsonas at gmail.com Mon Jan 29 14:10:45 2007 From: olsonas at gmail.com (Drew) Date: 29 Jan 2007 11:10:45 -0800 Subject: List Behavior when inserting new items In-Reply-To: <526ut2F1n2q69U1@mid.uni-berlin.de> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> <526ut2F1n2q69U1@mid.uni-berlin.de> Message-ID: <1170097845.805992.118870@h3g2000cwc.googlegroups.com> > What is your actual usecase? > > diez The issue is that I don't know how long the list will eventually be. Essentially I'm trying to use a 2D list to hold lines that I will eventually print to the screen. Blank elements in the list will be printed as spaces. I suppose every time I add an element, I could find the difference between the size of the list and the desired index and fill in the range between with " " values, however I just wanted to see if there was a more natural way in the language. Thanks, Drew From cvanarsdall at mvista.com Wed Jan 24 12:45:04 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 24 Jan 2007 09:45:04 -0800 Subject: The reliability of python threads In-Reply-To: <17847.39003.410596.481072@montanaro.dyndns.org> References: <45B7904B.90303@mvista.com> <17847.39003.410596.481072@montanaro.dyndns.org> Message-ID: <45B79B20.9010501@mvista.com> skip at pobox.com wrote: > Carl> Does anyone have any conclusive evidence that python threads/locks > Carl> are safe or unsafe? > > In my experience Python threads are generally safer than the programmers > that use them. ;-) > Haha, yea, tell me about it. The whole GIL thing made me nervous about the locking operations happening truly atomically and not getting weird. Thanks for ensuring me that i'm just nuts :) -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From buzzard at urubu.freeserve.co.uk Sat Jan 27 21:10:18 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sun, 28 Jan 2007 02:10:18 +0000 Subject: set update in 2.5 Message-ID: <45bc0c0c.0@entanet> Hello, In moving from 2.4 to 2.5 I find that some of my unit tests are now failing. I've worked out that the problem relates to the set update method. In 2.4 I could update a set with an iterable type derived from dict as the argument. I now find that the set is updated with the hash values of the items in my iterable, rather than the items themselves. Converting to a list first gets round the problem. My iterable type has the same API as 'set' but requires items to have hashable 'uid' attributes, so they can also be looked up by uid. I hope this, and the fact that this worked fine in 2.4 will be enough to track down the issue without me having to paste reams of code (other than the following, pasted from IDLE). Any ideas? Cheers. Duncan >>> from graphItems import Node >>> from keyed_sets import KeyedSet >>> n = Node(1) >>> n.uid 1 >>> k = KeyedSet([n]) >>> k KeyedSet([1]) >>> type(iter(k).next()) >>> type(k[1]) >>> s = set() >>> s.update(list(k)) >>> type(iter(s).next()) >>> s = set() >>> s.update(k) >>> type(iter(s).next()) >>> s = set() >>> s.add(n) >>> type(iter(s).next()) >>> hash(n) 1 >>> From alec at mihailovs.com Sat Jan 6 00:44:10 2007 From: alec at mihailovs.com (Alec Mihailovs) Date: Sat, 06 Jan 2007 05:44:10 GMT Subject: Memoization in Python References: Message-ID: "Gabriel Genellina" wrote > > Nice. There is already a memoize decorator in the Python wiki: > http://wiki.python.org/moin/PythonDecoratorLibrary, you can get some ideas > from there. Using the functools module (2.5) or the decorator module by M. > Simoniato (http://www.phyast.pitt.edu/~micheles/python/documentation.html) > you can improve it so the decorated function looks more like the original. Thank you very much. Both references are very useful. Alec From __peter__ at web.de Thu Jan 18 07:51:20 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Jan 2007 13:51:20 +0100 Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: Duncan Booth wrote: > Peter Otten <__peter__ at web.de> wrote: >> But still, to help my lack of fantasy -- what would a sane zip() >> implementation look like that does not guarantee the above output? >> > Hypothetically? > > The code in zip which builds the result tuples looks (ignoring error > handling) like: > > // inside a loop building each result element... > PyObject *next = PyTuple_New(itemsize); > > for (j = 0; j < itemsize; j++) { > PyObject *it = PyTuple_GET_ITEM(itlist, j); > PyObject *item = PyIter_Next(it); > PyTuple_SET_ITEM(next, j, item); > } > > For fixed size tuples you can create them using PyTuple_Pack. So imagine > some world where the following code works faster for small tuples: > > // Outside the loop building the result list: > PyObject *a, *b, *c; > if (itemsize >= 1 && itemsize <= 3) a = PyTuple_GET_ITEM(...); > if (itemsize >= 2 && itemsize <= 3) b = PyTuple_GET_ITEM(...); > if (itemsize == 3) c = PyTuple_GET_ITEM(...); > ... > > // inside the result list loop: > PyObject *next; > if (itemsize==1) { > next = PyTuple_Pack(1, > PyIter_Next(a)); > } else if (itemsize==2) { > next = PyTuple_Pack(2, > PyIter_Next(a), > PyIter_Next(b)); > } else if (itemsize==2) { > next = PyTuple_Pack(3, > PyIter_Next(a), > PyIter_Next(b), > PyIter_Next(c)); > } else { > next = PyTuple_New(itemsize); > > for (j = 0; j < itemsize; j++) { > PyObject *it = PyTuple_GET_ITEM(itlist, j); > PyObject *item = PyIter_Next(it); > PyTuple_SET_ITEM(next, j, item); > } > } > > If compiled on a system where the stack grows downwards (as it often does) > the C compiler is very likely to evaluate function arguments in reverse > order. > > (BTW, this also assumes that it's an implementation which uses exceptions > or something for error handling otherwise you probably can't get it right, > but maybe something like IronPython could end up with code like this.) > > Or maybe if someone added PyTuple_Pack1, PyTuple_Pack2, PyTuple_Pack3 > functions which grab their memory off a separate free list for each tuple > length. That might speed up the time to create the tuples as you might be > able to just reset the content not rebuild the object each time. Again > that could make code like the above run more quickly. Special-casing small tuples meets my sanity criterion :-) Let's see if I understand the above: In C a call f(g(), g()) may result in machine code equivalent to either x = g() y = g() f(x, y) or y = g() x = g() f(x, y) Is that it? Peter From webmaster at cacradicalgrace.org Mon Jan 29 17:22:01 2007 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Mon, 29 Jan 2007 15:22:01 -0700 Subject: Overloading assignment operator References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> <1169604475.177104.40330@s48g2000cws.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 23 Jan 2007 18:07:55 -0800, Russ wrote: > >> Achim Domma wrote: >>> Hi, >>> >>> I want to use Python to script some formulas in my application. The user >>> should be able to write something like >>> >>> A = B * C >>> >>> where A,B,C are instances of some wrapper classes. Overloading * is no >>> problem but I cannot overload the assignment of A. I understand that >>> this is due to the nature of Python, but is there a trick to work around >>> this? >>> All I'm interested in is a clean syntax to script my app. Any ideas are >>> very welcome. >>> >>> regards, >>> Achim >> Why do you need to overload assignment anyway? If you overloaded "*" >> properly, it should return >> the result you want, which you then "assign" to A as usual. Maybe I'm >> missing something. > > One common reason for overriding assignment is so the left-hand-side of > the assignment can choose the result type. E.g. if Cheddar, Swiss and > Wensleydale are three custom classes, mutually compatible for > multiplication: > > B = Cheddar() # B is type Cheddar > C = Swiss() # C is type Swiss > # without overloading assignment > A = B * C # A is (possibly) Cheddar since B.__mul__ is called first > A = C * B # A is (possibly) Swiss since C.__mul__ is called first > # with (hypothetical) assignment overloading > A = B * C # A is type Wensleydale since A.__assign__ is called > > Except, of course, there is no assignment overloading in Python. There > can't be, because A may not exist when the assignment is performed, and > if it does exist it might be a complete different type. > > Instead, you can do something like this: > > A = Wensleydale(B) * Wensleydale(C) > > or > > A = Wensleydale(B * C) > > > > I think that's the first time I've actually seen someone use a Monty Python theme for a python example, and I must say, I like it. However, "We are all out of Wensleydale." Cheers, Cliff From klaus at seistrup.dk Sun Jan 28 08:42:23 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sun, 28 Jan 2007 13:42:23 +0000 (UTC) Subject: IP address References: Message-ID: Colin J. Williams wrote: > Your one-liner doesn't work for me, with Windows XP, but the > following does, within Python. Could it be due to shell-escaping issues? I don't know anything about Windows... Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From wescpy at gmail.com Fri Jan 12 17:53:54 2007 From: wescpy at gmail.com (wesley chun) Date: Fri, 12 Jan 2007 14:53:54 -0800 Subject: ANN: Advanced Python training course, Nov 8-10, San Francisco In-Reply-To: <78b3a9580610111039hf332877ke9433cc0760143c6@mail.gmail.com> References: <78b3a9580610111039hf332877ke9433cc0760143c6@mail.gmail.com> Message-ID: <78b3a9580701121453w42b5dbd4red7346a9be078401@mail.gmail.com> FINAL REMINDER... we still have some seats left! What: (Intensive) Intro to Python When: February 7-9, 2007 Where: San Francisco (SFO/San Bruno), CA, USA Web: http://cyberwebconsulting.com (click "Python Training" link) Need to get up-to-speed with Python as quickly as possible? Come join us in beautiful Northern California for another one of our rigorous Python training events! This is an intense introduction to Python directed towards those who have some proficiency in another high-level language. This course will take place in San Bruno right near the San Francisco International Airport. LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and evening reception daily The cost is only $1095 (reg $1295) per attendee. Discounts are available for multiple registrations as well as teachers/students. Registration will be opening soon for the next Intro and Advanced courses both taking place back-to-back in May 2007. See website for more details. hope to meet you soon! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From Andreas.Ames at comergo.com Wed Jan 10 05:04:27 2007 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Wed, 10 Jan 2007 11:04:27 +0100 Subject: dynamic library loading, missing symbols Message-ID: <552B6B925278EF478EA8887D7F9E5AC301C3F9F9@tndefr-ws00024.tenovis.corp.lan> Some random notes below ... > -----Original Message----- > From: python-list-bounces+andreas.ames=comergo.com at python.org > [mailto:python-list-bounces+andreas.ames=comergo.com at python.or > g] On Behalf Of dfj225 at gmail.com > Sent: Wednesday, January 10, 2007 1:26 AM > Subject: dynamic library loading, missing symbols > > The reason for the complication is that I don't have control over how > the library does dlopen() or how the code that calls dlopen was > compiled. I am, however, able to control the build process for the > Boost.Python wrapper and the original C++ code that the Boost.Python > wraps. I've tried as many linker tricks as I can think of to get this > to work. Both the boost wrapper and the C++ code that it wraps are > built using --export-dynamic. * Make sure the exported symbols are marked "extern C" * Otherwise (you export C++ symbols), make sure the exporting component uses *exactly* the same compiler (version, ABI-influencing flags and all) as the importing component. * IMHO, C++ .sos are principally painful and almost unbearable, if you have (non-source) third party components involved. * Use nm to find the exact names of the exported and imported symbols (as already suggested). > > Is there a way to set at runtime what directories or libraries the > linker should search for these symbols? I have set LD_LIBRARY_PATH > correctly, but that didn't seem to affect anything. > > For reference, I am running on Gentoo linux 2.6.11.12 with gcc 3.4.4 > > I'm interested in any ideas that might help, but the ideal one should > work on any *nix system and not just linux. * You might read http://people.redhat.com/drepper/dsohowto.pdf, which I found very useful. There are ways described, how to control the way, the dynamic loader resolves symbols, all with their resp. caveats. * Nevertheless it only describes ELF-based systems, and mostly systems using Drepper's own .so-loader. * Portability to e.g. Windows is a almost impossible for you, because it doesn't support undefined symbols in .sos (and Drepper suggests on ELF-based systems this should only be used if absolutely unavoidable, IIRC). NB: There is a project on SF which claimes to provide this feature on Windows, but I haven't tried and it limits your choice of tools (http://edll.sf.net/). cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 711 13586 7789 | ames AT avaya DOT com From gagsl-py at yahoo.com.ar Sun Jan 21 19:37:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Jan 2007 21:37:57 -0300 Subject: instancemethod References: Message-ID: "Gert Cuykens" escribi? en el mensaje news:ef60af090701211416n5b2eb7edt2ee6d4555bd49c1a at mail.gmail.com... > class Db: > > _db=-1 > _cursor=-1 > > @classmethod > def __init__(self,server,user,password,database): > self._db=MySQLdb.connect(server , user , password , database) > self._cursor=self._db.cursor() > > @classmethod > def excecute(self,cmd): > self._cursor.execute(cmd) > self._db.commit() > > > if __name__ == '__main__': > gert=Db('localhost','root','******','gert') > gert.excecute('select * from person') > for x in range(0,gert.rowcount): > print gert.fetchone() > gert.close() Besides your specific question that was already answered, why are you using classmethods at all? You are constructing a Db instance and using it as if all were normal instance methods... Just remove all those @classmethod declarations and use it in a standard way. -- Gabriel Genellina From adamgarstang at googlemail.com Fri Jan 5 16:44:43 2007 From: adamgarstang at googlemail.com (Adam) Date: 5 Jan 2007 13:44:43 -0800 Subject: Learning to program in Python In-Reply-To: <1168028517.005902.172880@11g2000cwr.googlegroups.com> References: <1168028517.005902.172880@11g2000cwr.googlegroups.com> Message-ID: <1168033483.361615.53570@42g2000cwt.googlegroups.com> jbchua wrote: > Hello everybody. > > I am an Electrical Engineering major and have dabbled in several > languages such as Python, C, and Java in my spare time because of my > interest in programming. However, I have not done any practical > programming because I have no idea where to get started. I taught > myself these languages basically by e-tutorials and books. This makes > me feel as if I don't really know how to implement these languages. > Does anybody have any advice on where to start applying my limited > knowledge practically in order to advance my learning? I am just starting to learn to program as well. (In my spare time.) The advice about deciding on a goal, a project to work on, is good. I have just got through the basics section in this guide here (http://www.freenetpages.co.uk/hp/alan.gauld/), which I found very useful for beginners and the address book example you build up shows the python in practice. Once I had learnt about file inp/out I decided to make a program that would split a file in half for email and then could be used to join them together again. This helped me get used to most of what I had learnt in the beginner section. Also don't forget the Python.org documentation it's very helpful and is a great companion to most the 3rd party tutorials around. From Thomas.Ploch at gmx.net Thu Jan 4 09:32:21 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Thu, 04 Jan 2007 15:32:21 +0100 Subject: Best way to implement a timed queue? Message-ID: <459D0FF5.4020703@gmx.net> Hello folks, I am having troubles with implementing a timed queue. I am using the 'Queue' module to manage several queues. But I want a timed access, i.e. only 2 fetches per second max. I am horribly stuck on even how I actually could write it. Has somebody done that before? And when yes, how is the best way to implement it? Thanks, Thomas From mclaugb at nospm.yahoo.com Sat Jan 20 11:07:43 2007 From: mclaugb at nospm.yahoo.com (mclaugb) Date: Sat, 20 Jan 2007 16:07:43 -0000 Subject: scipy.optimize.lbfgsb help please!!! Message-ID: Does anyone out there have a piece of code that demonstrates the use of the lbfgsb multivariate, bounded solver in the scipy.optimize toolkit? An example would get me started because my code below does not seem to work. Thanks alot, Bryan I have tried to use the LBFGSB optimisation algorithm with these parameters: xstart = [20,-20] x, f, d = lbfgsb.fmin_l_bfgs_b(Permmin, x0, Jacobi, params, 0, [(0,100),(0,-50)] , 10, 1e7, 1e-5, 1e-8, -1, 500) I am getting this error: " x, f, d = lbfgsb.fmin_l_bfgs_b(Permmin, x0, Jacobi, params, 0, [(.001,100),(-50,-.001)] , 10, 1e7, 1e-5, 1e-8, -1, 500) File "C:\Python24\lib\site-packages\scipy\optimize\lbfgsb.py", line 197, in fmin_l_bfgs_b isave, dsave) ValueError: failed to initialize intent(inout) array -- expected elsize=8 but got 4 -- input 'l' not compatible to 'd' " Permmin is a function that simply returns a vector array [xmin, ymin] Jacobi returns an array [[A,B],[C,D]] which is the 2x2 Jacobi matrix The rest of the parameters seem okay... From bdesth.quelquechose at free.quelquepart.fr Tue Jan 2 11:05:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Jan 2007 17:05:35 +0100 Subject: Convert Perl to Python In-Reply-To: References: Message-ID: <459a7cb4$0$693$426a74cc@news.free.fr> Marc 'BlackJack' Rintsch a ?crit : > In , > ???????? ?????? wrote: > > >>How can I convert a perl script to Python? > > > Look what the Perl script does and then rewrite it in Python. Automatic > translations between programming languages, if possible, usually result in > code that is not supposed to be read by human beings. Every language has > its idioms and a "literal" translation looks very odd to "native speakers" > of the target language. and might be quite inefficient too... From auch-ich-m at g-kein-spam.com Tue Jan 30 01:36:51 2007 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Tue, 30 Jan 2007 07:36:51 +0100 Subject: List Behavior when inserting new items References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> <1170099535.989235.35800@a75g2000cwd.googlegroups.com> <1170102302.883700.87810@m58g2000cwm.googlegroups.com> Message-ID: <3427741.k3zYug0IVv@news.perlig.de> * Paul McGuire wrote: >> py> def __init__(self, arg = []): >> py> self.__list = arg > > Please don't perpetuate this bad habit!!! "arg=[]" is evaluated at > compile time, not runtime, and will give all default-inited llists the > same underlying list. While this actually might be bad habit, the default arguments are *not* eval'd at compile time. This seems to be a common mistake. They are evaluated at runtime as everything else. The difference to other local variables is, that the objects they're referring to are just initalized once instead of each time they're taken into account. nd -- die (eval q-qq[Just Another Perl Hacker ] ;-) # Andr? Malo, # From vinay_sajip at yahoo.co.uk Mon Jan 22 00:09:56 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 21 Jan 2007 21:09:56 -0800 Subject: selective logger disable/enable References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> <1169349399.938121.238430@38g2000cwa.googlegroups.com> <1169395276.181654.160810@a75g2000cwd.googlegroups.com> <1169437763.213781.163660@38g2000cwa.googlegroups.com> Message-ID: <1169442596.209314.162410@s34g2000cwa.googlegroups.com> Gary Jefferson wrote: > I am still a bit confused about Filters, though. It seems they are a > bit of an anomoly in the hierarchical view of loggers that the API > supports elsewhere, i.e., filters don't seem to inherit... Or am I > missing something again? Here's a quick example: > > import logging > > log1 = logging.getLogger("top") > log2 = logging.getLogger("top.network") > log3 = logging.getLogger("top.network.tcp") > log4 = logging.getLogger("top.network.http") > log5 = logging.getLogger("top.config") > log6 = logging.getLogger("top.config.file") > > logging.basicConfig(level=logging.DEBUG, > format='%(asctime)s %(levelname)s %(message)s') > > filter = logging.Filter("top.network") > log1.addFilter(filter) # only affects log1, do this for each of log2-7 > too? > > log1.debug("I'm top") > log2.debug("I'm top.network") > log3.debug("I'm top.network.tcp") > log4.debug("I'm top.network.http") > log5.debug("I'm top.config") > log6.debug("I'm top.config.file") > > > This is only for the binary case (and I think if I ignore the binary > case and filters altogether as you suggested), but it really would be > nice to be able to squelch /all/ output from loggers that belong to > certain parts of the namespace by using a filter as above (which I > can't get to work). > > Perhaps if I set up a basicConfig with a loglevel of nothing, I can get > this to approximate squelching of everything but that which I > explicitly setLevel (which does inherit properly). > > In other words, the addFilter/removeFilter part of the API seems rather > impotent if it can't be inherited in the logging namespaces. In fact, > I can't really figure out a use case where I could possibly want to use > it without it inheriting. Obviously I'm missing something. I'm sure > I've consumed more attention that I deserve already in this thread, > but, do you have any pointers which can enlighten me as to how to > effectively use addFilter/removeFilter? I don't really think there's a problem with the logging API - it went through a fair amount of peer review on python-dev before making it into the Python distribution. You need to use what's there rather than shoehorn it into how you think it ought to be. Filters are for more esoteric requirements - you can see some examples of filters in the old (out of date) standalone distribution at http://www.red-dove.com/python_logging.html (download and examine some of the test scripts). Loggers aren't binary - levels are there to be used. Most people get by with judicious use of levels, using Filters on loggers only for unusual cases. Since Filters are only meant to be used in unusual situations, there is no need to think about inheriting them. Filters can be set on Handlers so that even if Loggers log the events, they don't go to any output if filtered out at the handlers for that output. BTW I would also advise reading PEP-282 to understand more about the logging approach. Best regards, Vinay Sajip From bthom at cs.hmc.edu Thu Jan 4 13:54:04 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Thu, 04 Jan 2007 10:54:04 -0800 Subject: Set type? In-Reply-To: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> References: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> Message-ID: I've seen people do that using an exception, e.g. try: foo except : #variable foo not defined On Jan 4, 2007, at 10:48 AM, _ wrote: > How do you check to see if a variable is a set? I would like to use > > if type(var) is types.SetType: > blah > > but that is not available in types module. I am using 2.4 > > -- > http://mail.python.org/mailman/listinfo/python-list From steven.bethard at gmail.com Thu Jan 18 18:41:48 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 18 Jan 2007 16:41:48 -0700 Subject: A note on heapq module In-Reply-To: <1169159235.864192.263210@v45g2000cwv.googlegroups.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> <1169117876.063858.56570@s34g2000cwa.googlegroups.com> <8NSdnf38_otYcjLYnZ2dnUVZ_tadnZ2d@comcast.com> <1169159235.864192.263210@v45g2000cwv.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Steven Bethard wrote: >> The current code fails when using unbound methods however:: > > I don't like your solution, this class was already slow enough. Don't > use unbound methods with this class :-) > Maybe there's a (better) solution to your problem: to make Heap a > function (or classmethod) that return sone of two possibile objects > created by one of two different classes that have different methods... That's probably viable. Maybe you should just have two separate classes: Heap and KeyedHeap. The inplace= parameter doesn't really make sense for a KeyedHeap anway, so you could just have:: Heap(sequence=None, inplace=False) KeyedHeap(key, sequence=None) Of course, this approach ends up with a bunch of code duplication again. STeVe From bj_666 at gmx.net Tue Jan 2 06:03:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 02 Jan 2007 12:03:57 +0100 Subject: Difference between __init__ (again) and nothing ... References: Message-ID: In , Stef Mientki wrote: > What's the difference between using __init__ and using nothing, > as the examples below. > > class cpu: > PC = 4 This is a *class attribute*. It's the same for all instances of `cpu`. > class cpu: > def __init__: > self.PC = 4 This is an *instance attribute* which is set in every instance of `cpu`. In [8]: class CPU_1: ...: PC = 4 ...: In [9]: class CPU_2: ...: def __init__(self): ...: self.PC = 4 ...: In [10]: a = CPU_1() In [11]: b = CPU_1() In [12]: a.PC, b.PC Out[12]: (4, 4) In [13]: CPU_1.PC = 3.5 In [14]: a.PC, b.PC Out[14]: (3.5, 3.5) In [15]: c = CPU_2() In [16]: d = CPU_2() In [17]: c.PC, d.PC Out[17]: (4, 4) In [18]: c.PC = 3.5 In [19]: c.PC, d.PC Out[19]: (3.5, 4) Ciao, Marc 'BlackJack' Rintsch From nagle at animats.com Tue Jan 30 13:06:51 2007 From: nagle at animats.com (John Nagle) Date: Tue, 30 Jan 2007 18:06:51 GMT Subject: The reliability of python threads In-Reply-To: References: Message-ID: <%OLvh.67202$qO4.51886@newssvr13.news.prodigy.net> Aahz wrote: > In article , > Carl J. Van Arsdall wrote: > My point is that an app that dies only once every few months under load > is actually pretty damn stable! That is not the kind of problem that > you are likely to stimulate. This has all been so vague. How does it die? It would be useful if Python detected obvious deadlock. If all threads are blocked on mutexes, you're stuck, and at that point, it's time to abort and do tracebacks on all threads. You shouldn't have to run under a debugger to detect that. Then a timer, so that if the Global Python Lock stays locked for more than N seconds, you get an abort and a traceback. That way, if you get stuck in some C library, it gets noticed. Those would be some good basic facilities to have in thread support. In real-time work, you usually have a high-priority thread which wakes up periodically and checks that a few flags have been set indicating progress of the real time work, then clears the flags. Throughout the real time code, flags are set indicating progress for the checking thread to notice. All serious real time systems have some form of stall timer like that; there's often a stall timer in hardware. John Nagle From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 23:10:36 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 15:10:36 +1100 Subject: Determining when a file is an Open Office Document References: <1169171820.851021.49200@l53g2000cwa.googlegroups.com> <1169239691.159739.304050@l53g2000cwa.googlegroups.com> Message-ID: On Fri, 19 Jan 2007 12:48:14 -0800, Ross Ridge wrote: > tubby wrote: >> Now, If only I could something like that on PDF files :) > > PDF files should begin with "%PDF-" followed by a version number, eg. > "%PDF-1.4". The PDF Reference notes that Adobe Acrobat Reader is a bit > more flexiable about what it will accept: > > 13. Acrobat viewers require only that the header appear > somewhere within the first 1024 bytes of the file. > 14. Acrobat viewers also accept a header of the form > %!PS-Adobe-N.n PDF-M.m > > So identifying PDF files is pretty easy. Sure. MIS-identifying PDF files is pretty easy. Identifying them is not. Consider this example: $ cat not_a_pdf %PDF-1.4 This is not a pdf file. $ file not_a_pdf not_a_pdf: PDF document, version 1.4 Is there a security vulnerability buried in the detection of file types by magic bytes? I don't know, but I wouldn't be surprised if there were. Here's another example: $ cat not_a_gif.txt GIF89a is the header used to define a GIF file. $ file not_a_gif.txt not_a_gif: GIF image data, version 89a, 26912 x 8307 Any file system that doesn't have file type metadata is reduced to guessing the type of the file, and guesses can be wrong. As heuristics go, "look at the characters after the dot in the file name" is not that much worse than "look at the bytes at offset X through Y inside the file", and has the significant advantage that it is visible and easy to change for the end user. -- Steven. From david at boddie.org.uk Wed Jan 17 10:51:40 2007 From: david at boddie.org.uk (David Boddie) Date: 17 Jan 2007 07:51:40 -0800 Subject: The proper use of QSignalMapper References: <1169045073.138626.60770@l53g2000cwa.googlegroups.com> Message-ID: <1169049100.393777.269350@v45g2000cwv.googlegroups.com> borntonetwork wrote: > I am trying to implement QTCore.QSignalMapper using PyQT. I finally got > to a point where I don't receive any compile or runtime error messages, > but I also do not see the final slot function fire off. Here is a > snippet of the code: > > self.signalMapper = QtCore.QSignalMapper(window) > # Use qsignalmapper to use of one slot function for multiple > # widgets. The map() function sends the slot an extra param > # that identifies the sender. > for idx in range(1, maxIngredients+1): > wName = 'chkProductIngredientsDelete_'+str(idx) > w = self.__dict__[wName] > self.app.connect(w, QtCore.SIGNAL("stateChanged(int)"), > self.signalMapper, > QtCore.SLOT("self.signalMapper.map")) You need to pass the C++ signature to the SLOT() function. I believe you want the form that does not accept any arguments: self.app.connect(w, QtCore.SIGNAL("stateChanged(int)"), self.signalMapper, QtCore.SLOT("map()")) Alternatively, you can pass the slot directly to the function: self.app.connect(w, QtCore.SIGNAL("stateChanged(int)"), self.signalMapper.map) PyQt accepts Python methods as slots, without requiring that they be wrapped in calls to SLOT(). David From gagsl-py at yahoo.com.ar Sun Jan 7 14:19:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 11:19:58 -0800 Subject: A problem in embedding Python in a plug-in In-Reply-To: References: Message-ID: <1168197598.864406.39950@s34g2000cwa.googlegroups.com> On 6 ene, 15:29, Koichi wrote: > Hi, I'm now making a plug-in for a CG software. I embed > Python in a plugin and it works. The problem is that it > conflicts with other plugins that also embeds Python because it > runs in the same thread. I don't know when Py_Initialize() and Given all those constraints, I think the only safe option is to run Python in another process. You write a very simple plugin (NOT in Python, maybe C code) that spawns another process (the actual Python code) and forwards all requests to that other process, using some form of IPC. -- Gabriel Genellina From albert.wellens at gmail.com Tue Jan 16 17:19:04 2007 From: albert.wellens at gmail.com (awel) Date: 16 Jan 2007 14:19:04 -0800 Subject: Check a windows service In-Reply-To: References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> <1168967374.568967.173690@11g2000cwr.googlegroups.com> Message-ID: <1168985943.060145.54490@a75g2000cwd.googlegroups.com> Sorry, but could you give me an example with a real service 'cause I've tried this script but nothings happened, no error, nothings ; even if I launch it in cmd prompt. Thanks Chris Mellon a ?crit : > On 16 Jan 2007 09:09:34 -0800, Tim Golden wrote: > > awel wrote: > > > > > I'm new in python and I would like to know if it's possible to check if > > > a specific windows service is present and if it's possible how can I > > > do? > > > > This is one way: > > > > http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services > > > > You'd have to change that example slightly, but I > > hope the principal is clear enough. If not, ask again. > > > > TJG > > > > Here's some code cut & pasted from the demos included in the win32 module: > > import win32service > import win32con > > > def EnumServices(): > resume = 0 > accessSCM = win32con.GENERIC_READ > accessSrv = win32service.SC_MANAGER_ALL_ACCESS > > #Open Service Control Manager > hscm = win32service.OpenSCManager(None, None, accessSCM) > > #Enumerate Service Control Manager DB > > typeFilter = win32service.SERVICE_WIN32 > stateFilter = win32service.SERVICE_STATE_ALL > > statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter) > for (short_name, desc, status) in statuses: > print short_name, desc, status From MrJean1 at gmail.com Wed Jan 17 21:36:43 2007 From: MrJean1 at gmail.com (MrJean1) Date: 17 Jan 2007 18:36:43 -0800 Subject: Asyncore select statement problem In-Reply-To: <1169075120.491855.103200@q2g2000cwa.googlegroups.com> References: <1169075120.491855.103200@q2g2000cwa.googlegroups.com> Message-ID: <1169087803.896785.110630@s34g2000cwa.googlegroups.com> Try using another ascyncore example and see if that works for you. Maybe, first one without threading, like Asyncore worked fine on my application on Linux, but haven't tried that on MacOS. /Jean Brouwers JamesHoward wrote: > I have a problem with python's asyncore module throwing a bad file > descriptor error. The code might be difficult to copy here, but the > problem is essentially: > > The server wants to sever the connection of an open Asyncore socket. > Calling the socket.close() nor the socket.shutdown(2) calls seem to > work. The only way I can close the connection without creating the > error below is to have the client close the connection. > > I have the asyncore.loop() as the last line of a thread that is spawned > within the applications "mainframe.py" or gui thread. It doesn't seem > to me like this would make a difference, but I am unfamiliar with the > specifics of how the asyncore module works. > > Any thoughts people have would be greatly appreciated. If needed I may > be able to create a small version of the problem to post for people to > see. > > Thanks, > Jim Howard > > > Exception in thread Thread-1: > Traceback (most recent call last): > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", > line 460, in __bootstrap > self.run() > File > "/Users/jwhoward2/Documents/Projects/LJServer/LJDeviceServer/DeviceServer.py", > line 23, in run > asyncore.loop() > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/asyncore.py", > line 191, in loop > poll_fun(timeout, map) > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/asyncore.py", > line 121, in poll > r, w, e = select.select(r, w, e, timeout) > error: (9, 'Bad file descriptor') From jdvolz at gmail.com Thu Jan 18 03:21:08 2007 From: jdvolz at gmail.com (jdvolz at gmail.com) Date: 18 Jan 2007 00:21:08 -0800 Subject: urllib2 and transfer-encoding = chunked Message-ID: <1169108468.497013.228520@l53g2000cwa.googlegroups.com> I am having errors which appear to be linked to a previous bug in urllib2 (and urllib) for v2.4 and v2.5 of Python. Has this been fixed? Has anyone established a standard workaround? I keep finding old posts about it, that basically give up and say "well it's a known bug." Any help would be greatly appreciated. From nmm1 at cus.cam.ac.uk Thu Jan 25 16:17:19 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 25 Jan 2007 21:17:19 GMT Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> In article <1169754601.992058.205640 at q2g2000cwa.googlegroups.com>, "Paddy" writes: |> |> No, you should think of the service that needs to be up. You seem to be |> talking about how it can't be fixed rather than looking for ways to |> keep things going. A little learning is fine but "it can't |> theoretically be fixed" is no solution. I suggest that you do invest in a little learning and look up Poisson processes. |> Keep your eye on the goal and your more likely to score! And, if you have your eye on the wrong goal, you would generally be better off not scoring :-) Regards, Nick Maclaren. From ptmcg at austin.rr._bogus_.com Thu Jan 11 09:31:48 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 11 Jan 2007 08:31:48 -0600 Subject: Type casting a base class to a derived one? References: Message-ID: <45a64a53$0$16752$4c368faf@roadrunner.com> "Peter Otten" <__peter__ at web.de> wrote in message news:eo5bia$re6$00$1 at news.t-online.com... > Frederic Rentsch wrote: > >> If I derive a class from another one because I need a few extra >> features, is there a way to promote the base class to the derived one >> without having to make copies of all attributes? >> >> class Derived (Base): >> def __init__ (self, base_object): >> # ( copy all attributes ) >> ... >> >> This looks expensive. Moreover __init__ () may not be available if it >> needs to to something else. > > base_instance = Base(...) > base_instance.__class__ = Derived > > Peter This will change the class-level behavior of the object, but it wont automagically populate the instance with any attributes that are specifically added in Derived's __init__. class A(object): def __init__(self,x): self.x = x def method(self): print "I am an A whose x value is", self.x class B(A): bb = 1000 def __init__(self,x,y): super(B,self).__init__(x) self.y = y def method(self): print "I am a B whose x value is", self.x aobj = A(100) aobj.method() aobj.__class__ = B aobj.method() print aobj.bb print aobj.y prints: I am an A whose x value is 100 I am a B whose x value is 100 1000 Traceback (most recent call last): File "dertest.py", line 20, in ? print aobj.y AttributeError: 'B' object has no attribute 'y' But it wouldn't be hard to write a makeBaseIntoDerived method: def makeAintoB(a,y=0): a.y = y a.__class__ = B -- Paul From noway at ask.me Wed Jan 24 09:02:19 2007 From: noway at ask.me (Giovanni Bajo) Date: Wed, 24 Jan 2007 15:02:19 +0100 Subject: Missing .dlls when installing PyQt!? :( In-Reply-To: <1169645779.368746.157750@l53g2000cwa.googlegroups.com> References: <1169645779.368746.157750@l53g2000cwa.googlegroups.com> Message-ID: On 24/01/2007 14.36, wd.jonsson at gmail.com wrote: > I must be doing something wrong here because I'm getting all these > missing .dll messages after installing PyQT. This is what I've done (no > step excluded): > > 1. Fresh installation of Python25 > 2. I run the PyQt-gpl-4.1.1-Py2.5-Qt4.2.2.exe file which should include > SIP > 3. I run the qt-win-opensource-4.2.2-mingw.exe file > 4. I try to launch the C:\Program > Files\PyQt4\examples\tools\qtdemo\qtdemo.pyw file > > Result: > Error message says: Can't find mingwm10.dll > > After searching for the file I found it in the C:\Qt\4.2.2\bin > directory. I copied the dll to the windows dir just to run in to the > next missing dll error (QtCore4.dll) which is also located in the same > directory. What have I missed? I've been trying to install QT for 6 > hours now... Add C:\Qt\4.2.2\bin to your PATH. -- Giovanni Bajo From michele.simionato at gmail.com Tue Jan 16 11:21:34 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 16 Jan 2007 08:21:34 -0800 Subject: arguments of a function/metaclass In-Reply-To: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> References: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> Message-ID: <1168964489.326155.169680@l53g2000cwa.googlegroups.com> rubbishemail at web.de wrote: > Hello, > > > I have a member function with many (20) named arguments > > def __init__(self,a=1,b=2): > self.a=a > self.b=b > > I would like to get rid of the many redundant lines like self.a=a and > set the members automatically. > The list of default arguments could be given like > > def __init__(**kwargs): > arglist={"a":1,"b":2] > > if this makes things easier > > Of course there has to be a check that raises an error in case of an > unknown argument not mentioned in this list. > > > I am sure there is an elegant way how to do this, could you give me any > hints??? > def __init__(self, **kw): vars(self).update(kw) Michele Simionato From goodepic at gmail.com Fri Jan 5 16:44:26 2007 From: goodepic at gmail.com (goodepic) Date: 5 Jan 2007 13:44:26 -0800 Subject: Problem Running Working Code on Mac In-Reply-To: <1168030884.878349.119950@38g2000cwa.googlegroups.com> References: <1167946511.531632.41750@11g2000cwr.googlegroups.com> <1168030884.878349.119950@38g2000cwa.googlegroups.com> Message-ID: <1168033466.497889.243300@s34g2000cwa.googlegroups.com> I got pgdb installed right, so I've got no more warnings. Otherwise the output is exactly the same as quoted above!! From gagsl-py at yahoo.com.ar Wed Jan 10 05:35:11 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Jan 2007 07:35:11 -0300 Subject: convert binary data to int In-Reply-To: <1168424278.193439.216770@k58g2000hse.googlegroups.com> References: <1168424278.193439.216770@k58g2000hse.googlegroups.com> Message-ID: <7.0.1.0.0.20070110073244.03fe7488@yahoo.com.ar> At Wednesday 10/1/2007 07:17, rubbishemail at web.de wrote: >I need to convert a 3 byte binary string like >"\x41\x00\x00" to 3 int values ( (65,0,0) in this case). >The string might contain characters not escaped with a \x, like >"A\x00\x00" py> [ord(x) for x in "\x41\x00\x00"] [65, 0, 0] py> [ord(x) for x in "A\x00\x00"] [65, 0, 0] py> "\x41\x00\x00" == "A\x00\x00" True py> "\x41\x00\x00" is "A\x00\x00" True (The last test is actually irrelevant, however) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From mail at microcorp.co.za Fri Jan 12 01:12:03 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Jan 2007 08:12:03 +0200 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <009301c73610$944d0280$03000080@hendrik> "Nick Maclaren" wrote: > Yes, but that wasn't their point. It was that in (say) iterative > algorithms, the error builds up by a factor of the base at every step. > If it wasn't for the fact that errors build up, almost all programs > could ignore numerical analysis and still get reliable answers! > > Actually, my (limited) investigations indicated that such an error > build-up was extremely rare - I could achieve it only in VERY artificial > programs. But I did find that the errors built up faster for higher > bases, so that a reasonable rule of thumb is that 28 digits with a decimal > base was comparable to (say) 80 bits with a binary base. > I would have thought that this sort of thing was a natural consequence of rounding errors - if I round (or worse truncate) a binary, I can be off by at most one, with an expectation of a half of a least significant digit, while if I use hex digits, my expectation is around eight, and for decimal around five... So it would seem natural that errors would propagate faster on big base systems, AOTBE, but this may be a naive view.. - Hendrik From nagle at animats.com Wed Jan 24 12:15:04 2007 From: nagle at animats.com (John Nagle) Date: Wed, 24 Jan 2007 17:15:04 GMT Subject: Python does not play well with others In-Reply-To: References: Message-ID: Harry George wrote: > John Nagle writes: > You experience isn't shared by everyone. Some of us find Python the > most functional and portable of the candidates you mention. The language is fine. It's the bindings to other packages that are the problem. There are three different packages for talking to OpenSSL, and they're all broken in some important way. What's actually needed on the SSL side, I think, is to add bindings to the built-in SSL to export the functionality the M2Crypto C binding module has. Preferably with better attention to reference count problems, and without using SWIG. Then move over the Python portions of M2Crypto. Some problems, all of which are known and logged bugs: - The built in SSL package doesn't actually validate anything, and will happily accept bogus SSL certificates. - The built in SSL package doesn't allow access to most of the fields of an SSL certificate, and the ones you can get are returned in a debug format that's not parseable. - M2Crypto has OpenSSL and SWIG version dependencies beyond what is documented. The latest version of SWIG has a problem which breaks builds with older versions of OpenSSL. - M2Crypto may still have a memory leak associated with contexts. (Check out "close" in "Context".) - M2Crypto doesn't understand SSL certificates which support a list of sites. - M2Crypto and the socket library don't play nice about timeouts. Most of these problems have been known for years. The last person to try to fix this was treated so badly he stopped contributing. Read the bug history for "[1114345] Add SSL certificate validation". It's sad. John Nagle From gagsl-py at yahoo.com.ar Tue Jan 9 14:24:11 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Jan 2007 16:24:11 -0300 Subject: private variables In-Reply-To: References: <74E534EE-D260-409D-8E91-0182BB897B94@cs.hmc.edu> <45A331FE.90509@gmx.net> Message-ID: <7.0.1.0.0.20070109162039.00fd0770@yahoo.com.ar> At Tuesday 9/1/2007 04:38, belinda thom wrote: >I knew it was a beehive, but I had hoped someone would know which >version they were released, so I can put the proper statement into my >tutorial (e.g. In version , Python provided some support for >private variables...). I've been avoiding getting stung b/c I see >both sides and have no preference for one vs. the other. 1.5, but I doubt anyone is still using a version earlier than 1.52 anymore. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rweth at cisco.com Sat Jan 6 14:03:33 2007 From: rweth at cisco.com (rweth) Date: Sat, 06 Jan 2007 11:03:33 -0800 Subject: nntplib downloads content with extra linebreaks Message-ID: <1168110213.436860@sj-nntpcache-1.cisco.com> I am using nntplib to download archived xml messages from our internal newsgroup. This is working fine except the download of files to the connected server, has extra embedded lines in them (all over the place), from the s.body(id,afile) # body method Is there any way to employ this library to strip out these extra line breaks? I know this may seem trivial but they cause serious issues when I try and employ the subsequent downloaded xml file for a series of processes. When I forward one of these files from Thunderbird (via the newsgroup) to outlook and open it up, and then select "ignore extra line breaks", and cut and paste the content .. all is well. The file is "healed". Apart from being just a plain annoyance (all this manual steps) it really bothers me something this trivial (the pretty-fication of content) would throw me out of whack so badly .. also that outlook has some simple method that magically does what I need and I cannot hack it for myself. (not to mention how brittle the xml processing we must have in place is .. ) First I thought it was a call to RFC 977(or below) which I cannot work out, but which does the deed! But then I though that the content of the forwarded msg has something in it which outlook can filter .. because the forwarded msg is encapsulated, and likely cut off from the news server. (what do I know these are guesses) From tjgolden at gmail.com Fri Jan 26 09:49:25 2007 From: tjgolden at gmail.com (Tim Golden) Date: 26 Jan 2007 06:49:25 -0800 Subject: Win XP "Sleep" mode: can Py wake up? In-Reply-To: References: Message-ID: <1169822965.152810.317940@q2g2000cwa.googlegroups.com> > Does anyone have any experience having python deal with sleep mode? I'd > love to run something that would hear a sleep event coming and pickle > some data before sleep, then after coming out of sleep, unpickle... It should, in theory, be possibly by trapping the WMI Win32_PowerManagementEvent event. I haven't time to try it out at the moment, unfortunately. Alternatively, the WM_POWERBROADCAST message looks hopeful if you wanted to go the Message Loop route. TJG From moin at blackhole.labs.rootshell.ws Tue Jan 16 18:28:15 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Tue, 16 Jan 2007 17:28:15 -0600 Subject: POSH Query Message-ID: <20070116172815.2c75c30f.moin@blackhole.labs.rootshell.ws> Hi Folks, I am implementing a multithreaded Network application in Python. As most of you know that the GIL hinders the performance scalablity in SMP machines. I came across POSH. Here they talk about multiple instances of Python Interpreter sticking around a Shared memory , bypassing the GIL effect. Is anybody tried the POSH - does it really increases the performance ?? How good or bad is to have the POSH module imported into ones Python code. Please share your experience, if any, about POSH. Cheers Moin -- S.Mohideen From rodperson at comcast.net Fri Jan 19 18:34:21 2007 From: rodperson at comcast.net (Rod Person) Date: Fri, 19 Jan 2007 18:34:21 -0500 Subject: Help with creating processes Message-ID: <20070119183421.04311f34@atomizer.opensourcebeef.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm trying to create a simple gui wrapper for the handbrake dvd ripper with python 2.4 on a FreeBSD system. My problem is this. I want to scan the dvd to see all the titles and chapters. The handbrake command for this is: handbrake -i /dev/acd0 -t 0 I've tried: cmd = '/usr/local/bin/handbrake -i /dev/acd0 -t 0' rtn = os.popen(cmd) but the script exists before the disk has finished scanning. If I change cmd to 'ls' it work as I expected. My problem is that the scanning of the DVD can take upto a minute or more and os.popen doesn't seem to wait - although I thought it was suppose to? I've tried using subprocess.call and popen2 etc but nothing seems to wait for the return. Can someone give me a hint? - -- Rod "it takes an unusual mind to see the obvious." - - Alfred Whitehead -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.5 (FreeBSD) iD8DBQFFsVWA3rDijyy3LEcRAia4AJ4hWZosgDeFeK4dkKdMg9ZwmAebeACfVqkQ pGiJ7pL1/d1tVszxF0kzSjQ= =Jz9+ -----END PGP SIGNATURE----- From theller at ctypes.org Wed Jan 3 16:07:59 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 03 Jan 2007 22:07:59 +0100 Subject: M. Hammonds python panel In-Reply-To: <1167856840.117284.78420@k21g2000cwa.googlegroups.com> References: <1167856840.117284.78420@k21g2000cwa.googlegroups.com> Message-ID: jUrner at arcor.de schrieb: > Hello all > > I am a great fan of Mark Hammonds python pannel. But since starship > went down it didn't come up again ...with the link in my favs to > http://starship.python.net/crew/mhammond/mozilla/pythonpanel.xul > still pointing nowhere. > > Maybe Mark is around here somewhere... It may be better to mail him directly. You should be able to find his email address. Thomas From olsongt at verizon.net Mon Jan 8 15:29:36 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: 8 Jan 2007 12:29:36 -0800 Subject: Execute binary code In-Reply-To: <1168284300.638111.191440@38g2000cwa.googlegroups.com> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> Message-ID: <1168288176.054142.232780@s80g2000cwa.googlegroups.com> citronelu at yahoo.com wrote: > Is it possible to execute a binary string stored within a python script > as executable code ? > > The script is run under Windows, and the binary code (a full executable > file) is stored in a variable in the script. > > I know I can use os.system() or os.popen() to run an external file, but > these functions take as argument a string evaluated as command-line. > > I also know I could save the binary code as a temporary file, execute > it and delete it afterwards, but this is not an alternative. > > Thanks. It's not impossible, that's basically what I did on a smaller scale in pyasm: http://mysite.verizon.net/olsongt/ A small C-stub executes arbirary asm that was originally built as a string. The tough part for you would be loading all of the referenced .dlls into memory and patching in all the relocations from the source COFF file. It'll be a pain but not entirely impossible. From paddy3118 at netscape.net Fri Jan 26 04:24:39 2007 From: paddy3118 at netscape.net (Paddy) Date: 26 Jan 2007 01:24:39 -0800 Subject: The reliability of python threads In-Reply-To: References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> Message-ID: <1169803479.668543.228510@q2g2000cwa.googlegroups.com> On 26 Jan, 09:05, n... at cus.cam.ac.uk (Nick Maclaren) wrote: > In article ,s... at pobox.com writes:|> > |> What makes you think Paddy indicated he wouldn't try to solve the problem? > |> Here's what he wrote: > |> > |> What I'm proposing is that if, for example, a process stops running > |> three times in a year at roughly three to four months intervals , and it > |> should have stayed up; then restart the server sooner, at aa time of > |> your choosing, whilst taking other measures to investicate the error. > |> > |> I see nothing wrong with trying to minimize the chances of a problem rearing > |> its ugly head while at the same time trying to investigate its cause (and > |> presumably solve it). > > No, nor do I, but look more closely. His quote makes it quite clear that > he has got it firmly in his mind that this is a degradation problem, and > so regular restarting will improve the reliability. Well, it could also > be one where failure becomes LESS likely the longer the server stays up > (i.e. the "settling down" problem). If in the past year the settling down problem did not rear its head when the server crashed after three to four months and was restarted, then why not implement a regular , notified, downtime - whilst also looking into the problem in more depth? * You are already having to restart. * restarts last for 3-4 months. Why burden yourself with "Oh but it could fail once in three hours, you've not prooved that it can't, we'll have to stop everything whilst we do a thorough investigation. Is it Poisson? Is it 'settling down'? Just wait whilst I prepare my next doctoral thesis... " - Okay, the last was extreme. but cathartic :-) > > No problem is as hard to find as one where you are firmly convinced that > it is somewhere other than where it is. Amen! > > Regards, > Nick Maclaren. - Paddy. From horpner at yahoo.com Fri Jan 12 11:02:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 12 Jan 2007 17:02:28 +0100 Subject: Matching Directory Names and Grouping Them References: <1168554244.459131.190440@k58g2000hse.googlegroups.com> <1168558702.851290.230100@i56g2000hsf.googlegroups.com> Message-ID: On 2007-01-11, J wrote: > Steve- > > Thanks for the reply. I think what I'm trying to say by similar > is pattern matching. Essentially, walking through a directory > tree starting at a specified root folder, and returning a list > of all folders that matches a pattern, in this case, a folder > name containing a four digit number representing year and a > subdirectory name containing a two digit number representing a > month. The matches are grouped together and written into a text > file. I hope this helps. Here's a solution using itertools.groupby, just because this is the first programming problem I've seen that seemed to call for it. Hooray! from itertools import groupby def print_by_date(dirs): r""" Group a directory list according to date codes. >>> data = [ ... "/Input2/2002/03/", ... "/Input1/2001/01/", ... "/Input3/2005/05/", ... "/Input3/2001/01/", ... "/Input1/2002/03/", ... "/Input3/2005/12/", ... "/Input2/2001/01/", ... "/Input3/2002/03/", ... "/Input2/2005/05/", ... "/Input1/2005/12/"] >>> print_by_date(data) /Input1/2001/01/ /Input2/2001/01/ /Input3/2001/01/ /Input1/2002/03/ /Input2/2002/03/ /Input3/2002/03/ /Input2/2005/05/ /Input3/2005/05/ /Input1/2005/12/ /Input3/2005/12/ """ def date_key(path): return path[-7:] groups = [list(g) for _,g in groupby(sorted(dirs, key=date_key), date_key)] for g in groups: print '\n'.join(path for path in sorted(g)) print if __name__ == "__main__": import doctest doctest.testmod() I really wanted nested join calls for the output, to suppress that trailing blank line, but I kept getting confused and couldn't sort it out. It would better to use the os.path module, but I couldn't find the function in there lets me pull out path tails. I didn't filter out stuff that didn't match the date path convention you used. -- Neil Cerutti From parallelpython at gmail.com Wed Jan 10 03:17:45 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 10 Jan 2007 00:17:45 -0800 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: <1168417065.105920.319970@o58g2000hsb.googlegroups.com> > I always thought that if you use multiple processes (e.g. os.fork) then > Python can take advantage of multiple processors. I think the GIL locks > one processor only. The problem is that one interpreted can be run on > one processor only. Am I not right? Is your ppm module runs the same > interpreter on multiple processors? That would be very interesting, and > something new. > > > Or does it start multiple interpreters? Another way to do this is to > start multiple processes and let them communicate through IPC or a local > network. That's right. ppsmp starts multiple interpreters in separate processes and organize communication between them through IPC. Originally ppsmp was designed to speedup an existent application which is written in pure python but is quite computationally expensive (the other ways to optimize it were used too). It was also required that the application will run out of the box on the most standard Linux distributions (they all contain CPython). From robert.kern at gmail.com Tue Jan 9 14:38:51 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 13:38:51 -0600 Subject: distutils and ctypes In-Reply-To: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> Message-ID: jtravs at gmail.com wrote: > So finally, my question is, is there a way to get distutils to simply > build a shared library on windows so that I can use ctypes with them??? Not out-of-box, no. The OOF2 project has added a bdist_shlib command which should do most of what you want, though. It's somewhat UNIX-oriented, and I think it tries to install the shared library to a standard location (e.g. /usr/local/lib). You might want to modify it to install the shared library in the package so it is easy to locate at runtime. http://www.ctcms.nist.gov/oof/oof2/ http://www.ctcms.nist.gov/oof/oof2/source/oof2-2.0.1.tar.gz The code is in the shlib/ subdirectory. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From beej at beej.us Tue Jan 30 15:48:06 2007 From: beej at beej.us (Beej) Date: 30 Jan 2007 12:48:06 -0800 Subject: Help me understand this In-Reply-To: References: Message-ID: <1170190086.432548.205830@s48g2000cws.googlegroups.com> On Jan 30, 9:52 am, Jean-Paul Calderone wrote: > A float is, too. 2.__add is a float followed by an identifier. > Not legal. As pointed out elsewhere in the thread, (2). forces > it to be an integer followed by a ".". Which leads to these two beauties: >>> (2.).__add__(1) 3.0 >>> 2..__add__(1) 3.0 I like the second one more. :-) -Beej From PavPanchekha at gmail.com Fri Jan 19 17:18:19 2007 From: PavPanchekha at gmail.com (Pavel Panchekha) Date: 19 Jan 2007 14:18:19 -0800 Subject: How to comment code? In-Reply-To: References: <45b13876$0$323$e4fe514c@news.xs4all.nl> Message-ID: <1169245099.852799.142840@38g2000cwa.googlegroups.com> I think that doc strings are the most important way in which you should be commenting on your code. Once the code works, you can elimainate most inline comments, leaving only doc string for everything and a few comments on some particularly confusing parts. Other than that, comments usually only clutter Python code. But remember that you are the person who understands your code best, so don't be too fanatical about deleting inline comments. From __peter__ at web.de Thu Jan 25 05:40:40 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Jan 2007 11:40:40 +0100 Subject: str and __setitem__ References: Message-ID: Tor Erik Soenvisen wrote: > What do I need to do to make the code below work as expected: > > class str2(str): > > ????????def __setitem__(self, i, y): > ????????????????assert type(y) is str > ????????????????assert type(i) is int > ????????????????assert i < len(self) > > ????????????????self = self[:i] + y + self[1+i:] 'self' is a local variable; assigning to it rebinds it but has no effect outside of the __setitem__() method. > a = str2('123') > a[1] = '1' > print a > 123 > The print statement should return 113 You have to start from scratch as a strings are "immutable" (once created, their value cannot be changed). >>> class mutable_str(object): ... def __init__(self, value): ... self._value = value ... def __setitem__(self, index, value): ... self._value = self._value[:index] + value + self._value[index+1:] ... def __str__(self): ... return self._value ... >>> a = mutable_str("123") >>> a[1] = "x" >>> print a 1x3 Peter From fd.calabrese at gmail.com Tue Jan 9 04:18:29 2007 From: fd.calabrese at gmail.com (cesco) Date: 9 Jan 2007 01:18:29 -0800 Subject: recursive function In-Reply-To: References: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> <1168277289.970128.44880@38g2000cwa.googlegroups.com> Message-ID: <1168334309.507367.263290@v33g2000cwv.googlegroups.com> Hendrik van Rooyen wrote: > "cesco" wrote: > > > > > Neil Cerutti wrote: > > > On 2007-01-08, cesco wrote: > > > > Hi, > > > > > > > > I have a dictionary of lists of tuples like in the following example: > > > > dict = {1: [(3, 4), (5, 8)], > > > > 2: [(5, 4), (21, 3), (19, 2)], > > > > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]] > > > > > > > > In this case I have three lists inside the dict but this number > > > > is known only at runtime. I have to write a function that > > > > considers all the possible combinations of tuples belonging to > > > > the different lists and return a list of tuples of tuples for > > > > which the sum of the first element of the most inner tuple is > > > > equal to N. > > > > > > > > For example, assuming N = 24, in this case it should return: > > > > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19, > > > > 2), (0, 2))] > > > > > > What do you mean by "most inner tuple"? > > > > > > > A simple list comprehension would be enough if only I knew the > > > > number of keys/lists beforehand > > > > > > len(dict.keys()). > > > > What I mean is that the number of keys/lists is not known until runtime > > and it changes randomly from time to time which means I would have to > > write every time a different list comprehension (or a different number > > of nested loops) to accomplish the same thing. > > In the example the result of the search should be a list containing > > three tuples each of which contains again three tuple (the most inner > > tuples). If you consider the first element of each tuple the sum is 24 > > (like in 3+5+16, or 3+21+0 or 5+19+0). > > > > Any other help will be appreciated > > > Is there any reliable structure in the data? > - for instance in your example, the first list > has two tuples, the second one three, and the > third one four - Is this a pattern? Hi Hendrik, there is no such a pattern (I just happened to insert that ascending number of lists). Anyway the answer from bearophileH... at lycos.com was quite satisfactory:-) regards Cesco From krw at att.bizzzz Wed Jan 10 16:38:39 2007 From: krw at att.bizzzz (krw) Date: Wed, 10 Jan 2007 16:38:39 -0500 Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> <0001HW.C1CA63B1059BC980F0203648@news.verizon.net> Message-ID: In article , jmfbahciv at aol.com says... > In article <0001HW.C1CA63B1059BC980F0203648 at news.verizon.net>, > Lefty Bigfoot wrote: > >On Wed, 10 Jan 2007 08:28:33 -0600, jmfbahciv at aol.com wrote > >(in article ): > > > >> In article , > >> "Elan Magavi" wrote: > >>> Is that like.. OctaPussy? > >> > >> I didn't read their stuff. Are they really trying to put a > >> round peg in a square hole? > > > >Sounds more like an octagonal pole in a round hole. > > Nah, I figured they picked the word octal because it's never > been used before..... ...and "HexaPussy" just wouldn't be right. -- Keith From nmm1 at cus.cam.ac.uk Sun Jan 14 06:55:59 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jan 2007 11:55:59 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> In article , "Hendrik van Rooyen" writes: |> > |> I would suspect that this is one of those questions which are simple |> to ask, but horribly difficult to answer - I mean - if the hardware has |> thrown it away, how do you study it - you need somehow two |> different parallel engines doing the same stuff, and comparing the |> results, or you have to write a big simulation, and then you bring |> your simulation errors into the picture - There be Dragons... No. You just emulate floating-point in software and throw a switch selecting between the two rounding rules. Regards, Nick Maclaren. From bearophileHUGS at lycos.com Fri Jan 26 14:06:49 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Jan 2007 11:06:49 -0800 Subject: A note on heapq module In-Reply-To: <1169159235.864192.263210@v45g2000cwv.googlegroups.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> <1169117876.063858.56570@s34g2000cwa.googlegroups.com> <8NSdnf38_otYcjLYnZ2dnUVZ_tadnZ2d@comcast.com> <1169159235.864192.263210@v45g2000cwv.googlegroups.com> Message-ID: <1169838409.657590.275760@v45g2000cwv.googlegroups.com> bearophile: > I don't like your solution, this class was already slow enough. Don't > use unbound methods with this class :-) Sorry for raising this discussion after so much time. Another possibile solution is to use the normal methods for the normal case, and replace them only if key is present (this reduces problems with unbound methods but you may use the wrong method). Example: def __init__(self, sequence=None, key=None, inplace=False): ... if key is None: ... else: ... self.pop = self.__pop_key ... def pop(self): return heappop(self._heap) def __pop_key(self): return heappop(self._heap)[2] Someone else has done something similar: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e61ba58c9722bf51/ http://sourceforge.net/tracker/index.php?func=detail&aid=1162363&group_id=5470&atid=305470 Bye, bearophile From richfahey at gmail.com Thu Jan 11 14:27:13 2007 From: richfahey at gmail.com (Rich) Date: 11 Jan 2007 11:27:13 -0800 Subject: passing a variable to an external program In-Reply-To: References: <1168542633.290682.267570@77g2000hsv.googlegroups.com> Message-ID: <1168543633.441389.42200@i39g2000hsf.googlegroups.com> Thank you, that did it. I don't know why I didn't think to escape the \ with \\. On Jan 11, 2:18 pm, Neil Cerutti wrote: > On 2007-01-11, Rich wrote: > > > I want to run an external program using os.system() but I want to > > include a variable in the middle of the command line. > > > An example of the type of thing I want to be able to do: > > pathname = os.path.dirname(sys.argv[0]) > > os.system('cscript /nologo ' + pathname + '\test.vbs')Use / instead of \, or \\ instead of \. > > -- > Neil Cerutti > Ushers will eat latecomers. --Church Bulletin Blooper From ptmcg at austin.rr._bogus_.com Fri Jan 12 00:05:22 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 11 Jan 2007 23:05:22 -0600 Subject: Explanation about for loop References: <1168577299.485773.8160@q2g2000cwa.googlegroups.com> Message-ID: <45a71712$0$501$4c368faf@roadrunner.com> "raghu" wrote in message news:1168577299.485773.8160 at q2g2000cwa.googlegroups.com... > can any one help me explaining for loop and its execution and its > syntax with a simple example. > Bookmark this page: http://docs.python.org/ref/ref.html "for loop" reference page: http://docs.python.org/ref/for.html Bookmark this page: http://docs.python.org/tut/tut.html "for loop" explanation: http://docs.python.org/tut/node6.html#SECTION006200000000000000000 Please avail yourself of one of the many online or hardcopy Python tutorial and reference resources. If you are asking about for loops, you have a lot of basic ground to cover, more than is really suitable for newsgroup traffic. Google for "python tutorial" should give you a good start. -- Paul From bjourne at gmail.com Thu Jan 25 04:18:11 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 25 Jan 2007 10:18:11 +0100 Subject: Getting to an SSH account over a HTTP proxy In-Reply-To: References: <51jt71F1k884hU1@mid.uni-berlin.de> Message-ID: <740c3aec0701250118x3160d8efm243769394f1ab1ef@mail.gmail.com> On 1/22/07, Yu-Xi Lim wrote: > He's referring to the HTTP CONNECT method, which can tunnel arbitrary > TCP connections, not just HTTP. The IETF draft for this is titled > "Tunneling TCP based protocols through Web proxy servers". > > AFAIK, there are no Python modules which support that. The protocol > itself is fairly simply though, so it shouldn't be too hard to write > your own wrapper or proxy for the client side. Things get a little more > complicated if you have to authenticate with the proxy first. The proxy in question requires authentication. Do you mean that I should be able to write something that handles the communication to the proxy and then run a library like paramiko "over that"? I have no idea how to do that. -- mvh Bj?rn From steve at REMOVEME.cybersource.com.au Sun Jan 28 22:05:24 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 29 Jan 2007 14:05:24 +1100 Subject: Convert from unicode chars to HTML entities Message-ID: I have a string containing Latin-1 characters: s = u"? and many more..." I want to convert it to HTML entities: result => "© and many more..." Decimal/hex escapes would be acceptable: "© and many more..." "© and many more..." I can look up tables of HTML entities on the web (they're a dime a dozen), turn them into a dict mapping character to entity, then convert the string by hand. Is there a "batteries included" solution that doesn't involve reinventing the wheel? -- Steven D'Aprano From petri.savolainen at iki.fi Tue Jan 9 18:13:23 2007 From: petri.savolainen at iki.fi (Petri Savolainen) Date: Wed, 10 Jan 2007 01:13:23 +0200 Subject: [ANN] win32 binaries for zope.interface 3.3.0 Message-ID: Both eggs and installers (exe) are available for Python 2.4 & 2.5 from: http://www.zope.org/Members/saffe/zope_interface/folder_contents Compiled on winxp pro using mingw32 "current". Cheers, Petri From mhellwig at xs4all.nl Fri Jan 5 12:50:15 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Fri, 05 Jan 2007 18:50:15 +0100 Subject: Adding a directory to the Python System Path - Edit the registry? In-Reply-To: <1168017552.010631.276080@s34g2000cwa.googlegroups.com> References: <1168017552.010631.276080@s34g2000cwa.googlegroups.com> Message-ID: <459e8fa5$0$335$e4fe514c@news.xs4all.nl> redefined.horizons at gmail.com wrote: > I have been trying to find a way to add a directory to Python's sytem > path on my MS Windows XP computer. I did some searching online, but the > only solution I found involved editing the MS Windows Registry. That > seemed a little to hard core. Is there another easier way to do this? > > Thanks, > > Scott Huey > Take a look at: http://docs.python.org/tut/node8.html Specifically 6.1.1 and 6.2, perhaps that might answer your question. Cheers -- mph From george.sakkis at gmail.com Wed Jan 3 15:24:18 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 3 Jan 2007 12:24:18 -0800 Subject: Sorting on multiple values, some ascending, some descending References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> Message-ID: <1167855858.102690.265680@q40g2000cwq.googlegroups.com> dwelden wrote: > I have successfully used the sort lambda construct described in > http://mail.python.org/pipermail/python-list/2006-April/377443.html. > However, how do I take it one step further such that some values can be > sorted ascending and others descending? Easy enough if the sort values > are numeric (just negate the value), but what about text? You got already some good replies; here's yet another less-than-optimal way: class revstr(str): def __lt__(self, other): return str.__gt__(self,other) def __gt__(self, other): return str.__lt__(self,other) L.sort(key=lambda i: (i.somestring, revstr(i.someotherstring), i.anotherkey)) George From nmm1 at cus.cam.ac.uk Mon Jan 8 13:03:01 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 8 Jan 2007 18:03:01 GMT Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> <50fdf9F1fki7dU3@mid.individual.net> Message-ID: In article <50fdf9F1fki7dU3 at mid.individual.net>, Bjoern Schliessmann writes: |> |> > The use of different precisions for the two cases is not, however, |> > and it is that I was and am referring to. |> |> You mistake "precision" with "display". Not at all. "Precision" has been used to indicate the number of digits after the decimal point for at least 60 years, probably 100; in 40 years of IT and using dozens of programming languages, I have never seen "display" used for that purpose. Regards, Nick Maclaren. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 11 12:20:42 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 11 Jan 2007 18:20:42 +0100 Subject: what is the idiom for copy lots of params into self? References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> <1168481112.291651.89300@i39g2000hsf.googlegroups.com> <1168520386.457345.23680@i39g2000hsf.googlegroups.com> Message-ID: <50n9vaF1g30l4U3@mid.individual.net> Emin wrote: > Thanks for your suggestions. One issue with using *args or **kw is > that I might no want to copy all the arguments to __init__ into > self. Try prepending something like allowedParms = ("spam", "eggs", "yum") args = dict([key,val for key,val in args.elements() if key in allowedParms]) Regards, Bj?rn -- BOFH excuse #64: CPU needs recalibration From stefan.behnel-n05pAM at web.de Mon Jan 8 10:10:09 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 08 Jan 2007 16:10:09 +0100 Subject: Module to read svg In-Reply-To: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> References: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> Message-ID: <45a25ed2$0$18840$9b4e6d93@newsspool4.arcor-online.net> schpok at gmail.com wrote: > I'm looking for a module to load an SVG document so that I can read out > its contents in some graphics-centric way. For example, path elements > store their vertices in a long attribute string you need to parse. An > ideal module would get me these vertices in a list. > > SVGdraw seems to only write, but not read. > > I'm interested in a pretty simple subset of the actual spec, where SVG > Tiny is sufficient. W3C's python spec seems just what I want: > http://www.w3.org/TR/SVGMobile12/python-binding.html > > Does anyone know if there's an actual free implementation of this? > Before I start salvaging out code from Skencil, is there anything else > I might look at? Check out XIST, it seems to have some kind of SVG support. http://www.livinglogic.de/Python/xist/ http://mail.python.org/pipermail/xml-sig/2004-June/010325.html In case you still end up wanting to write something yourself, you might consider lxml's namespace implementation feature a good starting point. http://codespeak.net/lxml/element_classes.html Stefan From steve at REMOVEME.cybersource.com.au Wed Jan 31 21:35:09 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Thu, 01 Feb 2007 13:35:09 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> <1170220553.843010.258260@a34g2000cwb.googlegroups.com> <1170284969.902118.155570@l53g2000cwa.googlegroups.com> Message-ID: On Wed, 31 Jan 2007 15:09:29 -0800, manstey wrote: > Thanks for your input. Here is my next version, which works very well, > but for one problem I explain below: > > class CacheProperty(object): > def __init__(self, insCacheClass, name): > self.Name = name > self._bind_to_parent(insCacheClass) > self.__parent = insCacheClass > self.__pyValue = self.__parent.get(name) > > def _bind_to_parent(self, parent): > setattr(parent, self.Name, self) > > def get(self): > return self.__pyValue > > def set(self, val): > self.__parent.set(self.Name, val) > self.__pyValue = val # Set in wrapper's copy > > Value = property(get, set) > > def __repr__(self): > return str(self.Value) > def __str__(self): > return str(self.Value) > > > class CacheClass(object): > def __init__(self, obj): > self.__data = obj > > def getOref(self): > return self.__data That's pointless. Just get rid of the double-underscores and let the caller refer to self.data directly. > def __repr__(self): > return 'self.__data' What's the purpose of this? Why do completely different instances of CacheClass have exactly the same repr? > def __str__(self): > return str(self.__data) Pointless, because __getattr__ will have the same effect: if __str__ doesn't exist, __getattr__ will call getattr(self.__data, "__str__") which is equivalent to str(self.__data). > def __getattr__(self, attr): > return getattr(self.__data, attr) Straight-forward delegation to self.__data. As near as I can see, CacheClass(oref) essentially does nothing different to just oref. So why wrap oref in another class? What's the purpose of this? Why not just refer to oref in the first place? What makes this a "cache" class? It doesn't seem to act anything like a cache to me. It seems to be just a wrapper around oref that doesn't really do anything. > Our code works fine as follows (oref is in-memory version of Cache oo- > dbase class, and is an old-style class that comes with set and get and > run_obj_method methods): >>>> insCacheClass = CacheClass(oref) >>>> insCacheProperty = CacheProperty(insOref,'Chapter') What is insOref and where does it come from? Is it different from oref? Your classes are confusing, but I feel that all of the above is just a big, complicated way of saying something like this: insOref = something_or_other insOref.some_name = insOref and then jumping through all sorts of hoops writing this: insOref.some_name.attribute instead of just insOref.attribute That's what it seems like to me. Have I missed something? >>>> print insOref.Chapter.Value > 5 >>>> print insOref.Chapter.Name > 'Chapter' >>>> insOref.Chapter.Value=67 >>>> print insOref.Chapter > 67 > > However, the problem is now that I can also write: >>>> insOref.Chapter=67 > but we want to disallow this, as insOref.Chapter must remain = > insProperty Why? > We add various other instances of CacheProperty to the insOref as > well, btw. This whole design seems incredibly byzantine to me. It would help if you take a step back from asking technical questions "how do I do this?" and instead tell us what you're trying to accomplish. Why do you wrap the instances in the first place? What benefit do you get? Here is something that you should do. Write your documentation for the classes CacheProperty and CacheClass. The documentation should explain what they are for, why you would use them, and how you use them. If you can't explain what they are for and why you would use them, chances are very very good that they don't do anything useful and you shouldn't use them at all. -- Steven D'Aprano From nmm1 at cus.cam.ac.uk Fri Jan 12 06:33:18 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 12 Jan 2007 11:33:18 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: In article <1168597288.571937.176430 at s34g2000cwa.googlegroups.com>, "Paul Boddie" writes: |> parallelpyt... at gmail.com wrote: |> > |> > The main difference between MPI python solutions and ppsmp is that with |> > MPI you have to organize both computations |> > {MPI_Comm_rank(MPI_COMM_WORLD, &id); if id==1 then ... else ....} and |> > data distribution (MPI_Send / MPI_Recv) by yourself. While with ppsmp |> > you just submit a function with arguments to the execution server and |> > retrieve the results later. |> |> Couldn't you just provide similar conveniences on top of MPI? Searching |> for "Python MPI" yields a lot of existing work (as does "Python PVM"), |> so perhaps someone has already done so. Yes. No problem. |> Also, what about various grid toolkits? If you can find one that is robust enough for real work by someone who is not deeply into developing Grid software, I will be amazed. Regards, Nick Maclaren. From qertoip at gmail.com Fri Jan 26 04:41:54 2007 From: qertoip at gmail.com (qertoip at gmail.com) Date: 26 Jan 2007 01:41:54 -0800 Subject: xml.dom.minidom.parseString segmentation fault on mod_python Message-ID: <1169804514.862290.274940@q2g2000cwa.googlegroups.com> Python 2.4.4 mod_python 3.2.10 + Apache 2.0 def index( req, **params ): from xml.dom.minidom import parseString doc = parseString( "whatever" ) => blank screen, _no_any_exception_; Apache error_log: [Fri Jan 26 10:18:48 2007] [notice] child pid 17596 exit signal Segmentation fault (11) Outside mod_python code works well. Any ideas? I would be grateful. From stuart at bmsi.com Mon Jan 22 17:35:18 2007 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 22 Jan 2007 17:35:18 -0500 Subject: Best way to document Python code... References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: On Mon, 22 Jan 2007 20:40:57 +0000, Adonis Vargas wrote: > But a quick look at pydoc (not to be confused with epydoc) > which is part of the standard library allows you to generate > documentation in HTML format, and/or serve it over web with its built-in > HTTP server. > > pydoc: http://docs.python.org/lib/module-pydoc.html > > Hope this helps. > > Adonis The HTML generated by pydoc doesn't link to standard modules properly. They are generated as relative links. So it can't be used without modification for generating docs for a web page about a python package. I'm struggling with the same issue. Coding Python is so much easier than Java. However documenting Java is so much easier than Python. Just include doc comments, run javadoc, and voila! -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From Thomas.Ploch at gmx.net Sun Jan 7 13:30:17 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 19:30:17 +0100 Subject: Why less emphasis on private data? In-Reply-To: References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> Message-ID: <45A13C39.4070707@gmx.net> Sebastian 'lunar' Wiesner schrieb: > > Those people deserve to fail for being just extraordinary stupid... > Yes, but there are a lot of them around... Thomas P.S.: I don't mean they are around here. :-) From fejkadress at hushmail.com Mon Jan 1 20:09:19 2007 From: fejkadress at hushmail.com (fejkadress at hushmail.com) Date: 1 Jan 2007 17:09:19 -0800 Subject: OO question In-Reply-To: <1167639280.181587.242490@s34g2000cwa.googlegroups.com> References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> <1167639280.181587.242490@s34g2000cwa.googlegroups.com> Message-ID: <1167700159.792649.61210@a3g2000cwd.googlegroups.com> First I want to say thanks everyone for helping me! John Machin wrote: > fejkadress at hushmail.com wrote: > > I want to make an addressbook and I'm new to OO programming, so I > > wonder if this sounds reasonable. > > > > I think of making a class Address which contains all data about one > > person, that class can have UserDict as baseclass so I can access data > > like object['name'], etc.. > > Stop right there. Class Address contains all data about one *person*? > Please consider renaming that class Person, and having a separate class > Address. > > Interruption for a reality check: A person may be related to zero, one > or many addresses. An address may be related to zero, one or many > persons. The relationship may take many forms e.g. "lives at", "once > lived at", "has been noticed loitering outside", ... Lets say I have those two classes, Person and Address. How would one implement the relationship between them? First, a Person can have one or more addresses (or none), that could be represented as a list of Addresses, right? But then, if I have an Address I want to see which persons who live there, then I would have a list of Persons in each Address. Is this doubly-linked way of doing it a good way of doing it, or is there a better "OO way" I haven't learned yet? From nagle at animats.com Mon Jan 29 12:42:44 2007 From: nagle at animats.com (John Nagle) Date: Mon, 29 Jan 2007 09:42:44 -0800 Subject: Possible security hole in SSL - was Random Passwords Generation In-Reply-To: <7x64apzx8f.fsf@ruckus.brouhaha.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <7x3b5uwfa2.fsf@ruckus.brouhaha.com> <1170082883.393745.244840@a34g2000cwb.googlegroups.com> <7x64apzx8f.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Szabolcs Nagy" writes: > >>file('/dev/urandom').read(6).encode('base64') >>(oneliner and without import sa op requested) > > > Nice, though Un*x dependent (os.urandom is supposed to be portable). Uh oh. I was looking at the Python "SSL" code recently, and noted that OpenSSL initializes the keys with '/dev/urandom' if available, and otherwise relies on the caller to seed it with random data and to check that enough randomness has been input. But the Python glue code for SSL doesn't seem to have the machinery to seed SSL with randomness. I suspect that on platforms without '/dev/urandom', Python's SSL package may be using the same keys every time. This needs to be looked at by a crypto expert. John Nagle From pavlovevidence at gmail.com Thu Jan 4 16:31:27 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 4 Jan 2007 13:31:27 -0800 Subject: subclassing a module: misleading(?) error message References: <459d687a$1@nntp.zianet.com> Message-ID: <1167946286.988570.216110@i15g2000cwa.googlegroups.com> Erik Johnson wrote: > My questions are: > > Why does python complain about a function here? (it's a class definition > statement, right?) Because you're calling the function with the wrong number of arguments. > Is there really a function being called here? Yes. (Well, it's not exactly a function, but you are calling something.) > If so: > What function was called? types.ModuleType > What two arguments is it expecting? The name of the module and a docstring. > What three were given? 1. The name of the class 2. The tuple of bases 3. A dict containing the symbols defined inside the class statement. You are aware, I presume, that types (be it classes or built-in types) are callable. For example, to create an instance of class of class X, you would call X(). And to create a list, you can call list(). Well, in the same way, you can call type(), with the three arguments above, to create classes. And that's just what the class statement does under the covers (usually). The following class definition: class A(object): b = 1 is exactly equivalent to this explicit call to type: A = type("A",(object,),{"b":1}) However, there are some cases where, instead of creating the class object itself, type will instead call some other function to create it. One way is if you define __metaclass__ in the class namespace: then type will call the object spec. Another way is if there are any bases which have a type other than type. (Remember, bases are supposed to be type objects.) That's what happened to you. type saw that type(Super) was types.ModuleType, not type, so it called that instead of creating the class itself. However, types.ModuleType doesn't accept that same arguments that a normal type constructor does, so you get the error. Does that clear things up? Probably not. For a detailed explanation of how this all works, look for some resources on learning "metaclasses" or "metatypes" in Python. Carl Banks From nmm1 at cus.cam.ac.uk Fri Jan 19 17:09:10 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 19 Jan 2007 22:09:10 GMT Subject: OT Annoying Habits (Was: when format strings attack) References: Message-ID: In article , "Carroll, Barry" writes: |> |> Secondly, can someone point me to the Standard Usenet Convention that |> mandates against top-posting. This is not sarcasm; I would really like |> to see it. You see, I recently returned to Usenet after a LONG absence. |> When I was last a regular Usenet citizen the Internet was new, GUI |> interfaces were experimental and the World Wide Web didn't exist yet. |> Newsreader software was text-based. Top-posting was the common |> practice, because it was the most convenient: you didn't have to page |> through an arbitrarily large number of messages, most of which you'd |> already read umpteen times, to get to the new stuff you were interested |> in. =20 When I started to use this sort of thing, in the early 1970s, top posting was already deprecated. And top posting is only more convenient if you are merely adding a "me, too" or equivalent, and not responding in detail. But you have been told both of those before. Regards, Nick Maclaren. From vpolukcht at gmail.com Tue Jan 16 12:59:28 2007 From: vpolukcht at gmail.com (Victor Polukcht) Date: 16 Jan 2007 09:59:28 -0800 Subject: Regular expressions question In-Reply-To: References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> Message-ID: <1168970367.938185.294140@q2g2000cwa.googlegroups.com> Great thnx. It works. On Jan 16, 6:02 pm, Wolfgang Grafen wrote: > Victor Polukcht wrote: > > I have 2 strings: > > > "Global etsi3 *200 ok 30 100% 100% > > Outgoing" > > and > > "Global etsi3 * 4 ok 30 100% 100% > > Outgoing" > > > The difference is "*200" instead of "* 4". Is there ability to write a > > regular expression that will match both of that strings?---------------------------- x.py begin -------- > import re > > s1 = "Global etsi3 *200 ok 30 100% 100% Outgoing" > s2 = "Global etsi3 * 4 ok 30 100% 100% Outgoing" > > re_m = re.compile( "^" > "(\S+)" # Global > "\s+" > "(\S+)" # etsi3 > "\s+" > "((\*)\s*(\d+))" # *200 * 4 > "\s+" > "(\S+)" # ok > "\s+" > "(\S+)" # 30 > "\s+" > "(\S+)" # 100% > "\s+" > "(\S+)" # 100% > "\s+" > "(\S+)" # Outgoing > "$" > ).match > > print "match s1:", re_m(s1).groups() > print "match s2:", re_m(s2).groups() > ----------------------------- x.py file end --------- > > % python x.py > match s1: ('Global', 'etsi3', '*200', '*', '200', 'ok', '30', '100%', '100%', 'Outgoing') > match s2: ('Global', 'etsi3', '* 4', '*', '4', 'ok', '30', '100%', '100%', 'Outgoing') From martin at v.loewis.de Sun Jan 21 02:21:33 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Jan 2007 08:21:33 +0100 Subject: A solution to the MSVCRT vs MSVCR71 problem? In-Reply-To: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> References: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> Message-ID: <45B3147D.9010407@v.loewis.de> sturlamolden schrieb: > Problem 2: You want to distribute a program created Py2Exe, but has no > license for Visual Studio 2003. You are therefore not allowed to > redistribute msvcrt71.dll. But without this DLL your program will not > work. As a side note: Visual Studio 2003 is out of sale, so if you > don't have it already you may be out of luck. I believe this problem doesn't exist. Licensees of Python are permitted to redistribute mscvr71.dll, as long as they redistribute it in order to support pythonxy.dll. The EULA says # You also agree not to permit further distribution of the # Redistributables by your end users except you may permit further # redistribution of the Redistributables by your distributors to your # end-user customers if your distributors only distribute the # Redistributables in conjunction with, and as part of, the Licensee # Software, you comply with all other terms of this EULA, and your # distributors comply with all restrictions of this EULA that are # applicable to you. In this text, "you" is the licensee of VS 2003 (i.e. me, redistributing msvcr71.dll as part of Python 2.5), and the "Redistributable" is msvcr71.dll. The "Licensee Software" is "a software application product developed by you that adds significant and primary functionality to the Redistributables", i.e. python25.dll. IANAL; this is not legal advise. Regards, Martin From tew24 at spam.ac.uk Thu Jan 18 11:24:13 2007 From: tew24 at spam.ac.uk (Tom Wright) Date: Thu, 18 Jan 2007 16:24:13 +0000 Subject: How to find out if another process is using a file Message-ID: I'm writing a program which reads a series of data files as they are dumped into a directory by another process. At the moment, it gets sporadic bugs when it tries to read files which are only partially written. I'm looking for a function which will tell me if a file is opened in write-mode by another process - if it is, my program will ignore it for now and come back to it later. This needs to work on linux and windows. Mac OS would be a bonus too. An os-independent solution would be good, but I could write os-specific options and have it pick the appropriate one. Is there any way of doing this? I've drawn a blank with google so far. A nasty hack would be to use the file modification time, and wait until that's a few seconds in the past, but is there a nice solution? -- I'm at CAMbridge, not SPAMbridge From jon at ffconsultancy.com Tue Jan 2 20:12:38 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Wed, 03 Jan 2007 01:12:38 +0000 Subject: Writing more efficient code References: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> <1167715231.450710.325860@42g2000cwt.googlegroups.com> Message-ID: <459b0380$0$8731$ed2619ec@ptn-nntp-reader02.plus.net> Beliavsky wrote: > If in the newsgroup comp.lang.x somone asks how to do y, and you > suggest using language z, without answering their question, which was > how to do it in x, you will likely just annoy people and perhaps make > it even less likely that they will try z. Pattern matching isn't a language. -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet From wd.jonsson at gmail.com Thu Jan 25 05:26:09 2007 From: wd.jonsson at gmail.com (wd.jonsson at gmail.com) Date: 25 Jan 2007 02:26:09 -0800 Subject: While loop with "or"? Please help! Message-ID: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> Hmm, my while loop with "or" doesn't seem to work as I want it to... How do I tell the while loop to only accept "Y" or "y" or "N" or "n" input from the str(raw_input)? Thank's in advance! Snippet of code: import os def buildfinder(): os.system("CLS") GameRoot = os.getenv("GAME_ROOT") + "\\" print "Do you want to use " + GameRoot + " as your source directory?" usr = str(raw_input('Y/N: ')) return usr #Runs the buildfinder function usrinp = buildfinder() def buildwhiler(): while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM print "Enter Y or N!" usr = str(raw_input('Y/N: ')) else: code continues From wilder.usenet at gmail.com Thu Jan 11 18:38:22 2007 From: wilder.usenet at gmail.com (J) Date: 11 Jan 2007 15:38:22 -0800 Subject: Matching Directory Names and Grouping Them In-Reply-To: References: <1168554244.459131.190440@k58g2000hse.googlegroups.com> Message-ID: <1168558702.851290.230100@i56g2000hsf.googlegroups.com> Steve- Thanks for the reply. I think what I'm trying to say by similar is pattern matching. Essentially, walking through a directory tree starting at a specified root folder, and returning a list of all folders that matches a pattern, in this case, a folder name containing a four digit number representing year and a subdirectory name containing a two digit number representing a month. The matches are grouped together and written into a text file. I hope this helps. Kind Regards, J Steve Holden wrote: > J wrote: > > Hello Group- > > > > I have limited programming experience, but I'm looking for a generic > > way to search through a root directory for subdirectories with similar > > names, organize and group them by matching their subdirectory path, and > > then output their full paths into a text file. For example, the > > contents of the output text file may look like this: > > > > \Input1\2001\01\ > > \Input2\2001\01\ > > \Input3\2001\01\ > > > > \Input1\2002\03\ > > \Input2\2002\03\ > > \Input3\2002\03\ > > > > \Input2\2005\05\ > > \Input3\2005\05\ > > > > \Input1\2005\12\ > > \Input3\2005\12\ > > > > I tried working with python regular expressions, but so far haven't > > found code that can do the trick. Any help would be greatly > > appreciated. Thanks! > > > Define "similar". > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > Blog of Note: http://holdenweb.blogspot.com From gert.cuykens at gmail.com Sun Jan 21 21:25:06 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Mon, 22 Jan 2007 03:25:06 +0100 Subject: instancemethod In-Reply-To: References: Message-ID: import MySQLdb class Db: _db=-1 _cursor=-1 rowcount=-1 def __init__(self,server,user,password,database): self._db=MySQLdb.connect(server , user , password , database) self._cursor=self._db.cursor() def excecute(self,cmd): self._cursor.execute(cmd) self._db.commit() self.rowcount=int(self._cursor.rowcount()) def fetchone(self): return self._cursor.fetchone() def close(self): self._cursor.close() self._db.close() if __name__ == '__main__': gert=Db('localhost','root','*******','gert') gert.excecute('select * from person') for x in range(0,gert.rowcount): print gert.fetchone() gert.close() Traceback (most recent call last): File "Desktop/svn/db/Py/db.py", line 28, in gert.excecute('select * from person') File "Desktop/svn/db/Py/db.py", line 17, in excecute self.rowcount=int(self._cursor.rowcount()) TypeError: 'long' object is not callable I guess i did something wrong again ? :) From jgodoy at gmail.com Sat Jan 13 15:22:55 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 13 Jan 2007 18:22:55 -0200 Subject: sqlobject 0.8.0b1 and python 2.5 References: <50st46F1hiu23U1@mid.uni-berlin.de> Message-ID: <871wly7k2o.fsf@gmail.com> "Diez B. Roggisch" writes: > To my knowledge, the 0.8.x series is the current line of development, and has > made major progress over the previous versions. What makes you think it will > be stopped developing? And where does a sqlobject2 come from? http://www.sqlobject.org/2/ Be seeing you, -- Jorge Godoy From danb_83 at yahoo.com Fri Jan 5 21:38:38 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Jan 2007 18:38:38 -0800 Subject: Dividing integers...Convert to float first? In-Reply-To: References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> <459E8C77.3020603@rpath.com> Message-ID: <1168051118.835190.118540@q40g2000cwq.googlegroups.com> On Jan 5, 11:47 am, Thomas Ploch wrote: > Jonathan Smith schrieb: > > > Thomas Ploch wrote: > >> redefined.horiz... at gmail.com schrieb: > >>> I'm still pretty new to Python. I'm writing a function that accepts > >>> thre integers as arguments. I need to divide the first integer by te > >>> second integer, and get a float as a result. I don't want the caller of > >>> the function to have to pass floats instead of integers. How do I > >>> convert the arguments passed to the function into floats before I do > >>> the division? Is this necessary, or is their a better way? ... > >>>> from __future__ import division > >>>> 1/2 > > 0.5 > > > -smithjaahh, I have been tought so many things about python that are actually > so old, that I am starting to feel embarrassed. Don't feel embarrassed. "from __future__ import division" was added to Python only five years ago, so the tutorial writers haven't had enough time to mention it yet. Just remember that it's a good idea to use "from __future__ import division" (or better, "from __future__ import division as _division") in every module, and if you really want integer division, use the // operator instead of /. This will ensure that your code will continue to work correctly in Python 3.0, and that you won't be bitten by subtle bugs like def mean(num_list): return sum(num_list) / len(num_list) From elrondrules at gmail.com Thu Jan 25 21:32:26 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 25 Jan 2007 18:32:26 -0800 Subject: Http listener Message-ID: <1169778746.893177.20730@v33g2000cwv.googlegroups.com> Hi Am new to python and I am trying to do the following: 1. Write a Http Listener (listening on a particular port) that subscribes to a process. 2. This process posts events as xml docs. 3. Parse the xml docs as and when they are posted. Am trying to find any resources that helps me to do write the Http Listener.. any starting pointers would be helpful thx From arkanes at gmail.com Mon Jan 8 11:49:26 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 8 Jan 2007 10:49:26 -0600 Subject: Suitability for long-running text processing? In-Reply-To: References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> Message-ID: <4866bea60701080849h16d1dacew7a0abe950726c006@mail.gmail.com> On 1/8/07, Felipe Almeida Lessa wrote: > On 1/8/07, tsuraan wrote: > > > > > > > I just tried on my system > > > > > > (Python is using 2.9 MiB) > > > >>> a = ['a' * (1 << 20) for i in xrange(300)] > > > (Python is using 304.1 MiB) > > > >>> del a > > > (Python is using 2.9 MiB -- as before) > > > > > > And I didn't even need to tell the garbage collector to do its job. Some > > info: > > > > It looks like the big difference between our two programs is that you have > > one huge string repeated 300 times, whereas I have thousands of > > four-character strings. Are small strings ever collected by python? > > In my test there are 300 strings of 1 MiB, not a huge string repeated. However: > > $ python > Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> # Python is using 2.7 MiB > ... a = ['1234' for i in xrange(10 << 20)] > >>> # Python is using 42.9 MiB > ... del a > >>> # Python is using 2.9 MiB > > With 10,485,760 strings of 4 chars, it still works as expected. > > -- > Felipe. > -- Have you actually ran the OPs code? It has clearly different behavior than what you are posting, and the OPs code, to me at least, seems much more representative of real-world code. In your second case, you have the *same* string 10,485,760 times, in the OPs case each string is different. My first thought was that interned strings were causing the growth, but that doesn't seem to be the case. Regardless, what he's posting is clearly different, and has different behavior, than what he is posting. If you don't see the memory leak when you run the code he posted (the *same* code) that'd be important information. From sjmachin at lexicon.net Mon Jan 8 18:01:35 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 09 Jan 2007 10:01:35 +1100 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A68@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A68@eugsrv400.psc.pscnet.com> Message-ID: <45A2CD4F.9060004@lexicon.net> On 9/01/2007 8:25 AM, Carroll, Barry wrote: >> -----Original Message----- >> From: python-list-bounces+barry.carroll=psc.com at python.org [mailto:python- >> list-bounces+barry.carroll=psc.com at python.org] On Behalf Of John Machin >> Sent: Saturday, January 06, 2007 11:09 PM >> To: python-list at python.org >> Subject: Re: File Closing Problem in 2.3 and 2.4, Not in 2.5 >> >> Martin v. L?wis wrote: >>> Carroll, Barry schrieb: >>>> What I want to know is: >>>> >>>> * has anyone else encountered a problem like this, * how was the >>>> problem corrected, * can the fix be retro-fitted to 2.5 and 2.4? >>> From your description, I suspect an error in your code. Your description >>> indicates that you don't expect to have more than five files open >>> simultaneously. Yet, the error message "Too many open files" occurs when >>> you open many more files (in the order of hundreds of files). >>> >>> It is very unlikely that there is a bug in Python where it would fail to >>> close a file when .close() is explicitly invoked on it (as your >>> description suggests that you do), so if you get that error message, it >>> can only mean that you fail to close some files. >> I don't understand: the OP's description suggests nothing of the sort >> to me. What he said was: >> """ >> In this way, a tree of Parser instances is created, each with a single >> open file object. (BTW, recursive and circular references are not >> allowed.) When each Parser instance comes to the end of its table, the >> instance is explicitly destroyed, presumably destroying any objects it >> holds, AND closing its open file. >> """ >> which I interpret as: he is doing del parser_instance, and *presuming* >> (incorrectly) that attributes of parser_instance (including an open >> file object) are magically whisked away instantly, instead of >> later/maybe. He later says he explicitly closed the files, which fixed >> what he alleges (incorrectly) to be a bug. >> >> To the OP: >> (1) The del statement doesn't "destroy" anything. It unbinds the name >> from the object in the current namespace, and decrements the object's >> reference count. Only if the reference count is then zero will the >> janitor be called in. >> (2) Check the reference count on the parser_instance just before you >> del it. You could be retaining a reference somewhere. >> (3) Explicitly close all non-lightweight objects like files (even >> read-only ones) and sockets rather than hoping they will go away. >> >> HTH, >> John > > John: > > Thank you. I was afraid I had been totally misunderstood. We have retained the explicit file close in the current version of the Parser code. > > I still have a question, however. Python 2.3 and 2.4 both produce the "Too many open files" error on Windows XP Pro, but Python 2.5 does not. Running on the 2.5 interpreter, our program process all the table invocations with no errors, a total of over 650 file opens. Also, Python 2.3 on RedHat Fedora core 1 runs our program to completion with no errors. (I know, we are running pretty ancient SW here. Constraints unrelated to this question make that necessary.) Do you know why the error would appear on some combinations of OS and interpreter and not on others? > > Thanks again for your help. > > Regards, > > Barry Hi Barry, Please always reply on-list if the communication is non-private -- and meaningful :-) I don't know; here are some things you could check out: (1) Windows XP versus *x: The limit on open file handles is 512 in Windows XP; write yourself a reference-preserving [hint: append to a list] multiple file opener on *x and see how many you get open. I have vague recollections of the number 1024 being mentioned. (2) Python 2.4 versus 2.5: Read the "what's new" doc, fire up your googler, ... IMHO, the attitude should be to program defensively so that you need neither to know nor care about such implementation-specific concerns. Operating systems these days give you enough file handles to do any reasonable job. It's many moons since MS-DOS 2.n with its max 20 open file handles made folks implement LRU caches for file handles. Simple rules about unwanted objects include: (1) If an object has a free() or close() method, then call it! (2) Unbind *all* references to the object. Have you checked out my point 2 (holding multiple references to your Parser objects)? Cheers, John From wilson at afn.org Mon Jan 15 17:28:41 2007 From: wilson at afn.org (Jim B. Wilson) Date: Mon, 15 Jan 2007 22:28:41 GMT Subject: The curious behavior of integer objects Message-ID: Am I nuts? Or only profoundly confused? I expected the this little script to print "0": class foo(int): def __init__(self, value): self = value & 0xF print foo(0x10) Instead, it prints "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine). Jim Wilson GNV, FL From mcfletch at vrplumber.com Mon Jan 8 15:39:23 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Mon, 08 Jan 2007 15:39:23 -0500 Subject: Traceback of hanged process In-Reply-To: <1168286710.482272.33770@11g2000cwr.googlegroups.com> References: <1168286710.482272.33770@11g2000cwr.googlegroups.com> Message-ID: <45A2ABFB.7050208@vrplumber.com> Klaas wrote: > Hynek Hanke wrote: > >> Hello, >> >> please, how do I create a pythonic traceback from a python process that >> hangs and is not running in an interpreter that I executed manually >> or it is but doesn't react on CTRL-C etc? I'm trying to debug a server >> implemented in Python, so I need some analog of 'gdb attach' for C. >> ... > In python2.5, you can run a background thread that listens on a port or > unix socket, and prints a formatted version of sys._current_frames() to > stderr. > You can also use the signal module to similar effect. Works well in Twisted, at least: http://blog.vrplumber.com/835 HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From half.italian at gmail.com Wed Jan 24 21:47:46 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 24 Jan 2007 18:47:46 -0800 Subject: My Tkinter Threading nightmare Message-ID: <1169693266.209082.323310@a75g2000cwd.googlegroups.com> Hi all, I don't really understand how to properly use threading in my programs, however I have managed to get by so far using them improperly. Once again I have come up to what I think is something that won't work because of the way the program is set up. I have a long running process running underneath a gui in a different thread, and a progress bar that updates the status of the operation. What I would like to do is use something like : self.progressWindow.protocol('WM_DELETE_WINDOW', self.callback) and setup the callback to kill the operation and then the window when the user clicks on the X of the progress window. I've implemented this in my code, but clicking on the X does nothing until I kill the main thread (i think), and then my callback is run. I've also had problems in the past of the gui not refreshing properly, which leads me to believe that both of these are thread related. Any help would be immensely appreciated. ~Sean DiZazzo ~~~~~~~~~~~~~~~~~~~ import sys, os, time libdir = "/usr/local/sw/lib" sys.path.append(libdir) import ProgressBarView, Folder, P from Tkinter import * from tkFileDialog import askopenfilenames from tkMessageBox import showerror, showinfo import pexpect, ssh_session import P import Pmw rootWin = Tk() class Window(Frame): label = None initialdir = "/" dest = "/tmp" folder = None logpath = "/tmp/Send.log" copyindex = 0 files = [] progressWindow = None session = None password = P.P() ssh = ssh_session.ssh_session("root", "XX.XX.XX.XX", password.Decrypt(password.sean)) timeout = 30 def __init__(self, parent=None): Frame.__init__(self, parent) rootWin.title("Send to Blah") rootWin.resizable(width=0,height=0) self.pack() self.progress_and_log() f = Frame(self) openfunc = (lambda self=self, name=None: self.openfolder()) Button(f, text="Choose", command=openfunc).pack(side="left") self.label = Label(f, text=' <--- Choose files', bg="grey", width=40, justify='left', anchor='w') self.label.pack(side="left", anchor='w', padx=5) f.pack(padx=10, pady=10, side='left', fill='both', anchor='w') submitfunc = (lambda self=self, name=None: self.submit()) b = Button(self, text="Send", command=submitfunc) b.pack(side="right", padx=5) def openfolder(self): self.files = [] self.files_tuple = askopenfilenames(parent=rootWin, initialdir="/") for file in self.files_tuple: self.files.append(file) self.files.sort() label = "Click button to send files -->" self.st.configure(text_state = 'normal') self.st.clear() self.st.insert('end', "Files to be copied:\n") self.st.insert('end', "~~~~~~~~~~~~~~~~~~~\n") for file in self.files: self.st.insert('end', os.path.split(file)[-1] + "\n") self.st.insert('end', " \n \n") self.st.configure(text_state = 'disabled') self.label.config(text='Click to send files ---> ', justify='right', anchor='e') def callback(self): """Need to get the pid here and kill the running process""" def submit(self): files = self.files dest = Folder.Folder(self.dest) for file in files: if self.ssh.exists(os.path.join(dest.path, os.path.split(file)[-1])): showerror("error", "The file '%s' already exists" % os.path.join(dest.path, os.path.split(file)[-1])) return 0 import threading geometry = None for file in files: self.progressWindow = Toplevel(rootWin) self.progressWindow.protocol('WM_DELETE_WINDOW', self.callback) self.progressWindow.geometry(geometry) self.progressWindow.title("Progress") self.progressWindow.resizable(width=0,height=0) self.proglabel = Label(self.progressWindow, text='Copying...', anchor=NW, justify=LEFT, width=30) self.proglabel.pack(fill=X, expand=1) self.progressBar = ProgressBarView.ProgressBarView(self.progressWindow) self.progressBar.pack(fill=X) threading.Thread(target=self.threadedCopy,args=(file, dest)).start() #grab the location from the first window if geometry is None: self.progressBar.updateProgress(0) geometry = self.progressWindow.geometry() self.incrementProgress(self.progressWindow, file, dest) self.label.config(text=" <--- Choose files", justify='left', anchor='w') self.files=[] def progress_and_log(self): self.st = Pmw.ScrolledText(rootWin, borderframe = 1, usehullsize = 1, hull_width = 400, hull_height = 150, text_wrap='none', #text_font = fixedFont, text_padx = 4, text_pady = 4, ) self.st.configure(text_state = 'disabled') self.st.pack(padx = 5, pady = 5, fill = 'both', expand = 1) def threadedCopy(self, file, dest): self.ssh.scp(file, os.path.join(dest.path, os.path.split(file)[1])) def appendToLog(self, src, dest): dest_size = self.ssh.size(dest.path) try: dest_size = float(dest_size) except: dest_size = 0 if src.size == dest_size: status = "SUCCESS" else: status = "FAILED" entry = "%s - %s %s, %s\n" % (time.ctime(time.time()), status, src.name, src.readableSize) f = open(self.logpath, 'a') f.write(entry) f.close() self.st.configure(text_state = 'normal') self.st.insert('end', entry) self.st.configure(text_state = 'disabled') def incrementProgress(self, window, file, dest): import File src = File.File(file) dest = File.File(os.path.join(dest.path, os.path.split(file)[-1])) start = time.time() p = 0 last_dest = 0 same_count = 0 while p < 100: d_size = self.ssh.size(dest.path) try: float(d_size) except: "Couldn't turn %s into a float" % d_size continue if last_dest == d_size and same_count == 40: showerror("error", "Error copying %s\nRemoving the partially transferred file and continuing..." % dest.path) self.ssh.ssh("sudo rm %s" % dest.path) if d_size == None: d_size = 1000 self.proglabel.config(text=src.name) p = (float(d_size) / float(src.size)) * 100.0 d_size = self.ssh.size(dest.path) if last_dest == d_size: same_count = same_count +1 print "P:", p self.progressBar.updateProgress(p) self.update_idletasks() time.sleep(0.25) last_dest = d_size self.appendToLog(src, dest) window.destroy() return if __name__ == "__main__": Window().mainloop() From gagsl-py at yahoo.com.ar Wed Jan 24 13:17:01 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 15:17:01 -0300 Subject: module email In-Reply-To: References: Message-ID: <7.0.1.0.0.20070124151444.03481110@yahoo.com.ar> At Wednesday 24/1/2007 13:02, Sergey Dorofeev wrote: >Why does not work? Some details please? -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From exarkun at divmod.com Tue Jan 30 10:59:30 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Jan 2007 10:59:30 -0500 Subject: Synchronous shutil.copyfile() In-Reply-To: <4e8efcf50701300705v2b787ec4h1c539cab8068d58c@mail.gmail.com> Message-ID: <20070130155930.25807.817470641.divmod.quotient.3564@ohm> On Tue, 30 Jan 2007 15:05:23 +0000, Hugo Ferreira wrote: >Hi there, > >I have a problem. I'm using calling shutil.copyfile() followed by >open(). The thing is that most of the times open() is called before >the actual file is copied. I don't have this problem when doing a >step-by-step debug, since I give enough time for the OS to copy the >file, but at run-time, it throws an exception. > >Is there anyway to force a sync copy of the file (make python wait for >the completion)? shutil.copyfile() _is_ synchronous. Check out the source: def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error, "`%s` and `%s` are the same file" % (src, dst) fsrc = None fdst = None try: fsrc = open(src, 'rb') fdst = open(dst, 'wb') copyfileobj(fsrc, fdst) finally: if fdst: fdst.close() if fsrc: fsrc.close() The problem you are experiencing must have a different cause. Jean-Paul From jim at none Wed Jan 31 15:41:27 2007 From: jim at none (Jim) Date: Wed, 31 Jan 2007 13:41:27 -0700 Subject: Python 2.5 Tkinter not configured References: <528ctaF1nig7eU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Jim schrieb: >> I compiled Python 2.5 from python.org and I get an error message when I >> try to import the Tkinter module. Python reports that there is no such >> module. It says my Python isn't configured for Tkinter. How do I >> configure it? I'm using GCC 4.1.1 to compile the tarball. Thanks for any >> help with this. > > You need to have tcl/tk together with it's development-headers > installed. Python _should_ figure out where things are, and then be > configured to include tkinter. > > Diez That was the problem, I got it working after recompiling. Thanks. Jim From fredrik at pythonware.com Fri Jan 5 01:36:28 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Jan 2007 07:36:28 +0100 Subject: Undefined symbol __pure_virtual when importing MySQLdb In-Reply-To: <1167977378.425615.220350@51g2000cwl.googlegroups.com> References: <1167977378.425615.220350@51g2000cwl.googlegroups.com> Message-ID: antonyliu2002 at yahoo.com wrote: > I have googled hard, and did see someone asking the same question, but > haven't found a good solution to this problem. Could anyone give me a > hint? Thanks a lot! googling for "undefined symbol: __pure_virtual" brings up hundreds of posts on this topic, and the answer is *always* to make sure that you're linking with a version of the C++ libraries that matches your compiler. From pythonnews at nospam.jmbc.fr Wed Jan 17 09:55:40 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Wed, 17 Jan 2007 15:55:40 +0100 Subject: IMAP SEARCH Error In-Reply-To: <1169043202.521317.226910@q2g2000cwa.googlegroups.com> References: <1169043202.521317.226910@q2g2000cwa.googlegroups.com> Message-ID: <45ae38fc$0$21151$7a628cd7@news.club-internet.fr> > imaplib.abort: command: SEARCH => unexpected response: '*' > > Can anyone tell me why this happens ? It looks like a server problem. What kind of server are you using ? Exchange, Cyrus ? Did you try with two different Imap servers ? If it is a unix server, did you have a look in /var/log ? Or in windows event log ? From joel.hedlund at gmail.com Thu Jan 11 04:05:21 2007 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Thu, 11 Jan 2007 10:05:21 +0100 Subject: Need startup suggestions for writing a MSA viewer GUI in python In-Reply-To: References: Message-ID: > This will probably be a major, but not humongous project. wxPython, > pyGTk, and pyQt all have the architecture and basics you'll need, it > will probably be about the same amount of work to create in all of > them. Pick the one that best suites your licensing and platform needs. Thanks for the suggestions. Now I'll start my reading up. Cheers! /Joel From tinaweb at bestemselv.com Tue Jan 16 12:57:44 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 16 Jan 2007 18:57:44 +0100 Subject: PyQt: QListviewItemIterator Message-ID: Hi, I'm fairly new to both Python and Qt so please bare with me. I have a QListView with a number of columns. In order to filter the output I iterate using QListViewItemIterator looking for the string entered by the user (filterString). Currently I do it this way: it = QListViewItemIterator(self.authListView) try: while it: item = it.current() if item.text(0).contains(filterString) or item.text(1).contains(filterString) or item.text(2).contains(filterString): item.setVisible(1) else: item.setVisible(0) it +=1 except AttributeError: pass Basically I iterate through the ListView until it goes beyond the list and raise an exception, which I catch. It works but to be honest it looks and feels ugly; "Do something until it goes wrong" So, question: How can I know I have reached the last item in the QListView? Thanks Tina From http Thu Jan 25 12:30:17 2007 From: http (Paul Rubin) Date: 25 Jan 2007 09:30:17 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> Message-ID: <7x8xfrnhee.fsf@ruckus.brouhaha.com> John Nagle writes: > My main concern is with glue code to major packages. The connections > to OpenSSL, MySQL, and Apache (i.e. mod_python) all exist, but have major > weaknesses. If you're doing web applications, those are standard pieces > which need to work right. There's a tendency to treat those as abandonware > and re-implement them as event-driven systems in Twisted. Yet the > main packages aren't seriously broken. It's just that the learning curve > to make a small fix to any of them is substantial, so nobody new takes > on the problem. There is an attitude widespread in the Python community, maybe inherited from Extreme Programming, that when writing some subsystem it's enough to implement just enough functionality to satisfy the application's immediate needs. Then if the application needs more functionality from the subsystem later, go back and add it. That's fairly reasonable when the application and subsystem are being done by the same people and there's not such a learning curve. But it's unwise for libraries. For all Java's ugliness, when the Java library developers want to implement some protocol like SSL, they take the specification for the protocol and they implement it completely. Python's library modules are very often missing stuff, as you've pointed out. In the specific examples of OpenSSL, MySQL, and Apache, the modules involved aren't even part of the Python stdlib, the way JSSE and JDBC are part of the Java stdlib (I guess that doesn't apply to Tomcat though). From hg at nospam.org Tue Jan 23 10:32:50 2007 From: hg at nospam.org (hg) Date: Tue, 23 Jan 2007 16:32:50 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? References: Message-ID: <82wth.63580$Yu6.28960@newsfe16.lga> Daniel Jonsson wrote: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! > > Daniel It is best you try both ... I feel they have the same quality. The cross plateform issue depends on your needs/constraints ... I need cross-platform for commercial applications so I went for wx hg From sittner at lkb.ens.fr Tue Jan 23 08:20:58 2007 From: sittner at lkb.ens.fr (sittner at lkb.ens.fr) Date: Tue, 23 Jan 2007 14:20:58 +0100 (CET) Subject: best package for a physical simulation? In-Reply-To: References: Message-ID: <60915.195.220.102.78.1169558458.squirrel@mailgate.phys.ens.fr> Hello everyone, i would like to use python to perform some simulation involving collisions of colloidal particles. which is the best package/engine to do that in python? thanks, T From steve at REMOVE.THIS.cybersource.com.au Fri Jan 12 19:19:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 13 Jan 2007 11:19:46 +1100 Subject: Rational Numbers References: <8c7f10c60701121134q35bf7c27h7c4b5cf1dcfe44ca@mail.gmail.com> <45A7E8E9.8060105@gmx.net> Message-ID: On Fri, 12 Jan 2007 20:07:04 +0000, Simon Brunning wrote: > On 1/12/07, Thomas Ploch wrote: >> Do not forget: >> >> - Time >> - Personal Data (like birthdays, age) > > The datetime module has perfectly good classes for holding date and > time values, and age sounds like an integer to me. You've obviously never spoken to a small child who insists, absolutely insists, that they aren't five years old, but "almost five and a half". :) -- Steven. From rshepard at appl-ecosys.com Thu Jan 25 16:46:59 2007 From: rshepard at appl-ecosys.com (Rich Shepard) Date: Thu, 25 Jan 2007 13:46:59 -0800 (PST) Subject: Right-Justifying Numeric Output Message-ID: I have this print statement in a function: print '%2d $%11.2f $%10.2f $%9.2f $%9.2f' %(nper, pv, diff, ten, bonus) and I would like to have the output right justified in the specified field. My trials using .rjust(n) have produced that string in the output, not the intended results. Is there a way of right justifying numeric output? Thanks, Rich -- Richard B. Shepard, Ph.D. | The Environmental Permitting Applied Ecosystem Services, Inc. | Accelerator(TM) Voice: 503-667-4517 Fax: 503-667-8863 From __peter__ at web.de Wed Jan 17 11:36:40 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Jan 2007 17:36:40 +0100 Subject: how to write unicode to a txt file? References: <1169051293.848769.163860@s34g2000cwa.googlegroups.com> Message-ID: Frank Potter wrote: > I want to change an srt file to unicode format so mpalyer can display > Chinese subtitles properly. > I did it like this: > > txt=open('dmd-guardian-cd1.srt').read() > txt=unicode(txt,'gb18030') > open('dmd-guardian-cd1.srt','w').write(txt) > > But it seems that python can't directly write unicode to a file, > I got and error at the 3rd line: > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 85-96: ordinal not in range(128) > > How to save the unicode string to the file, please? > Thanks! You have to tell Python what encoding to use (i. e how to translate the codepoints into bytes): >>> txt = u"?hnlicher als gew?hnlich ?blich" >>> import codecs >>> codecs.open("tmp.txt", "w", "utf8").write(txt) >>> codecs.open("tmp.txt", "r", "utf8").read() u'\xe4hnlicher als gew\xf6hnlich \xfcblich' You would perhaps use 'gb18030' instead of 'utf8'. Peter From skip at pobox.com Tue Jan 16 19:51:15 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 Jan 2007 18:51:15 -0600 Subject: Queue and signals In-Reply-To: References: Message-ID: <17837.29443.82120.783476@montanaro.dyndns.org> >> Is it legal to use Queue.put in a signal handle and Queue.get in the >> main process (no thread) hg> PS: and if not is there a way to share data between a "main" and its hg> signal in a safe way (write in signal and read in main) The Queue module was designed to work in multithreaded contexts. I doubt it will work as expected in a nonthreaded application. Given that your application isn't multithreaded I suspect you can just modify an object that both your signal handler and the rest of the application reference. In particular, there's no reason your signal handler can't be a method of an instance: import signal import time class MyClass: def __init__(self): self.alarm_rang = False signal.signal(signal.SIGALRM, self.ring_alarm) signal.alarm(2) def ring_alarm(self, sig, frame): self.alarm_rang = True obj = MyClass() print obj.alarm_rang time.sleep(4.0) print obj.alarm_rang Skip From robert.kern at gmail.com Sat Jan 6 05:36:27 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 06 Jan 2007 04:36:27 -0600 Subject: howto overload with a NOP (empty statement) In-Reply-To: References: Message-ID: Stef Mientki wrote: > How should I overload / disable a method ? > In the example below I have defined the class "Power_Supply", derived > from baseclass "device". > The baseclass has a method "execute", which will be implemented in most > derived classes, but not in all. > Now apparently it's not allowed to overload a method with an empty > statement. > I could write a nonsense dummy statement, like "A= 3", but isn't there > another way ? pass -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mail at microcorp.co.za Sun Jan 14 05:08:52 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 14 Jan 2007 12:08:52 +0200 Subject: Maths error References: Message-ID: <017901c737c6$a4315fe0$03000080@hendrik> "Tim Peters" wrote: > [Nick Maclaren] > >> ... > >> Yes, but that wasn't their point. It was that in (say) iterative > >> algorithms, the error builds up by a factor of the base at every > >> step. If it wasn't for the fact that errors build up, almost all > >> programs could ignore numerical analysis and still get reliable > >> answers! > >> > >> Actually, my (limited) investigations indicated that such an error > >> build-up was extremely rare - I could achieve it only in VERY > >> artificial programs. But I did find that the errors built up faster > >> for higher bases, so that a reasonable rule of thumb is that 28 > >> digits with a decimal base was comparable to (say) 80 bits with a > >> binary base. > > [Hendrik van Rooyen] > > I would have thought that this sort of thing was a natural consequence > > of rounding errors - if I round (or worse truncate) a binary, I can be > > off by at most one, with an expectation of a half of a least > > significant digit, while if I use hex digits, my expectation is around > > eight, and for decimal around five... > > Which, in all cases, is a half ULP at worst (when rounding -- as > everyone does now). > > > So it would seem natural that errors would propagate > > faster on big base systems, AOTBE, but this may be > > a naive view.. > > I don't know of any current support for this view. It the bad old days, > such things were often confused by architectures that mixed non-binary > bases with "creative" rounding rules (like truncation indeed), and it > could be hard to know where to "pin the blame". > > What you will still see stated is variations on Kahan's telegraphic > "binary is better than any other radix for error analysis (but not very > much)", listed as one of two techincal advantages for binary fp in: > > http://www.cs.berkeley.edu/~wkahan/MktgMath.pdf > > It's important to note that he says "error analysis", not "error > propagation" -- regardless of base in use, rounding is good to <= 1/2 > ULP. A fuller elementary explanation of this can be found in David > Goldberg's widely available "What Every Computer Scientist Should Know > About Floating-Point", in its "Relative Error and Ulps" section. The > short course is that rigorous forward error analysis of fp algorithms is > usually framed in terms of relative error: given a computed > approximation x' to the mathematically exact result x, what's the > largest possible absolute value of the mathematical > > r = (x'-x)/x > > (the relative error of x')? This framework gets used because it's more- > or-less tractable, starting by assuming inputs are exact (or not, in > which case you start by bounding the inputs' relative errors), then > successively computing relative errors for each step of the algorithm. > Goldberg's paper, and Knuth volume 2, contain many introductory examples > of rigorous analysis using this approach. > > Analysis of relative error generally goes along independent of FP base. > It's at the end, when you want to transform a statement about relative > error into a statement about error as measured by ULPs (units in the > last place), where the base comes in strongly. As Goldberg explains, > the larger the fp base the sloppier the relative-error-converted-to-ULPs > bound is -- but this is by a constant factor independent of the > algorithm being analyzed, hence Kahan's "... better ... but not very > much". In more words from Goldberg: > > Since epsilon [a measure of relative error] can overestimate the > effect of rounding to the nearest floating-point number by the > wobble factor of B [the FP base, like 2 for binary or 10 for > decimal], error estimates of formulas will be tighter on machines > with a small B. > > When only the order of magnitude of rounding error is of interest, > ulps and epsilon may be used interchangeably, since they differ by > at most a factor of B. > > So that factor of B is irrelevant to most apps most of the time. For a > combination of an fp algorithm + set of inputs near the edge of giving > gibberish results, of course it can be important. Someone using > Python's decimal implementation has an often very effective workaround > then, short of writing a more robust fp algorithm: just boost the > precision. > Thanks Tim, for taking the trouble. - really nice explanation. My basic error of thinking ( ? - more like gut feel ) was that the bigger bases somehow lose "more bits" at every round, forgetting that half a microvolt is still half a microvolt, whether it is rounded in binary, decimal, or hex... - Hendrik From deets at nospam.web.de Wed Jan 10 05:42:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Jan 2007 11:42:00 +0100 Subject: Is there a way to protect a piece of critical code? References: Message-ID: <50ju7oF1fqlg6U1@mid.uni-berlin.de> Hendrik van Rooyen wrote: > Hi, > > I would like to do the following as one atomic operation: > > 1) Append an item to a list > 2) Set a Boolean indicator > > It would be almost like getting and holding the GIL, > to prevent a thread swap out between the two operations. > - sort of the inverted function than for which the GIL > seems to be used, which looks like "let go", get control > back via return from blocking I/O, and then "re - acquire" > > Is this "reversed" usage possible? > Is there some way to prevent thread swapping? > > The question arises in the context of a multi threaded > environment where the list is used as a single producer, > single consumer queue - I can solve my problem in various > ways, of which this is one, and I am curious as to if it is > possible to prevent a thread swap from inside the thread. There have been discussions to make the GIL available from python code. But it is considered a implementation detail - and this is the reason you can't do what you need the way you want to. Just use a regular lock - in the end, that is what the GIL is anyway. And besides that, you don't "get" anything by your way, as the thread-scheduling itself isn't controlled by python - instead the OS threading implementation is used. Diez From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 17:11:59 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 23:11:59 +0100 Subject: how to find the longst element list of lists In-Reply-To: References: Message-ID: <45a169f0$0$309$426a34cc@news.free.fr> Michael M. a ?crit : > How to find the longst element list of lists? For what definition of "find" ? You want the lenght of the longest sublist, it's index, or a reference to it ? > I think, there should be an easier way then this: > > s1 = ["q", "e", "d"] > s2 = ["a", "b"] > s3 = ["a", "b", "c", "d"] Err... this makes three distinct lists, not a list of lists. > if len(s1) >= len(s2) and len(s1) >= len(s3): > sx1=s1 ## s1 ist l?ngster > if len(s2) >= len(s3): > sx2=s2 > sx3=s3 > else: > sx2=s3 > sx3=s2 > (snip repeated code) Looks like it would be time to learn how to factor out repetitions... > After, the list ist sorted: > > sx1 = ["a", "b", "c", "d"] > sx2 = ["q", "e", "d"] > sx3 = ["a", "b"] > This is still not a list of lists. Now for the answer, sorted() is your friend: print sorted([s1, s2, s3], key=list.__len__, reverse=True) => [['a', 'b', 'c', 'd'], ['q', 'e', 'd'], ['a', 'b']] # Or if you really want sx1, sx2 and sx3: sx1, sx2, sx3 = sorted([s1, s2, s3], key=list.__len__, reverse=True) Is that easier enough ?-) From tinaweb at bestemselv.com Tue Jan 23 05:31:20 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 23 Jan 2007 11:31:20 +0100 Subject: PyQt4 strangeness Message-ID: I'm trying to 'convert' my self from Qt3 to Qt4 (it rocks!) and one thing seem strange: With Qt3 I usually did "from qt import *", but this does not seem to work with Qt4. I have to use "from PyQt4 import QtGui , QtCore" and also have to use "QtCore.something". Like when connecting a button: self.connect(self.ui.testButton, QtCore.SIGNAL("clicked()"), self.doSomething) Anyone know why this is? Or am I missing something very basic here? (I'm still very much a noob I guess) I'm using the Debian packages by the way. Thanks Tina From goofyheadedpunk at gmail.com Tue Jan 9 23:47:20 2007 From: goofyheadedpunk at gmail.com (Brian L. Troutwine) Date: 9 Jan 2007 20:47:20 -0800 Subject: pgen2 use questions. Message-ID: <1168404440.281588.233910@k58g2000hse.googlegroups.com> I happened to stumble upon Guido's announcement of his python2 to python3 refactoring tool earlier today (http://mail.python.org/pipermail/python-3000/2006-December/005102.html), and, after playing with it a bit, I have some use questions as I don't quite understand how the pattern matching language works. In some instances I cannot grok matching certain sorts of patterns, sometimes very simple ones. For instance, how is the following incorrect for matching pass statements? pass_stmt< 'pass'> If I wanted to insert "# Do nothing, and well." after each pass statement how would the transformation work? Why would this pattern not match function statements? funcdef< decorators < decs=any > 'def' atom < def_name=NAME > parameters < pars=any > ':' suite < suite_content=any > > If I wanted to change the function name how would I do so? How about parts of the function body? From Thomas.Ploch at gmx.net Tue Jan 9 02:23:26 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Tue, 09 Jan 2007 08:23:26 +0100 Subject: How to write temporary data to file? In-Reply-To: <1168326437.416524.154770@v33g2000cwv.googlegroups.com> References: <1168324907.803841.79020@42g2000cwt.googlegroups.com> <1168326437.416524.154770@v33g2000cwv.googlegroups.com> Message-ID: <45A342EE.3060508@gmx.net> Ravi Teja schrieb: > Thomas Ploch wrote: >> Ravi Teja schrieb: >>> Thomas Ploch wrote: >>>> Hi folks, >>>> >>>> I have a data structure that looks like this: >>>> >>>> d = { >>>> 'url1': { >>>> 'emails': ['a', 'b', 'c',...], >>>> 'matches': ['d', 'e', 'f',...] >>>> }, >>>> 'url2': {... >>>> } >>>> >>>> This dictionary will get _very_ big, so I want to write it somehow to a >>>> file after it has grown to a certain size. >>>> >>>> How would I achieve that? >>>> >>>> Thanks, >>>> Thomas >>> Pickle/cPickle are standard library modules that can persist data. >>> But in this case, I would recommend ZODB/Durus. >>> >>> (Your code example scares me. I hope you have benevolent purposes for >>> that application.) >>> >>> Ravi Teja. >>> >> Thanks, but why is this code example scaring you? >> >> Thomas > > The code indicates that you are trying to harvest a _very_ (as you put > it) large set of email addresses from web pages. With my limited > imagination, I can think of only one group of people who would need to > do that. But considering that you write good English, you must not be > one of those mean people that needed me to get a new email account just > for posting to Usenet :-). > > Ravi Teja. > Oh, well, yes you are right that this application is able to harvest email addresses. But it can do much more than that. It has a text matching engine, that according to given meta keywords can scan or not scan documents in the web and harvest all kinds of information. It can also be fed with callbacks for each of the Content-Types. I know that the email matching engine is a kind of a 'grey zone', and I asked myself, if it needs the email stuff. But I mean you could easily include the email regex to the text matching engine yourself, so I decided to add this functionality (it is 'OFF' by default :-) ). Thomas P.S.: No, I am a good person. From tim at tdw.net Fri Jan 12 12:42:42 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 12 Jan 2007 17:42:42 +0000 Subject: parsing a file name In-Reply-To: References: Message-ID: <9afea2ac0701120942w72a853b9s4ad24987c426e867@mail.gmail.com> On 12 Jan 2007 09:16:51 -0800, CSUIDL PROGRAMMEr wrote: > I have a filename > cairo-2.3.4.src.rpm > Is there any way i can only get 2.3.4 from this file name Is this a one off, or do you have to process multiple files with similar names? -- Tim Williams From jstroud at mbi.ucla.edu Tue Jan 16 18:39:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 16 Jan 2007 15:39:17 -0800 Subject: How can i eval subindex on list[ ][ ] ? In-Reply-To: <1168988937.512029.192800@q2g2000cwa.googlegroups.com> References: <1168988937.512029.192800@q2g2000cwa.googlegroups.com> Message-ID: jairodsl wrote: > Excuse me, i was trying in too many ways but i couldnt access subindex > on a list , the problem is the next: > > I have > > indif=[[0,'A'],[1,'B'],[2,'C'],[3,'D']] > > and > > indic=[[0,'B'],[1,'C'],[2,'D'],[3,'E']] > > i need to eval if indic[i][j] is equal to indif[i][j] > > I used a double for but i had got "list index out of range". How can i > do ??? > > Thanks a lot, > > Cordially, > > jDSL > py> i = 1 py> j = 0 py> indif[i][j] == indic[i][j] True Works for me. James From nagle at animats.com Sun Jan 28 14:46:41 2007 From: nagle at animats.com (John Nagle) Date: Sun, 28 Jan 2007 19:46:41 GMT Subject: Do I need Python to run Blender correctly? In-Reply-To: <9TYuh.3468$4W5.752@newsfe10.phx> References: <5%4uh.75582$wP1.6882@newssvr14.news.prodigy.net> <9TYuh.3468$4W5.752@newsfe10.phx> Message-ID: AKA gray asphalt wrote: > "John Nagle" wrote in message > news:ssTuh.36083$QU1.26111 at newssvr22.news.prodigy.net... > Is the manual you refer to the group project on blender.org or the $ manual > like the one on Ebay? > The "Blender 2.3 Guide" book. Also, if you're going to program the thing, the "Blender GameKit" book is a big help. Unless you have two screens, the online manual gets in your way. This really should go in a Blender newsgroup or forum. John Nagle From nobody at localhost.localdomain Fri Jan 12 05:50:21 2007 From: nobody at localhost.localdomain (Steven Wayne) Date: Fri, 12 Jan 2007 04:50:21 -0600 Subject: Learning Python book, new edition? References: Message-ID: On Thu, 11 Jan 2007 16:42:34 -0600, Demel, Jeff wrote: > John wrote: >>So what happens with google bots etc... Information provided >>in the email could be helpful to others that are NOT the original >> recipient. And what happens to the archive stuff? > > I will forward your response to our crack legal department. Perhaps > they can help you with your very astute questions. > > -Jeff > This email is intended only for the individual or entity to which it is > addressed. Hi, Don't take this the wrong way, but this isn't an email, it's a usenet posting. I'm also not the "individual or entity to which it is addressed" because I read it from a news server and it was addressed to "comp.lang.python". > This email may contain information that is privileged, > confidential or otherwise protected from disclosure. Then you would do well to not publish it in a public forum. > Dissemination, > distribution or copying of this e-mail or any attachments by anyone > other than the intended recipient, or an employee or agent responsible > for delivering the message to the intended recipient, is prohibited. So if this /were/ actually an email you've just given permission for an admin of any mail server the email passes through to disseminate or copy it. For those not aware: Disseminate: Verb: disseminate - cause to become widely known; "spread information"; "circulate a rumor"; "broadcast the news" > If > you are not the intended recipient of this message or the employee or > agent responsible for delivery of this email to the intended recipient, > please notify the sender by replying to this message and then delete it > from your system. Any use, dissemination, distribution, or reproduction > of this message by unintended recipients is strictly prohibited and may > be unlawful. Unlawful how? You've already given permission for an "agent responsible for delivering the message" to broadcast it around the world. Sorry for the rant, but I'm an email admin and I've just been told about the change to UK law. I'm giving our legal department even more grief. Steven -- .''`. : :' : `. `'` `- From laurent.pointal at limsi.fr Tue Jan 23 04:06:07 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 23 Jan 2007 10:06:07 +0100 Subject: Python Windows Editors In-Reply-To: <7d773$45b5cb01$83aef404$30645@news2.tudelft.nl> References: <7d773$45b5cb01$83aef404$30645@news2.tudelft.nl> Message-ID: stef a ?crit : > Laurent Pointal wrote: >> W. Watson a ?crit : >> >>> I downloaded python-2.5.msi and installed it. I believe its editor is >>> IDE. I understand there's a Win editor called pythonwin. I believe it's >>> in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this >>> exe file has just the editor or all of Python. Comments? If not how do I >>> get the PythonWin editor by itself? >>> >>> >> Have you take a look at the IDEs page in the Python Wiki (python.org)? >> >> http://wiki.python.org/moin/IntegratedDevelopmentEnvironments >> >> > just what I said, TOO many ;-) Yes, test some, and choose one. [personnaly, I use Notepad++ on Windows, and Kate on Linux, just editors, not IDEs] > and of course how do you keep these pages up-to-date ? > Zeus (commercial) isn't mentioned ... ...its a Wiki... click the right link and update it: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments?action=edit > SPE which has great credits, but can't be found, and if you find it > somewhere, no manual and it crashes within 30 seconds (repeatly) ;-) > > Not an easy task I guess, > but it would be nice to have some voting system, > (maybe only to allow voting when you have compared at least 2 programs) > that would represent the current state, > and in which new programs would have a fair chance to start. Its difficult, apart from their stability (which can get better or bad on the time, upen their evolution and the evolution of the libraries they use), its a large part of personnal taste. IMHO you can only have functionnal comparison of such tools. I started a synthesis page of editors/IDEs functionnalities in the pythonfr wiki (french) some (long) time ago... http://wikipython.flibuste.net/moin.py/EditeursEtIDESynthese But a Wiki form seem to not be the best way for such comparison... a dynamic page with a database and some dynamic request would be better. A+ Laurent. From webraviteja at gmail.com Fri Jan 12 14:11:21 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 12 Jan 2007 11:11:21 -0800 Subject: I need to consume a .NET web service in a Python client In-Reply-To: <1168626439.257622.134700@38g2000cwa.googlegroups.com> References: <1168626439.257622.134700@38g2000cwa.googlegroups.com> Message-ID: <1168629081.271619.316370@s34g2000cwa.googlegroups.com> mohit wrote: > Hello, > > I am a .NET developer experimenting with Python. > I need to consume a .NET web service in a Python client. how do I go > about it? > which libraries do i need? > pointers to help me get started would be much appreciated. > I am just a newbie to the Python world so please be bear with my novice > queries. > > thanks in advance, > Mohit Start Here http://www.diveintopython.org/soap_web_services/index.html Example Client http://www.diveintopython.org/soap_web_services/first_steps.html Ravi Teja From Barry.Carroll at psc.com Fri Jan 19 16:43:52 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 19 Jan 2007 13:43:52 -0800 Subject: OT Annoying Habits (Was: when format strings attack) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A9C@eugsrv400.psc.pscnet.com> Hello again. First off, Aahz is absolutely right. It is my choice, just as it is his choice what to read and what to ignore. My reply was about the fuss, not the choice. Secondly, can someone point me to the Standard Usenet Convention that mandates against top-posting. This is not sarcasm; I would really like to see it. You see, I recently returned to Usenet after a LONG absence. When I was last a regular Usenet citizen the Internet was new, GUI interfaces were experimental and the World Wide Web didn't exist yet. Newsreader software was text-based. Top-posting was the common practice, because it was the most convenient: you didn't have to page through an arbitrarily large number of messages, most of which you'd already read umpteen times, to get to the new stuff you were interested in. So I'd really like to know what the standard is now. I like to know which rules I'm choosing to break. ;^) Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: Aahz [mailto:aahz at pythoncraft.com] > Sent: Friday, January 19, 2007 1:12 PM > To: python-list at python.org > Subject: Re: OT Annoying Habits (Was: when format strings attack) > > In article , > Carroll, Barry wrote: > > > >Personally, I don't think top-posting is the most annoying newsgroup > >habit. I think it's making a big fuss about minor inconveniences. =20 > > Thing is, nobody will ignore your posts for following standard Usenet > conventions, but some of us will definitely ignore your posts if you > don't. It's your choice how much attention you want. > -- > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ > > Help a hearing-impaired person: http://rule6.info/hearing.html From bj_666 at gmx.net Fri Jan 19 07:11:06 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 19 Jan 2007 13:11:06 +0100 Subject: Standard streams References: <1169208432.786099.199690@11g2000cwr.googlegroups.com> Message-ID: In <1169208432.786099.199690 at 11g2000cwr.googlegroups.com>, raghu wrote: > what is standard streams in case of python? Do you mean `sys.stdin`, `sys.stdout` ans `sys.stderr`? Ciao, Marc 'BlackJack' Rintsch From GatlingGun at gmail.com Wed Jan 31 11:48:01 2007 From: GatlingGun at gmail.com (TOXiC) Date: 31 Jan 2007 08:48:01 -0800 Subject: Regex with ASCII and non-ASCII chars In-Reply-To: <1170261017.718665.179530@a75g2000cwd.googlegroups.com> References: <1170243969.504255.134100@v33g2000cwv.googlegroups.com> <1170257547.041535.20770@a75g2000cwd.googlegroups.com> <1170261017.718665.179530@a75g2000cwd.googlegroups.com> Message-ID: <1170262081.746655.174790@m58g2000cwm.googlegroups.com> On 31 Gen, 17:30, "TOXiC" wrote: > It wont work with utf-8,iso or ascii... I think the best way is to search hex value in the file stream but I tryed (in the regex) \hxx but it don't work... From richmoore44 at gmail.com Tue Jan 9 08:02:08 2007 From: richmoore44 at gmail.com (richmoore44 at gmail.com) Date: 9 Jan 2007 05:02:08 -0800 Subject: Execute binary code In-Reply-To: References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> Message-ID: <1168347728.421860.4820@v33g2000cwv.googlegroups.com> Jorgen Grahn wrote: > On 8 Jan 2007 12:29:36 -0800, olsongt at verizon.net wrote: > For what it's worth[1], under Unix it /is/ impossible. The only way to bring in > new code (short of dynamic libraries) is to call exec(2) or its variations, > and all need a file system object to load the code from. That's totally untrue, how do you think a JIT compiler works? For example you can generate x86 assembler on the fly and call it using pyASM see http://mysite.verizon.net/olsongt/usersGuide.html Cheers Rich. From hg at nospam.org Fri Jan 5 04:29:24 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 10:29:24 +0100 Subject: find a .py path References: Message-ID: Laszlo Nagy wrote: > hg i'rta: >> Hi, >> >> Is there an easy way for a script being executed (from anywhere) to know >> where is is ... something in os.path ? >> > __file__ > > You can also use os.argv[0] but that is not the same... > > Laszlo Thanks From steve at REMOVE.THIS.cybersource.com.au Mon Jan 1 07:16:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 01 Jan 2007 23:16:21 +1100 Subject: OO question References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> <1167631258.804660.154490@n51g2000cwc.googlegroups.com> Message-ID: On Sun, 31 Dec 2006 22:00:58 -0800, Paddy wrote: >> def save(self, filename): >> self.currentfile = file(filename, "w") >> for address in self.addresses: >> self.save_one_address(address.export()) >> self.currentfile.close() >> self.currentfile = None > > Small addition. > If a class does a save then it should also do the load of the data too. What, you've never heard of a write-only file? -- Steven. From yinglcs at gmail.com Mon Jan 15 19:28:10 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 15 Jan 2007 16:28:10 -0800 Subject: Can't find module named 'svn' in python Message-ID: <1168907290.539976.117270@51g2000cwl.googlegroups.com> Hi, i have a simple test which tries to load 'svn' moddule. # python -c "from svn import client" Traceback (most recent call last): File "", line 1, in ? ImportError: No module named svn I have checked I have sub-directories 'libsvn', 'svn' under /usr/local/lib/svn-python/ cd /usr/local/lib/svn-python/ [root at localhost svn-python]# ls libsvn svn But python still can't find it. Please tell me what am I missing. I appreciate your help. From rzantow at gmail.com Sat Jan 6 11:34:01 2007 From: rzantow at gmail.com (rzed) Date: Sat, 06 Jan 2007 11:34:01 -0500 Subject: Just Getting Started with Python on MS XP Pro References: <1168064599.558820.9410@42g2000cwt.googlegroups.com> Message-ID: DouhetSukd at gmail.com wrote in news:1168064599.558820.9410 at 42g2000cwt.googlegroups.com: > Wise choice + welcome to the club. Seconded. > The only real XP drawback is that Python is not bundled on > Windows, while it is included with OS X and most (all?) Linux > distros. > My computer does, in fact, include a Python 2.2.1 installation, which the manufacturer uses internally. > 2. use any ol' text editor that _you_ are familiar with, save > to file, and python under DOS. later on you can always > pick an editor. i prefer eclipse + pydev, yes, even on windows. > > personally, i find pythonwin _great_ to test out code > interactively, mediocre to write lots of code with and > occasionally handy to debug code in. > > if you hate typing python under DOS, then I guess you > will have to run programs from pythonwin. > Not so, but it takes a little setup. If I want to run a Python program named, say, "fixthis.py", I can invoke it by typing "fixthis.py" at the command-line prompt (if I'm running cmd.exe), or by clicking the icon in Windows Explorer. To make the command- line option work, I have to have file associations set so that .py files open with python (and .pyw files open with pythonw, for that matter). I *think* this is done at install time, though I may have done that separately. There is also an environment variable called "pathext", which is just a list of extensions the system recognizes as being executable in some way. if you add .py and .pyw to that list, then all you have to type at the command line is "fixthis" to get that Python program to run. I note that I have had my Python root and Python/Scripts directory on my path at times. There may be some packages that require these things, but what I talked about in the previous two paragraphs doesn't require pythonpath to be set specially. (Fiddling around) Ah! If you want to invoke the interactive python shell, you will probably want to add the root location to your path, so you can type > python ... to invoke it, rather than > c:\python25\python ... and something similar may be true for the Scripts subdirectory. -- rzed From s.mientki at id.umcn.nl Wed Jan 31 11:20:31 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 31 Jan 2007 17:20:31 +0100 Subject: another newbie question: why should you use "*args" ? In-Reply-To: References: <4b4a3$45c0b94c$83aef404$20934@news1.tudelft.nl> Message-ID: <9f3d1$45c0c1cf$83aef404$22682@news1.tudelft.nl> >> I would love that, >> but please tell me how (I need an integer counter for something else too): >> >> def chunk_plot(*args): >> if len(args) == 1: list = args[0] >> else: list = args >> >> color = ['g','r','b','y','m'] >> plot ( list[0], color[0]) >> hold (True) >> for i in range ( 1, len(list) ): >> plot ( list[i], color[i] ) >> > > No need for the counter here. > > for args in zip(list[1:], color[1:]): > plot(*args) > > that looks nice, thanks! All the other people also thanks, "enumerate" looks also better than range(len( nice ! > Ciao, > Marc 'BlackJack' Rintsch > -------------- next part -------------- An HTML attachment was scrubbed... URL: From redvasily at gmail.com Sat Jan 6 05:36:26 2007 From: redvasily at gmail.com (Vasily Sulatskov) Date: 6 Jan 2007 02:36:26 -0800 Subject: howto overload with a NOP (empty statement) In-Reply-To: References: Message-ID: <1168079786.093590.299570@v33g2000cwv.googlegroups.com> class Power_Supply (device): def execute (self): pass Stef Mientki wrote: > How should I overload / disable a method ? > In the example below I have defined the class "Power_Supply", derived > from baseclass "device". > The baseclass has a method "execute", which will be implemented in most > derived classes, but not in all. > Now apparently it's not allowed to overload a method with an empty > statement. > I could write a nonsense dummy statement, like "A= 3", but isn't there > another way ? > > thanks, Stef Mientki > > class device: > def execute (self): > print 'execute not yet implemented for', self.Name > > > class Power_Supply (device): > def execute (self): ; From pythonnews at nospam.jmbc.fr Wed Jan 24 10:36:09 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Wed, 24 Jan 2007 16:36:09 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: <45B76FE8.5080701@codebykevin.com> Message-ID: <45b77d02$0$21145$7a628cd7@news.club-internet.fr> Hi > > Just for info - one of the reasons I stopped using Tkinter a few years ago > was for the lack of print support (preview ...) - is there such an > extension today ? > Same for me, it was a point for what I choosed wx. Nowadays, I'd say users commonly accept to get pdf reports instead of direct printing, so it's not so much important. Regards, jm From dudds at netspace.net.au Sat Jan 27 09:00:19 2007 From: dudds at netspace.net.au (dudds) Date: 27 Jan 2007 06:00:19 -0800 Subject: wx Python event question In-Reply-To: <1169892089.110196.98010@a75g2000cwd.googlegroups.com> References: <1169881014.463339.257190@v45g2000cwv.googlegroups.com> <1169892089.110196.98010@a75g2000cwd.googlegroups.com> Message-ID: <1169906419.715011.245660@a75g2000cwd.googlegroups.com> Thanks Steve. On Jan 27, 8:01 pm, "Steve" wrote: > use wx.Timer - you bind a method to a timer event and define the > timer's interval when you start it > > timer = wx.Timer(self, -1) > self.Bind(wx.EVT_TIMER, self.timerMethod, timer) > timer.Start(500) > > On Jan 27, 5:56 pm, "dudds" wrote: > > > Hi I really haven't used wxPython before and I was just wondering if > > there was some sort of timer event that can be used. For example if I > > have a database that I want to query at regular intervals and display > > the results in a window is that possibly to do under a wx Python > > program? > > > So far I have come across certain event handlers, but they all seem to > > wait for something to happen, like moving the mouse, clicking on a > > button etc. I just want to display the results of a query every so > > often automatically without having to press a button to do so. > > > I'm not looking for a complete solution as I'm doing this so I can > > teach myself Python, but a bit of a hint or a nudge in the right > > direction would be great. From tiedon_jano at hotmail.com Sun Jan 7 15:14:15 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sun, 07 Jan 2007 20:14:15 GMT Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: <1168194009.220437.286210@q40g2000cwq.googlegroups.com> Message-ID: W. Watson kirjoitti: > Gabriel Genellina wrote: >> On 7 ene, 13:22, "W. Watson" wrote: >> >>>>>> https://sourceforge.net/projects/pywin32/ >> >>> As I understand it, there are two files I'm after: 1. python >>> interpreter, >>> and 2. a python editor. It's #2 that I'm having trouble downloading. The >>> link is broken. >> >> The above link should work. Follow the instructions in a previous post. >> Note that in the last step, you have to choose a mirror for >> downloading; that mirrow might be down or out-of-sync so you might get >> an error there. Choose another mirrorr... >> >> Note that you dont *need* PythonWin in order to use Python on Windows. >> The standard Python distribution works fine. Even includes a Python >> editor (IDLE) but you can use whichever editor you like to write your >> code (even Notepad...) >> > We seem to be looping. I have the Python interpreter. I would like the > pythonwin editor. The download link doesn't work on SourceForge. Where > can I get it? If not there, where? If it can't be obtained, then I'll go > to the default editor built into python-2.5.msi. > > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > ""I do not fear death. I had been dead for billions > and billions of years before I was born, and had > not suffered the slightest inconvenience from it." > -- Mark Twain (a nod to evolution) Trying to break the loop: The above link works for me. I've tried it numerous times during this looping. Clicking the link pops up a security warning informing that the browser is going to enter "https mode". Do you get that pop-up? When I accept the pop-up, I get a page containing a green rectangle "button". When I click it, I get another page in which I have to click download to go to the actual download page. If this doesn't work for you there must be something wrong with your configuration. HTH, Jussi From vamsi.hr.rec at gmail.com Thu Jan 11 02:09:19 2007 From: vamsi.hr.rec at gmail.com (Software Hiring) Date: 10 Jan 2007 23:09:19 -0800 Subject: Urgent Openings with the World's Leading Software Company !!! Message-ID: <1168499359.596195.286240@77g2000hsv.googlegroups.com> Hi Friends, Hope you're doing great. We are looking for Software Professionals with about 7 years of experience and willing to work for the World's Biggest Software Company - Microsoft. We have a variety of jobs across different verticals at Microsoft India Development Center (MSIDC) based at HITEC City in Hyderabad, India. This is a world-class facility that provides State-of-the-Art Technology, Infrastructure and Recreational Facilities that are on par with Microsoft Head Quarters in Redmond, WA. If you're interested in relocating to India for such a good opportunity and be a part of the World's Best Software Company and if you have good skill sets in: C, C++, C#, Java (for .Net Platform or Visual Studio) OR C, C++, Java, Product Development (for MS RFID Infrastructure PathFinder - Adapters) OR C, C++, driver or kernel, Linux or Unix (for Windows Serviceability) Please send your updated resume or contact us at: vamsi.hr.rec at gmail.com Also, if you are aware of any experienced Software Professionals who could be your friends, family members or colleagues who are willing to relocate to India for this opportunity, please forward this e-mail to them. Please visit http://www.microsoft.com/india/careers/idc.aspx to know more about Microsoft India Development Center and other positions available at MSIDC. Sincerely, Vamsi Narayana vamsi.hr.rec at gmail.com From jacques.cazotte at laposte.net Tue Jan 30 11:03:28 2007 From: jacques.cazotte at laposte.net (Jacques Cazotte) Date: Tue, 30 Jan 2007 17:03:28 +0100 Subject: Please take me off the list In-Reply-To: References: Message-ID: <45bf6c5a$0$28762$426a74cc@news.free.fr> Daniel kavic a ?crit : > Sorry to waste email space , but I wish to be off this list because I have tried python and it is too difficult for me. > > -Dan Hi Daniel, My name is God, and I am quite new to mailing lists. I sometimes wonder wether computerizing the whole thing was a good idea. Do You want to give up the List downthere, and proceed to heavens, or be completely erased? Do You want me to remove python from the list of available langages? (I didnt even remember I had done this one). Without any answer from You within 1000 years, we shall transmit your demand to the Comitee. From carsten at uniqsys.com Sat Jan 6 11:15:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 06 Jan 2007 11:15:18 -0500 Subject: Python re expr from Perl to Python In-Reply-To: References: Message-ID: <1168100118.3341.9.camel@localhost.localdomain> On Sat, 2007-01-06 at 15:43 +0100, Michael M. wrote: > In Perl, it was: > > > ## Example: "Abc | def | ghi | jkl" > ## -> "Abc ghi jkl" > ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st > pipe). > $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; > > ## -- remove [ and ] in text > $na =~ s/\[//g; > $na =~ s/\]//g; > # print "DEB: \"$na\"\n"; > > > # input string > na="Abc | def | ghi | jkl [gugu]" > # output > na="Abc ghi jkl gugu" > > > How is it done in Python? Here's an almost literal translation: ################################################## import re na = re.sub(r"\ \|(.*?)\ \|(.*?)\ \|", r"\2", na) na = na.replace("[", "") na = na.replace("]", "") ################################################## Background information on regular expressions in Python can be found here: http://www.amk.ca/python/howto/regex/ http://docs.python.org/lib/module-re.html Hope this helps, Carsten. From paul.sijben at xs4all.nl Wed Jan 10 02:38:18 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 08:38:18 +0100 Subject: maximum number of threads Message-ID: <45a497ec$0$331$e4fe514c@news.xs4all.nl> I have a server in Python 2.5 that generates a lot of threads. It is running on a linux server (Fedora Core 6). The server quickly runs out of threads. I am seeing the following error. File "/home/sijben/ORCA/src/libmercury_mt.py", line 565, in __init__ MercuryObject.__init__(self,mylink) File "/home/sijben/ORCA/src/libmercury_mt.py", line 223, in __init__ self.start() File "/usr/local/lib/python2.5/threading.py", line 434, in start _start_new_thread(self.__bootstrap, ()) error: can't start new thread Does anyone know what it going on here and how I can ensure that I have all the threads I need? Paul From bearophileHUGS at lycos.com Thu Jan 25 06:06:42 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Jan 2007 03:06:42 -0800 Subject: str and __setitem__ In-Reply-To: References: Message-ID: <1169723202.289924.63650@m58g2000cwm.googlegroups.com> Peter Otten: > >>> class mutable_str(object):... def __init__(self, value): > ... self._value = value > ... def __setitem__(self, index, value): > ... self._value = self._value[:index] + value + > self._value[index+1:] > ... def __str__(self): > ... return self._value > ...>>> a = mutable_str("123") > >>> a[1] = "x" > >>> print a For this purpose an array may be better, if you have to change it often and print is only once in a while: from array import array a = array("c", "123") a[1] = "x" print a The OP can also use a class, if some other methods are needed: from array import array class mutable_str(object): def __init__(self, value): self._value = array("c", value) def __setitem__(self, index, value): self._value[index] = value def __str__(self): return self._value.tostring() # this requires time a = mutable_str("123") a[1] = "x" print a Probably array.array can be subclassed too... bye, bearophile From salvatore.difazio at gmail.com Tue Jan 16 08:59:53 2007 From: salvatore.difazio at gmail.com (Salvatore Di Fazio) Date: 16 Jan 2007 05:59:53 -0800 Subject: Watch log In-Reply-To: <1168924866.691081.251880@q2g2000cwa.googlegroups.com> References: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> <1168924866.691081.251880@q2g2000cwa.googlegroups.com> Message-ID: <1168955992.751736.4170@38g2000cwa.googlegroups.com> Michele Simionato ha scritto: > You may begin from this: Tnx Michele From hg at nospam.org Wed Jan 24 11:38:59 2007 From: hg at nospam.org (hg) Date: Wed, 24 Jan 2007 17:38:59 +0100 Subject: Python does not play well with others References: Message-ID: <86Sth.49189$sE7.21480@newsfe21.lga> egbert wrote: > On Wed, Jan 24, 2007 at 06:24:37AM +0000, Harry George wrote: >> >> Perl - excellent modules and bindings for just about everything ... >> Java - a world of its own. They reinvent the wheel instead of ... >> PHP - are we talking web scripts or serious programs? Are you ... >> C - the portable assembler. Solid, trusted, tunable ... >> C++ - objects tacked onto C; but that didn't work so invent ... >> Python - it just works. Same scripts run on every platform ... > > What about C# ? > e > -- > Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 > ======================================================================== arf arf From irmen.NOSPAM at xs4all.nl Sun Jan 28 21:27:28 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 29 Jan 2007 03:27:28 +0100 Subject: socket.inet_ntop, and pton question In-Reply-To: References: <12rpns1tkp0e34@corp.supernews.com> <45bce8f7$0$334$e4fe514c@news.xs4all.nl> Message-ID: <45bd5bb4$0$325$e4fe514c@news.xs4all.nl> Gabriel Genellina wrote: > But these are not the requested functions, inet_ntop() and inet_pton(): > > py> socket.inet_ntop > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'inet_ntop' > > Oops, my bad. Should have had more coffee before replying I guess. --Irmen From bearophileHUGS at lycos.com Thu Jan 18 17:27:15 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Jan 2007 14:27:15 -0800 Subject: A note on heapq module In-Reply-To: <8NSdnf38_otYcjLYnZ2dnUVZ_tadnZ2d@comcast.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> <1169117876.063858.56570@s34g2000cwa.googlegroups.com> <8NSdnf38_otYcjLYnZ2dnUVZ_tadnZ2d@comcast.com> Message-ID: <1169159235.864192.263210@v45g2000cwv.googlegroups.com> Steven Bethard wrote: > The current code fails when using unbound methods however:: I don't like your solution, this class was already slow enough. Don't use unbound methods with this class :-) Maybe there's a (better) solution to your problem: to make Heap a function (or classmethod) that return sone of two possibile objects created by one of two different classes that have different methods... Beside that, I think __eq__ method needs more tests, because comparing a Heap with key against another Heap without key may give some problems... I'll think about such problems/things. Bye, bearophile From peterbe at gmail.com Fri Jan 5 11:10:25 2007 From: peterbe at gmail.com (peterbe at gmail.com) Date: 5 Jan 2007 08:10:25 -0800 Subject: elementtree.SimpleXMLWriter and xmlcharrefreplace In-Reply-To: <1168012797.140846.159160@q40g2000cwq.googlegroups.com> References: <1168012797.140846.159160@q40g2000cwq.googlegroups.com> Message-ID: <1168013425.344157.36970@42g2000cwt.googlegroups.com> My current version of SimpeXMLWriter is: $Id: SimpleXMLWriter.py 1862 2004-06-18 07:31:02Z Fredrik $ I'm testing this on in python2.3.5 and python2.4.3. peterbe at gmail.com wrote: > I'll try to explain my problem with code. > The problem is the output > > msg = u"S?dert?lje & Bor?s" # latin1 unicode string with a & > > from elementtree.SimpleXMLWriter import XMLWriter > from cStringIO import StringIO > out = StringIO() > w = XMLWriter(out) > body = w.start("body") > w.element("text", msg) > w.close(body) > return out.getvalue() > > Here's the output I get: > Södertälje &amp; Borås > Here's what I would want and expect: > Södertälje & Borås > > Notice that & is converted to &amp; when it should be & or &38; > only. From http Thu Jan 11 01:31:39 2007 From: http (Paul Rubin) Date: 10 Jan 2007 22:31:39 -0800 Subject: Is there a way to protect a piece of critical code? References: <7xzm8q6pw7.fsf@ruckus.brouhaha.com> Message-ID: <7xsleiysz8.fsf@ruckus.brouhaha.com> Paul Rubin writes: > def get_from_queue(queue): > try: > return queue.get(block=False) > except Queue.Empty: > return QUEUE_IS_EMPTY Alternatively: def get_from_queue(queue): try: return (queue.get(block=False), True) except Queue.Empty: return (None, False) This is maybe a nicer interface (no special sentinel value needed). You'd use value, nonempty = get_from_queue(queue) if nonempty is true then the item is valid. From tmosher at epix.net Sun Jan 7 21:50:59 2007 From: tmosher at epix.net (tim mosher) Date: Sun, 7 Jan 2007 21:50:59 -0500 Subject: Finding the name of a class Message-ID: <000001c732cf$d6779a10$01fea8c0@mosherfamily> Hello I'm looking for a Larry Bates that was in the Navy. Could this be you?? In CT in 1965??? In your 60's?? Please let me know I have been searching for over 10 yrs thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Mon Jan 8 19:09:09 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 21:09:09 -0300 Subject: Fwd: Execute binary code In-Reply-To: <1168290090.137259.324360@i15g2000cwa.googlegroups.com> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168289145.319706.199950@11g2000cwr.googlegroups.com> <4866bea60701081251we2bf7f3vb55a285ee20e91f6@mail.gmail.com> <1168290090.137259.324360@i15g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070108194009.03993008@yahoo.com.ar> At Monday 8/1/2007 18:01, citronelu at yahoo.com wrote: >Chris Mellon wrote: > > Writing to a temp file will be at least 3 times as easy and twice as > > reliable as any other method you come up with. > >I'm not disputing that, but I want to keep a piece of code (a parser >for Oracle binary dumps, that I didn't wrote) out of foreign hands, as >much as possible. Using a TEMP directory is not "stealth" enough. This is what I would do (untested of course!) (Mostly using the Win32 API so you'll have to use pywin32 or ctypes). Call CreateFile with dwShareMode=0, FILE_ATTRIBUTE_TEMPORARY, FILE_FLAG_NO_BUFFERING, FILE_FLAG_DELETE_ON_CLOSE. That means that no other process could open the file, if it fits in available memory probably it won't even be written to disk, and it will be deleted as soon as it has no more open handles. File name does not have to end in .exe. Copy the desired contents into a buffer obtained from VirtualAlloc; then call WriteFile; release the buffer (rounding size up to next 4KB multiple) Then CreateProcess with CREATE_SUSPENDED, and CloseHandle on the file, and CloseHandle on the two handles returned on PROCESS_INFORMATION. At this stage, the only open handle to the temporary file is held by the section object inside the process. Then ResumeThread(hTread) -process begins running- and WaitForSingleObject(hProcess) -wait until finishes-. As soon as it finishes execution, the last handle to the file is closed and it is deleted. Another approach would be to go below the Windows API and use the native API function NtCreateProcess -officially undocumented- which receives a section handle (which does not have to be disk based). But this interfase is undocumented and known to change between Windows versions... Or search for a rootkit... -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From beliavsky at aol.com Sun Jan 21 19:00:30 2007 From: beliavsky at aol.com (Beliavsky) Date: 21 Jan 2007 16:00:30 -0800 Subject: Reading Fortran Data In-Reply-To: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> Message-ID: <1169424030.101768.124000@m58g2000cwm.googlegroups.com> Tyler wrote: > Hello All: > > After trying to find an open source alternative to Matlab (or IDL), I > am currently getting acquainted with Python and, in particular SciPy, > NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's > NumPy manual, I have a quick question (hopefully) regarding how to read > in Fortran written data. > > The data files are not binary, but ASCII text files with no formatting > and mixed data types (strings, integers, floats). For example, I have > the following write statements in my Fortran code: In plain Python, you can read each line in to a string, break the string into "words" using split, and then convert the words into variables of the desired types. If you are new to Python, this is an important idiom to learn. I don't know if NumPy has facilities to do this more easily. > I write the files as such: > WRITE(90,'(A30)') fgeo_name > WRITE(90,'(A30)') fmed_name Let me comment on the Fortran code. For the following lines using list-directed output, the compiler has considerable freedom in how it writes the output. I guess you expect the integers nfault and npoint to be written on one line and the vectors xpt and ypt to each be written on separate lines. The compiler could print each number on a separate line and be standard-conforming. This does not matter if you are going to use a Fortran list-directed read to read the file, but it will matter if you are using other languages. I suggest that you use format strings to get more control over the ouptput format before you think about reading the output files in Python. Otherwise you will be trying to hit a moving target. From nagle at animats.com Tue Jan 30 14:59:41 2007 From: nagle at animats.com (John Nagle) Date: Tue, 30 Jan 2007 19:59:41 GMT Subject: Sourcing Python Developers In-Reply-To: <45be52f5$1@news.arcor-ip.de> References: <45BE4348.9020500@gmail.com> <45be52f5$1@news.arcor-ip.de> Message-ID: Ralf Sch?nian wrote: > Kartic schrieb: > >> Hello, >> >> My company has quite a few opening involving python expertise. We are >> always looking for python resources (and find it difficult filling >> these positions, might I add). Is there any place to find developers' >> resumes (like finding jobs from http://python.org/community/jobs/)? If >> any one knows of a resume repository (other than Monster, Dice, >> Costs-an-arm-and-leg job site) please share. > > > Do not know if you have to give your arm or your leg away, but maybe the > following place is of interest for you: > > http://www.opensourcexperts.com > > Ralf Schoenian I'd recommend against Rent-A-Coder. I put a job out there (overhauling "rwhois.py"), and three "coders" in succession tried it and gave up. John Nagle From basti.wiesner at gmx.net Wed Jan 3 11:36:07 2007 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Wed, 03 Jan 2007 17:36:07 +0100 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: [ Ivan Voras ] > Sebastian 'lunar' Wiesner wrote: >> Carsten Haese typed > >>> I don't think that that has anything to do with Linux or not. The >>> script is not the actual executable, hence its suid bit is >>> irrelevant. >> >> I don't think so. From what I know, the script is passed as >> executable to the kernel loader, which interprets the shebang and >> feeds the script through the correct interpreter. So the kernel >> loader sees the script itself as executable instead of the >> interpreter binary. I've heard of other Unix systems, which handle >> this differently (meaning that the SUID bit on scripts has an >> effect), but I may be wrong. > > Yes, the kernel parses #! but the suid-ness is still controlled by the > target interpreter (i.e. python executable). At least BSD systems also > behave this way. I don't think, that the interpreter controls SUID-ness. Privileges are always handled by the kernel. At least the kernel needs to agree, when a normal user wants to execute a SUID scripts. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From fccoelho at gmail.com Thu Jan 25 04:23:18 2007 From: fccoelho at gmail.com (Flavio) Date: 25 Jan 2007 01:23:18 -0800 Subject: raise UnicodeError, "label too long" In-Reply-To: References: <1169672223.231030.262610@l53g2000cwa.googlegroups.com> <1169675004.099912.79520@v33g2000cwv.googlegroups.com> <45B7D4F7.9020308@v.loewis.de> <1169684719.607504.307310@l53g2000cwa.googlegroups.com> Message-ID: <1169716998.773756.43930@v33g2000cwv.googlegroups.com> Guys, I am sorry I wrote these messages very late at night. Naturally what came before the dot is the language defining two letter string that is usual of wikipedia urls. Something in my code is obviously gobbling that up. Thanks for pointing that out and my apologies again for not seeing this obvious bug. On Jan 25, 4:39 am, Dennis Lee Bieber wrote: > On 24 Jan 2007 16:25:19 -0800, "Flavio" declaimed > the following in comp.lang.python: > > > > > something like this, for instance: > >http://.wikipedia.org/wiki/Copper%28II%29_hydroxide Was there some text between the // and .wikipedia? As written this, > and the next one, both lock up Firefox. Take out the . and they work (or > put www before the . ). > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ From gagsl-py at yahoo.com.ar Thu Jan 25 01:28:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 03:28:32 -0300 Subject: ftplib and retrbinary or retrlines (losing newline characters in my log files) In-Reply-To: <7d1760310701242205u6e6b4706ja20e3c07406a8064@mail.gmail.co m> References: <7d1760310701242205u6e6b4706ja20e3c07406a8064@mail.gmail.com> Message-ID: <7.0.1.0.0.20070125031353.0452a4f8@yahoo.com.ar> At Thursday 25/1/2007 03:05, aus stuff wrote: >Hi am successfully downloading my text files and writing them to >local files with either > >ftp.retrlines('RETR ' + fl, fileObj.write)" > >ftp.retrbinary('RETR ' + fl, fileObj.write) > >However all my recieved (log) files have lost thier newline characters? Both methods are different. From the docs for retrlines: "Retrieve a file or directory listing in ASCII transfer mode (...) The callback function is called for each line, with the trailing CRLF stripped.". The callback should be responsible of writting the missing '\n' then (fileObj should have been opened in text mode): ftp.retrlines('RETR ' + fl, lambda line: fileObj.write('%s\n' % line)) Using retrbinary() you get the file in pieces, thay you should write in binary mode (just as the original code). The resulting file should be identical to the original file on the server. Line endings may be different on both platforms (some editors may allow to convert between \n, \r\n, \r...). That's why for a log file the ASCII transfer mode is better. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gandalf at designaproduct.biz Fri Jan 5 11:33:09 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 17:33:09 +0100 Subject: find a .py path In-Reply-To: <0Nunh.45640$gl2.30462@newsfe16.lga> References: <0Nunh.45640$gl2.30462@newsfe16.lga> Message-ID: <459E7DC5.20800@designaproduct.biz> hg ?rta: > hg wrote: > > >> Hi, >> >> Is there an easy way for a script being executed (from anywhere) to know >> where is is ... something in os.path ? >> >> Thanks, >> >> hg >> > > oops: os.path.abspath(sys.argv[0]) > Be aware with this. It is different when you do /usr/bin/python prog.py and ./prog.py In the first case, sys.argv[0] will be /usr/bin/python! You should better use os.path.abspath(__file__) (that will work for normal python programs, but not for py2exe compiled programs or for modules imported from a zip file...) Best, Laszlo From hg at nospam.org Sat Jan 27 09:59:02 2007 From: hg at nospam.org (hg) Date: Sat, 27 Jan 2007 15:59:02 +0100 Subject: looking for ppp dialing tutorial / resources Message-ID: Hi, I need to implement ppp client connection in my program ... found chestnut dialer so far ... any other resource in mind ? Thanks hg From larry.bates at websafe.com Thu Jan 11 13:13:09 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 11 Jan 2007 12:13:09 -0600 Subject: Python - C# interoperability In-Reply-To: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> References: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> Message-ID: <45A67E35.4050107@websafe.com> mc wrote: > Is there an easy way to compile a Python class (or set of classes) into > a .DLL that a C# program can call? Or otherwise to use an existing > library of Python classes from a C# program as seamlessly as possible? > You can write COM objects that can be called from C# (or basically ANY other language that can call COM objects) quite easily and compile them with py2exe for distribution without python itself. -Larry Bates From mail at microcorp.co.za Fri Jan 12 00:00:34 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Jan 2007 07:00:34 +0200 Subject: Is there a way to protect a piece of critical code? References: <7xzm8q6pw7.fsf@ruckus.brouhaha.com> Message-ID: <003601c73606$98340c40$03000080@hendrik> "Paul Rubin" wrote: > "Hendrik van Rooyen" writes: > > am aware of Queue module - the same app uses it for something else. > > I dont like too many try -- excepts in the code - I find they confuse > > me when I try to read it later - and in this case I cannot block on waiting for > > the queue to fill. > > Do you have multiple threads reading from the same queue? If not then > you can use queue.empty() to see whether the queue is empty. If yes, > queue.empty isn't reliable (it can return nonempty, and then another > thread empties out the queue before you get a chance to read it). But > you could always wrap the queue: > > QUEUE_IS_EMPTY = object() # global sentinel > > def get_from_queue(queue): > try: > return queue.get(block=False) > except Queue.Empty: > return QUEUE_IS_EMPTY > > Maybe it's worth adding a method like that to the Queue module in the stdlib. > There is only one reader. I like this its clever, thanks - Hendrik From anthony at pob.org.uk Sun Jan 21 17:20:03 2007 From: anthony at pob.org.uk (Ant) Date: 21 Jan 2007 14:20:03 -0800 Subject: Python Windows Editors In-Reply-To: References: Message-ID: <1169418003.870318.270800@51g2000cwl.googlegroups.com> The pywin32 extension does not contain the python runtime itself, but comes with many (very useful) classes you can use when interacting with the windows universe. The editor is based on a component called scintilla (http://www.scintilla.org/). The referenced site also offers an editor SciTE based around the component, which comes with some nice features and syntax files for a number of languages. If you are going to make use of python on the windows platform, I would highly recommend the pywin32 extension. Regards, Ant W. Watson wrote: > I downloaded python-2.5.msi and installed it. I believe its editor is IDE. I > understand there's a Win editor called pythonwin. I believe it's in the > download pywin32-210.win32-py2.5.exe, but I'm not sure if this exe file has > just the editor or all of Python. Comments? If not how do I get the > PythonWin editor by itself? > > BTW, one of the features I did not like of IDE is the limited file Print > command. It puts everything in 16pt type, and gives no choice over what > pages should be printed. Maybe there's an option? > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Two laws Newton and Einstein didn't discover: > 1. Time is money. > 2. Matter will be damaged in direct proportion > to its value. > -- > Web Page: From yacinechaouche at gmail.com Mon Jan 29 10:31:33 2007 From: yacinechaouche at gmail.com (ychaouche) Date: 29 Jan 2007 07:31:33 -0800 Subject: HTMLParser's start_tag method never called ? Message-ID: <1170084691.837503.10520@j27g2000cwj.googlegroups.com> Hi, python experts. chaouche at CAY:~/TEST$ python nettoyageHTML.py chaouche at CAY:~/TEST$ This is the nettoyageHTML.py python script from HTMLParser import HTMLParser class ParseurHTML(HTMLParser): def __init__(self): HTMLParser.__init__(self) def start_body(self,attrs): print "this is my body" p = ParseurHTML() p.feed(open("/home/chaouche/TEST/AJAX/testXMLRPC.html","r").read()) this is the testXMLRPC.html html file : NON The script should output "this is my body", but nothing is printed. Anyone ? Y.Chaouche From robert.kern at gmail.com Wed Jan 24 19:42:04 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 24 Jan 2007 18:42:04 -0600 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: <49E1CCC0-D22F-4411-B192-429E42045578@datafly.net> References: <45b72b0d$0$5107$ba4acef3@news.orange.fr> <49E1CCC0-D22F-4411-B192-429E42045578@datafly.net> Message-ID: Sean Schertell wrote: > Not to totally hijack the thread -- but since you're all talking > about best GUI frameworks. Any thoughts on the best looking framework > for OS X only? Is there any way to write little Python apps that will > launch in OS X using OS X widgets? Use PyObjC. You have full access to the Cocoa framework. http://pyobjc.sourceforge.net/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From heikki at osafoundation.org Fri Jan 19 20:59:36 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 19 Jan 2007 17:59:36 -0800 Subject: More M2Crypto issues In-Reply-To: References: <6u7sh.264$4H1.150@newssvr17.news.prodigy.net> Message-ID: John Nagle wrote: > OpenSSL version: "OpenSSL 0.9.7a Feb 19 2003" Hmm, I've never actually used that old OpenSSL myself, just assumed from the original author's notes that anything from 0.9.7 onward worked. Guess not. I am thinking of changing the requirements to state which one works... I think the oldest that I have personally tested may have been 0.9.7d. -- Heikki Toivonen From bigblueswope at gmail.com Wed Jan 24 11:33:34 2007 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 24 Jan 2007 11:33:34 -0500 Subject: smtplib starttls gmail example - comments? In-Reply-To: <9afea2ac0701240724v6416c530v2e97d7c7ccd701f3@mail.gmail.com> References: <9afea2ac0701240256kae247b3s666be6529362c84e@mail.gmail.com> <9afea2ac0701240724v6416c530v2e97d7c7ccd701f3@mail.gmail.com> Message-ID: Sweet! -------------- next part -------------- An HTML attachment was scrubbed... URL: From edquichan at yahoo.com Thu Jan 18 14:02:26 2007 From: edquichan at yahoo.com (EdG) Date: 18 Jan 2007 11:02:26 -0800 Subject: Traversing the properties of a Class In-Reply-To: References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> Message-ID: <1169146946.319702.145110@v45g2000cwv.googlegroups.com> Thanks. Daniel Nogradi wrote: > > I'm using Python version 2.4 and I created a class with some properties > > like: > > > > def GetCallAmount(self): > > return somedata > > > > def GetCallCurrency(self): > > return somemoredata > > > > more....defs..etc. > > > > CallAmount = property(GetCallAmount,None,None,None) > > CallCurrency = property(GetCallCurrency, None, None, None) > > > > more....properies..etc. > > > > For debugging purposes, I would like to traverse the class listing out > > all the properties. > > > for attr in dir( yourclass ): > if repr( yourclass.__dict__[ attr ] ).startswith( ' print 'This looks like a property although can be something > else too: ' + attr > > :) From phd at phd.pp.ru Tue Jan 30 14:58:00 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Tue, 30 Jan 2007 22:58:00 +0300 Subject: SQLObject 0.7.3 Message-ID: <20070130195800.GB7446@phd.pp.ru> Hello! I'm pleased to announce the 0.7.3 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.3 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.2 ---------------- Bug Fixes ~~~~~~~~~ * Allow multiple MSSQL connections. * Psycopg1 requires port to be a string; psycopg2 requires port to be an int. * Fixed a bug in MSSQLConnection caused by column names being unicode. * Fixed a bug in FirebirdConnection caused by column names having trailing spaces. * Fixed a missed import in firebirdconnection.py. * Remove a leading slash in FirebirdConnection. * Fixed a bug in deep Inheritance tree. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From tim at tdw.net Thu Jan 25 07:53:01 2007 From: tim at tdw.net (Tim Williams) Date: Thu, 25 Jan 2007 12:53:01 +0000 Subject: While loop with "or"? Please help! In-Reply-To: References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> <45b8a31d$0$2401$426a74cc@news.free.fr> Message-ID: <9afea2ac0701250453s7d0d0887hf32aebabb754867d@mail.gmail.com> On 25/01/07, Bruno Desthuilliers wrote: > Peter Otten a ?crit : > > Bruno Desthuilliers wrote: > > > >> and simplified again thanks to Python 'in' operator: > >> while not usrinp.lower() in "yn": > > > > But note that 'in' performs a substring search and therefore "yn" and "" > > would be accepted as valid answers, too. > > Mmm, right. Thanks for the correction. > > => > while not usrinp.lower() in ['y', 'n']: or better still while usrinp.lower() not in ['y', 'n']: :):) -- Tim Williams From s.mientki at id.umcn.nl Thu Jan 11 09:55:02 2007 From: s.mientki at id.umcn.nl (stef) Date: Thu, 11 Jan 2007 15:55:02 +0100 Subject: globals accros modules In-Reply-To: References: Message-ID: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> > > Change a=1 to amodule.a=1 > If you find yourself doing tricks with the module globals, think about > redesigning your application. > Of course I completely agree with you. But ... if you're moving from MatLab to Python, and want to show your collegaes, with how little effort they can reuse all their existing MatLab routines in Python, then the global issue is a real pain !! You can explain your collegaes, that - the startindex of arrays changes from 1 to 0 - slices are upto, instead of including the final border - indention is th? key And tell them about all beautiful things in Python, but tell them that they are going to loose all their globals ??? cheers, Stef Mientki From kleiner at hora-obscura.de Thu Jan 18 05:19:36 2007 From: kleiner at hora-obscura.de (Stefan Palme) Date: Thu, 18 Jan 2007 11:19:36 +0100 Subject: DOTALL not working as expected References: Message-ID: Just noticed, that it works when *compiling* the pattern: import re p = re.compile('X.*?Y', re.DOTALL) print re.sub(p, 'Z', 'Xab\ncdY') Still the question - my fault or a bug? Best regards -stefan- On Thu, 18 Jan 2007 11:10:08 +0100, Stefan Palme wrote: > > Hi all, > > using the "re" module of Python (2.3 and 2.4), I tried the following: > > import re > print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL) > > I wanted to replace > Xab > cdY > by a single "Z", but the "." in the pattern does not match the > included "\n". > > When using the pattern "X(.|\n)*?Y" (explicity including "\n" > in the set of "any character") I get the wanted result. > > My fault or a bug in the module? > > Thanks > -stefan- From horpner at yahoo.com Thu Jan 11 10:33:51 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Jan 2007 16:33:51 +0100 Subject: __init__ vs __new__ References: <7sicq25i3qbddgst5fdjhu5i7d1p8j5qg1@4ax.com> Message-ID: On 2007-01-11, Daniel Klein wrote: > I've have a program that is using both of the methods below (in > different classes of course) for initializing the class. The > example below shows a class with the 2 methods with one > commented out. > > class JsubroutineParameters(list): > "Represents a list of arguments for external subroutine calls." > # We only need to override methods which add objects to the list. > > def __init__(self, alist = []): > for objekt in alist: _validateParameter(objekt) > self.extend(alist) > > #def __new__(cls, alist = []): > # for objekt in alist: _validateParameter(objekt) > # return list.__new__(cls, alist) > > I don't really notice any behavioral difference. Is there in > fact any difference in using one over the other? Performance? > Side effects? ??? > > I am using Python version 2.5. The second version doesn't work the way you might be assuming. Guido's paper says that mutable builtins like list have a dummy __new__ static method. So 'return list.__new__(cls, alist)' does nothing. It seems to work because the base class __init__ performs the initialization (assuming your __init__ above is commented out). You can see this by providing a dummy __init__. class Example(list): def __new__(cls, alist): return list.__new__(cls, alist) def __init__(self, alist): pass >>> a = Example(range(5)) >>> a [] There is no need to use __new__ for mutable builtin types. Since all you want from this construction is a side-effect, you can nevertheless use it in this case. Your __init__ should call the base-class __init__. It's usually a bad idea to provide mutable types as default arguments. Since you aren't modifying alist in __init__ you can get away with it here, but getting in the habit of using the below idiom might save you from a "gotcha" someday. class JsubroutineParameters(list): def __init__(self, alist=None): if alist is None: alist = [] for objekt in alist: _validateParameter(objekt) list.__init__(self, alist) You will no longer need to call append. -- Neil Cerutti From nick at craig-wood.com Sat Jan 27 08:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 27 Jan 2007 07:30:06 -0600 Subject: assertions to validate function parameters References: Message-ID: Matthew Woodcraft wrote: > I have a question for you. Consider this function: > > def f(n): > """Return the largest natural power of 2 which does not exceed n.""" > if n < 1: > raise ValueError > i = 1 > while i <= n: > j = i > i *= 2 > return j > > If I pass it an instance of MyNumericClass, it will return an int or a > long, not an instance of MyNumericClass. > > In your view, is this a weakness of the implementation? Should the > author of the function make an effort to have it return a value of the > same type that it was passed? Possibly... It is relatively easy to do anyway and reasonably cheap so why not? In this case a number about the same size as the original number (possibly very large) will be returned so the argument that it should return the same type is reasonably strong. >>> def f(n): ... """Return the largest natural power of 2 which does not exceed n.""" ... if n < 1: ... raise ValueError ... i = n - n + 1 ... while i <= n: ... j = i ... i *= 2 ... return j ... >>> f(1023) 512 >>> from decimal import Decimal >>> f(Decimal("1023")) Decimal("512") >>> There are other ways of writing that i = n - n + 1 eg i = n.__class__(1) It it basically saying "make me a numeric type with this value" so maybe the __class__ is the clearest. It assumes that the constructor can co-erce an int into the type, wheras the first assumes that the type can add an int. Here is my function to calculate arctan() from any type. The only subtle bit for a general numeric type is detecting when we've calculated enough, without using any specific knowledge about which numeric type. def arctan(x): """ Calculate arctan(x) arctan(x) = x - x**3/3 + x**5/5 - ... (-1 < x < 1) """ total = x power = x divisor = 1 old_delta = None while 1: power *= x power *= x power = -power divisor += 2 old_total = total total += power / divisor delta = abs(total - old_total) if old_delta is not None and delta >= old_delta: break old_delta = delta return total >>> arctan(0.5) 0.46364760900080587 >>> arctan(Decimal("0.5")) Decimal("0.4636476090008061162142562314") -- Nick Craig-Wood -- http://www.craig-wood.com/nick From grahn+nntp at snipabacken.dyndns.org Thu Jan 11 06:48:09 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 11 Jan 2007 11:48:09 GMT Subject: Execute binary code References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> <1168355051.339026.211830@v33g2000cwv.googlegroups.com> Message-ID: On 9 Jan 2007 07:04:11 -0800, sturlamolden wrote: > > Jorgen Grahn wrote: > >> For what it's worth[1], under Unix it /is/ impossible. The only way to bring in >> new code (short of dynamic libraries) is to call exec(2) or its variations, >> and all need a file system object to load the code from. > > The x86 processor cannot tell the difference between code segments and > data segments. If the executable code is stored in string, all you need > is a pointer to the string holding the code. You can cast the string > address to a function pointer (possibly through a void* if the compiler > complains), then dereference (call) the function pointer. > > Trojans, viruses and JIT compilers do this all the time. Here is an > (untested) example: [...] You probably need to flush the code cache somewhere there, too, don't you? Or will that resolve itself because that memory area hasn't been executed before? I must admit I haven't contemplated this since the MC68000 was state of the art, before caches became popular. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From sbassi at clubdelarazon.org Thu Jan 25 13:58:18 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 25 Jan 2007 15:58:18 -0300 Subject: Module for SVG? Message-ID: <9e2f512b0701251058k97ead4h89ccf1f4a40f269a@mail.gmail.com> Hello, I found http://www2.sfk.nl/svg as a Python module for writing SVG. Last update was in 2004 and I am not sure if there is something better. Any recommendation for generating SVG graphics? Best, SB. From smusnmrNOSPAM at yahoo.com Tue Jan 9 11:04:18 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Tue, 9 Jan 2007 17:04:18 +0100 Subject: code formatter? References: Message-ID: >tabnanny? not quite! "Hendrik van Rooyen" schrieb im Newsbeitrag news:mailman.2473.1168332187.32031.python-list at python.org... > "siggi" wrote: > >> Is there a simple code formatter that first removes all indentations and >> then refomats correctly? > > tabnanny ? > > - Hendrik > > > From gokkog at yahoo.com Mon Jan 1 08:53:44 2007 From: gokkog at yahoo.com (gokkog at yahoo.com) Date: 1 Jan 2007 05:53:44 -0800 Subject: Help with small program In-Reply-To: <45985255.1080105@redlinepy.com> References: <1166966360.384179.101400@48g2000cwx.googlegroups.com> <1166979265.284345.173840@48g2000cwx.googlegroups.com> <4v94fuF1avmp3U1@mid.individual.net> <4v95b8F1b5csnU1@mid.individual.net> <1167270942.421817.280490@n51g2000cwc.googlegroups.com> <45985255.1080105@redlinepy.com> Message-ID: <1167659624.767818.74940@42g2000cwt.googlegroups.com> "Paul Watson ??? " > Tim Roberts wrote: > > gokkog at yahoo.com wrote: > >> Interesting impl in Python! I am wondering what if the requirement is > >> to find the minimum number of coins which added to the "fin" sum... > > > > Given the set of coins in the original problem (100, 10, 5, 1, 0.5), the > > solution it provides will always be optimal. Even if we change this to > > American coinage (50, 25, 10, 5, 1), I believe it is still optimal. > > > > It is certainly possible to construct a set of denominations for which the > > algorithm occasionally chooses badly. For example, if you give it the set > > (40,35,10) and ask it to make change for 70, it will be suboptimal. > > Tim, > > Unless I am missing the point, the minimum number of coins from the set > available will be chosen. Surely this homework is past due by now. > > $ cat coins.py > #!/usr/bin/env python > import sys > > cointypes = (100, 10, 5, 1, 0.5) > > def coins(fin, cointypes): > needed = {} > for c in cointypes: > v, r = divmod(fin, c) > if v > 0: > needed[c] = int(v) > fin = r > return needed > > def doit(fin, cointypes = cointypes): > h = coins(fin, cointypes) > print '%.1f requires %d coins in hash ' % (fin, sum(h.values())), h > > if __name__ == '__main__': > doit(51) > doit(127) > doit(12.5) > doit(70, (40,35,10)) > > sys.exit(0) > > $ ./coins.py > 51.0 requires 6 coins in hash {1: 1, 10: 5} > 127.0 requires 6 coins in hash {1: 2, 10: 2, 100: 1, 5: 1} > 12.5 requires 4 coins in hash {0.5: 1, 1: 2, 10: 1} > 70.0 requires 4 coins in hash {40: 1, 10: 3} To be explicit, the min coins question could be resolved with "dynamic programming". So it is not a pure python question. No, this is not a homework question. Well, it is somewhat academic: http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=dynProg I wrote the following Python implementation akin to topcoder algorithm: #!/usr/bin/env python default_cointypes = (1, 3, 5) def mincoins(fin, cointypes = default_cointypes): needed = {} for c in cointypes: needed[c] = 0 min = {} for item in range(1, fin+1): min[item] = 2007 # suppose 2007 is the "infinity" min[0] = 0 for i in range(1, fin+1): for c in cointypes: if (c <= i and min[i-c] + 1 < min[i]): min[i] = min[i-c] + 1 needed[c] += 1 print fin, "==>", min[fin] print needed if __name__ == '__main__': mincoins(11) Probably there are things to be improved and there could be the pythonic way(s): Welcome your comments and ideas! Happy new year! Wenjie From pwatson at redlinepy.com Thu Jan 4 13:30:36 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Thu, 04 Jan 2007 12:30:36 -0600 Subject: what is this? In-Reply-To: <504v40F1ebv3sU1@mid.individual.net> References: <504v40F1ebv3sU1@mid.individual.net> Message-ID: <504veeF1dqqq4U1@mid.individual.net> Paul Watson wrote: > Eric Price wrote: >> Hello; >> I'm studying some code examples from the python cookbook site. I came >> across this: >> >> def colsplit(l, cols): >> rows = len(l) / cols >> if len(l) % cols: >> rows += 1 >> m = [] >> for i in range(rows): >> m.append(l[i::rows]) >> return m >> >> What I'd like to know is what is the double colon? What does it do? >> m.append(l[i::rows]) >> >> Thanks, >> Eric > > http://docs.python.org/tut/tut.html > http://docs.python.org/tut/node5.html#SECTION005140000000000000000 > http://docs.python.org/ref/slicings.html > > Probably most helpful to you is: > > http://developer.mozilla.org/es4/proposals/slice_syntax.html Sorry. Probably most helpful to you is: http://docs.python.org/lib/built-in-funcs.html slice( [start,] stop[, step]) Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: "a[start:stop:step]" or "a[start:stop, i]". From fd.calabrese at gmail.com Mon Jan 8 09:07:20 2007 From: fd.calabrese at gmail.com (cesco) Date: 8 Jan 2007 06:07:20 -0800 Subject: recursive function Message-ID: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> Hi, I have a dictionary of lists of tuples like in the following example: dict = {1: [(3, 4), (5, 8)], 2: [(5, 4), (21, 3), (19, 2)], 3: [(16, 1), (0, 2), (1, 2), (3, 4)]] In this case I have three lists inside the dict but this number is known only at runtime. I have to write a function that considers all the possible combinations of tuples belonging to the different lists and return a list of tuples of tuples for which the sum of the first element of the most inner tuple is equal to N. For example, assuming N = 24, in this case it should return: [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19, 2), (0, 2))] A simple list comprehension would be enough if only I knew the number of keys/lists beforehand but this is not the case. I guess I need a recursive function. Can anyone help? Thanks in advance Francesco From oliphant.travis at ieee.org Fri Jan 12 01:07:32 2007 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Thu, 11 Jan 2007 23:07:32 -0700 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168458486.538863.316130@k58g2000hse.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> Message-ID: oyekomova wrote: > Thanks for your help. I compared the following code in NumPy with the > csvread in Matlab for a very large csv file. Matlab read the file in > 577 seconds. On the other hand, this code below kept running for over 2 > hours. Can this program be made more efficient? FYI - The csv file was > a simple 6 column file with a header row and more than a million > records. > > > import csv > from numpy import array > import time > t1=time.clock() > file_to_read = file('somename.csv','r') > read_from = csv.reader(file_to_read) > read_from.next() > > datalist = [ map(float, row[:]) for row in read_from ] > > # now the real data > data = array(datalist, dtype = float) > > elapsed=time.clock()-t1 > print elapsed > If you use numpy.fromfile, you need to skip past the initial header row yourself. Something like this: fid = open('somename.csv') data = numpy.fromfile(fid, sep=',').reshape(-1,6) # for 6-column data. -Travis From andelys at riddergarn.dk Sun Jan 28 13:04:25 2007 From: andelys at riddergarn.dk (Andreas Lysdal) Date: Sun, 28 Jan 2007 19:04:25 +0100 Subject: Array delete Message-ID: <45BCE5A9.2000300@riddergarn.dk> Hey, Can someone plz make a function for that takes a array, and then search in it for duplicates, if it finds 2 or more items thats the same string then delete all except 1. Short: it deletes all duplicates in a array thanks -- _________ .__ __ ______________ / _____/ ___________|__|______/ |_ ___________ / | \______ \ \_____ \_/ ___\_ __ \ \____ \ __\/ __ \_ __ \/ | |_ / / / \ \___| | \/ | |_> > | \ ___/| | \/ ^ / / / /_______ /\___ >__| |__| __/|__| \___ >__| \____ | /____/ \/ \/ |__| \/ |__| From gagsl-py at yahoo.com.ar Mon Jan 15 03:06:25 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 05:06:25 -0300 Subject: Class list of a module In-Reply-To: References: Message-ID: <7.0.1.0.0.20070115045533.0388daa0@yahoo.com.ar> At Monday 15/1/2007 04:27, you wrote: >I want to get all classes of a module in a list. I wrote this code but I >wonder >if there's not a simpler solution > > >import inspect > >def getClassList(aModule): > return [getattr(aModule, attName) \ > for attName in aModule.__dict__ \ > if inspect.isclass(getattr(aModule, attName))] Looks rather simple to me... Anyway, you could avoid calling getattr twice, if you iterate over vars(aModule).itervalues() def getClassList(aModule): return [cls for cls in vars(aModule).itervalues() if inspect.isclass(cls)] (And note that there is no need for using \ at the line ends, because of the []) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rasmussen.bryan at gmail.com Wed Jan 31 04:40:11 2007 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Wed, 31 Jan 2007 10:40:11 +0100 Subject: BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job In-Reply-To: <45bff548$0$97249$892e7fe2@authen.yellow.readfreenews.net> References: <1170200864.492655.11850@s48g2000cws.googlegroups.com> <45bff548$0$97249$892e7fe2@authen.yellow.readfreenews.net> Message-ID: <3bb44c6e0701310140w4406879dof5616c66c0b233ae@mail.gmail.com> I think he meant that the body of Thermate was found among WTC physical samples, the conclusion is that Thermate was responsible for collapsing the WTC. The further conclusion is that Thermate is or was in possession of time travel technology, he has obviously recently gone back in time to attack the WTC and been killed. This would explain why trolling duties have been recently taken up by stj911 at rock.com on this list. Cheers, Bryan Rasmussen On 1/31/07, soutjhyDin wrote: > > wrote in message > news:1170200864.492655.11850 at s48g2000cws.googlegroups.com... > > http://portland.indymedia.org/en/2006/06/341238.shtml > > > > BYU Physics Prof Finds Thermate in WTC Physical Samples, Building > > Collapses an Inside Job > > author: Jacob Hamblin > > Based on chemical analysis of WTC structural steel residue, a Brigham > > Young University physics professor has identified the material as > > Thermate. Thermate is the controlled demolition explosive thermite > > plus sulfur. > > WRONG! you must make this stuff up as you go along. > > Thermate and thermite have nothing to do with "controlled demolition", > moron. > > What is the prime ingredient of both? Rust. > > The Iron Oxide(s), dummy. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From bj_666 at gmx.net Tue Jan 9 04:32:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 09 Jan 2007 10:32:23 +0100 Subject: How to write temporary data to file? References: Message-ID: In , Thomas Ploch wrote: > d = { > 'url1': { > 'emails': ['a', 'b', 'c',...], > 'matches': ['d', 'e', 'f',...] > }, > 'url2': {... > } > > This dictionary will get _very_ big, so I want to write it somehow to a > file after it has grown to a certain size. > > How would I achieve that? If you want easy access to single 'url' keys then `shelve` might be an alternative to pickling the whole thing as one big object. Ciao, Marc 'BlackJack' Rintsch From mail at microcorp.co.za Mon Jan 15 00:49:58 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 15 Jan 2007 07:49:58 +0200 Subject: Maths error References: Message-ID: <008c01c73868$fe309720$03000080@hendrik> "Dennis Lee Bieber" wrote: > On Sun, 14 Jan 2007 07:18:11 +0200, "Hendrik van Rooyen" > declaimed the following in comp.lang.python: > > > > > I recall an SF character known as "Slipstick Libby", > > who was supposed to be a Genius - but I forget > > the setting and the author. > > > Robert Heinlein. Appears a few of the Lazarus Long books. > > > It is something that has become quietly extinct, and > > we did not even notice. > > > And get collector prices -- > http://www.sphere.bc.ca/test/sruniverse.html Thanks Dennis - Fascinating site ! - Hendrik From nyenyec at gmail.com Mon Jan 8 23:17:46 2007 From: nyenyec at gmail.com (nyenyec) Date: 8 Jan 2007 20:17:46 -0800 Subject: re.sub and re.MULTILINE Message-ID: <1168316266.374186.271310@42g2000cwt.googlegroups.com> I feel like a complete idiot but I can't figure out why re.sub won't match multiline strings: This works: >>> re.search("^foo", "\nfoo", re.MULTILINE) <_sre.SRE_Match object at 0x6c448> This doesn't. No replacement: >>> re.sub("^foo", "bar", "\nfoo", re.MULTILINE) '\nfoo' Why? Thanks, nyenyec From jamesthiele.usenet at gmail.com Wed Jan 10 10:35:22 2007 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 10 Jan 2007 07:35:22 -0800 Subject: Seattle Python Interest Group Thursday at 7:00 PM Message-ID: Seattle Python Interest Group Meeting Thursday, Jan 11th at 7:00 PM Bar underneath the Third Place Books in Ravenna. http://www.ravennathirdplace.com/ NE 65th St & 20th Ave NE From mail at microcorp.co.za Sat Jan 13 01:20:38 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 13 Jan 2007 08:20:38 +0200 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <008101c736db$0d5bb480$03000080@hendrik> "Nick Maclaren" wrote: > > In article , > "Hendrik van Rooyen" writes: > |> > |> I would have thought that this sort of thing was a natural consequence > |> of rounding errors - if I round (or worse truncate) a binary, I can be off > |> by at most one, with an expectation of a half of a least significant digit, > |> while if I use hex digits, my expectation is around eight, and for decimal > |> around five... > |> > |> So it would seem natural that errors would propagate > |> faster on big base systems, AOTBE, but this may be > |> a naive view.. > > Yes, indeed, and that is precisely why the "we must use binary" camp won > out. The problem was that computers of the early 1970s were not quite > powerful enough to run real applications with simulated floating-point > arithmetic. I am one of the half-dozen people who did ANY actual tests > on real numerical code, but there may have been some work since! *grin* - I was around at that time, and some of the inappropriate habits almost forced by the lack of processing power still linger in my mind, like - "Don't use division if you can possibly avoid it, - its EXPENSIVE!" - it seems so silly nowadays. > > Nowadays, it would be easy, and it would make quite a good PhD. The > points to look at would be the base and the rounding rules (including > IEEE rounding versus probabilistic versus last bit forced[*]). We know > that the use or not of denormalised numbers and the exact details of > true rounding make essentially no difference. > > In a world ruled by reason rather than spin, this investigation > would have been done before claiming that decimal floating-point is an > adequate replacement for binary for numerical work, but we don't live > in such a world. No matter. Almost everyone in the area agrees that > decimal floating-point isn't MUCH worse than binary, from a numerical > point of view :-) > As an old slide rule user - I can agree with this - if you know the order of the answer, and maybe two points after the decimal, it will tell you if the bridge will fall down or not. Having an additional fifty decimal places of accuracy does not really add any real information in these cases. Its nice of course if its free, like it has almost become - but I think people get mesmerized by the numbers, without giving any thought to what they mean - which is probably why we often see threads complaining about the "error" in the fifteenth decimal place.. > > [*] Assuming signed magnitude, calculate the answer truncated towards > zero but keep track of whether it is exact. If not, force the last > bit to 1. An old, cheap approximation to rounding. > This is not so cheap - its good solid reasoning in my book - after all, "something" is a lot more than "nothing" and should not be thrown away... - Hendrik From dickinsm at gmail.com Tue Jan 16 10:25:08 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 16 Jan 2007 07:25:08 -0800 Subject: Conflicting needs for __init__ method In-Reply-To: References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <1168961105.446604.259840@l53g2000cwa.googlegroups.com> On Jan 15, 4:54 pm, Ben Finney wrote: > dicki... at gmail.com writes: > > Suppose you're writing a class "Rational" for rational numbers. The > > __init__ function of such a class has two quite different roles to > > play. > That should be your first clue to question whether you're actually > needing separate functions, rather than trying to force one function > to do many different things. Agreed. It was clear that I wanted two separate functions, but it seemed that the system was effectively forcing me to use just one; that is, I was working from the following two assumptions: (1) *Every* time a Rational is created, __init__ must eventually be called, and (2) The user of the class expects to call Rational() to create rationals. (1) argues for __init__ being small, simple and efficient, while (2) wants it to be large and user friendly (possibly dispatching to other methods to do most of the real work). But as has been pointed out, thanks to the existence of __new__, (1) is simply false. Time to be thankful for new-style classes. > > But __init__ also plays another role: it's going to be used by the > > other Rational arithmetic methods, like __add__ and __mul__, to > > return new Rational instances. > No, it won't; those methods won't "use" the __init__ method. They will > use a constructor, and __init__ is not a constructor (though it does > get *called by* the construction process). Sorry---I'm well aware that __init__ isn't a constructor; I wasn't being precise enough in my use of `used'. Mark From gagsl-py at yahoo.com.ar Sun Jan 7 15:17:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 12:17:19 -0800 Subject: Capturing stderr and stdout of a subprocess as a single stream In-Reply-To: <1168198435.629380.136080@42g2000cwt.googlegroups.com> References: <1168198435.629380.136080@42g2000cwt.googlegroups.com> Message-ID: <1168201039.867515.35300@38g2000cwa.googlegroups.com> On 7 ene, 16:33, "Fuzzyman" wrote: > Hello all, > > Before I ask the question a couple of notes : > > * This question is for implementing a script inside the Wing IDE. For > some reason using the subprocess module doesn't work so I need a > solution that doesn't use this module. > * The platform is Windows and I'm happy with a Windoze only solution. > :-) > > I would like to execute subprocesses asynchronously and capture stdout > / stderr as a single stream. > > If I use "os.popen3(executable)" it gives me separate pipes for stdout > and stderr, but reads from them are blocking. > > The output on stdout and stderr may be interleaved and I would like to > display them *as* they arrive. That means I can't just read from them > and output the results. > > The only solution I can think of is to read from both a character at a > time on two separate threads, putting the data into a queue. A separate > thread could pull characters off the queue and display them. (I don't > need to differentiate between stdout and stderr when I display.) > > Can anyone think of a better solution ? > > My current code works, but *doesn't* capture stderr : > > from threading import Thread > > pipe = os.popen(executable) > > def DisplayOutput(): > while True: > output = pipe.read(1) > if not output: > break > display(output) > > Thread(target=DisplayOutput).start() > > All the best, > > Fuzzymanhttp://www.voidspace.org.uk/python/articles.shtml Try using popen4 instead. But since you already have a thread, it may be better to use popen2 and two threads to read from stdout and stderr to avoid a potential deadlock; they can put read lines into a Queue, and DisplayOutput just get these lines in order. (See the warnings in the popen2 module documentation). -- Gabriel Genellina From Art at Arthurian.com Mon Jan 29 13:15:13 2007 From: Art at Arthurian.com (Frank Arthur) Date: Mon, 29 Jan 2007 13:15:13 -0500 Subject: Excellent Interview with Dennis D'Souza, full of laughs References: <1170083292.991070.79560@v33g2000cwv.googlegroups.com> <45be1d27$0$97248$892e7fe2@authen.yellow.readfreenews.net> <1170087497.071441.118560@s48g2000cws.googlegroups.com> Message-ID: <6Mqvh.5640$fC2.95@bignews4.bellsouth.net> Islamist bastard wrote in message news:1170087497.071441.118560 at s48g2000cws.googlegroups.com... wrote in message news:1170087497.071441.118560 at s48g2000cws.googlegroups.com... > FBI spook bastard that speaks french also > > On Jan 29, 8:13 am, "Hampton Din" wrote: >> stupid troll > > From gagsl-py at yahoo.com.ar Thu Jan 11 00:15:31 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 02:15:31 -0300 Subject: globals accros modules In-Reply-To: References: Message-ID: <7.0.1.0.0.20070111021138.0584ed78@yahoo.com.ar> At Thursday 11/1/2007 01:11, alf wrote: >How can I have global globals without cyclical import? You can't. Globals are module globals. You need to qualify *which* module `a` belongs to. >-------------------- >amodule.py: >def f(): > global a > print a >-------------------- >main.py: >import amodule >a=1 >amodule.f() Change a=1 to amodule.a=1 If you find yourself doing tricks with the module globals, think about redesigning your application. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From DustanGroups at gmail.com Sun Jan 7 16:52:42 2007 From: DustanGroups at gmail.com (Dustan) Date: 7 Jan 2007 13:52:42 -0800 Subject: strange for loop construct In-Reply-To: <12ptf5bl21f2teb@corp.supernews.com> References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> <12ptf5bl21f2teb@corp.supernews.com> Message-ID: <1168206762.164747.299470@42g2000cwt.googlegroups.com> Mark Elston wrote: > * Gabriel Genellina wrote (on 1/5/2007 12:49 PM): > > At Friday 5/1/2007 17:39, Sardaukary at gmail.com wrote: > > > >> wordfreq = [wordlist.count(p) for p in wordlist] > >> > >> I would expect > >> > >> for p in wordlist: > >> wordfreq.append(wordlist.count(p)) > >> > >> > >> I didn't know you could have an expression in the same line. > > > > That's known as a "list comprehension" and is roughly equivalent to your > > code. Section 5 of the tutorial covers them. > > http://docs.python.org/tut/node7.html > > > > > > If you have a Python installation you should be able to find the > "Whats New" section of the docs. List comprehensions are described > pretty well in the "What's new in Python 2.0?" section. This gives > some simple examples as well as the rationale behind them. Shouldn't that same page be found on the python website? http://www.python.org/doc/2.0/ Any clue as to why it isn't? > Mark From ask.me at mail.com Sun Jan 28 12:57:55 2007 From: ask.me at mail.com (Jammer) Date: Sun, 28 Jan 2007 12:57:55 -0500 Subject: string byte dump Message-ID: <9609c$45bce423$d8a87c2a$8428@NEXICOM.NET> Does anyone that knows python want to write me a byte dump for strings? :-) I am trying to modify a plugin (that someone else wrote) that uses interprocess communication. It works on strings without special characters but it fails on other stings like "Bj?rk". It calls decode('utf8') but I guess the strings are not utf8 so I need to find out what is being input. From smusnmrNOSPAM at yahoo.com Fri Jan 26 03:32:19 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Fri, 26 Jan 2007 09:32:19 +0100 Subject: Thank you, Martin, Wang and Colin References: Message-ID: Thanks for your answers, Martin, Wang and Colin! siggi "siggi" schrieb im Newsbeitrag news:epad97$fhqb$1 at zam602.zam.kfa-juelich.de... > Hi all, > > installing a package with 'setup.py' is easy. But how do I uninstall the > package, once I want to get rid of it again? > > Thanks, > > siggi > > > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 12:29:43 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 18:29:43 +0100 Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> Message-ID: <50fdc7F1fki7dU2@mid.individual.net> Nick Maclaren wrote: > I think that you should. Big words. > Where does it say that tuple's __str__ is the same as its > __repr__? Where does it say that a tuple's __str__ does not call its contents' __repr__? > The obvious interpretation of the documentation is that a sequence > type's __str__ would call __str__ on each sub-object, Where do you read that? BTW, that makes absolutely no sense to me. Also, lists of Strings would quickly get messed up when displaying them using __str__. Regards, Bj?rn -- BOFH excuse #359: YOU HAVE AN I/O ERROR -> Incompetent Operator error From mensanator at aol.com Mon Jan 29 15:56:02 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 29 Jan 2007 12:56:02 -0800 Subject: List Behavior when inserting new items In-Reply-To: <1170097845.805992.118870@h3g2000cwc.googlegroups.com> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> <526ut2F1n2q69U1@mid.uni-berlin.de> <1170097845.805992.118870@h3g2000cwc.googlegroups.com> Message-ID: <1170104162.555403.164270@m58g2000cwm.googlegroups.com> On Jan 29, 1:10 pm, "Drew" wrote: > > What is your actual usecase? > > > diezThe issue is that I don't know how long the list will eventually be. > Essentially I'm trying to use a 2D list to hold lines that I will > eventually print to the screen. Blank elements in the list will be > printed as spaces. I suppose every time I add an element, I could find > the difference between the size of the list and the desired index and > fill in the range between with " " values, however I just wanted to > see if there was a more natural way in the language. I would use DBR's suggestion to use a dictionary and only store actual values. In this example, I'm making a histogram that only ends up having results for 4,7,8,9,10 but I want the graph to show the zero occurrences as well, so I just create them on the fly when printing. print print 'tc factor of 2 distribution (* scale = 8)' print tchistkeys = tchist.keys() tchistkeys.sort() prev_key = 0 for i in tchistkeys: while prev_key0: s = s + '.' print s prev_key += 1 ## tc factor of 2 distribution (* scale = 8) ## ## 0 ( 0) ## 1 ( 0) ## 2 ( 0) ## 3 ( 0) ## 4 ( 1) . ## 5 ( 0) ## 6 ( 0) ## 7 (112) ************** ## 8 (219) ***************************. ## 9 ( 58) *******. ## 10 (110) *************. > > Thanks, > Drew From pavlovevidence at gmail.com Tue Jan 16 16:29:54 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 16 Jan 2007 13:29:54 -0800 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: References: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> <1168931486.610893.250040@38g2000cwa.googlegroups.com> Message-ID: <1168982994.057441.182780@38g2000cwa.googlegroups.com> Neil Cerutti wrote: > On 2007-01-16, Ron Adam wrote: > > I have to admit that part of why assert seems wrong to me is > > the meaning of the word implies something you shouldn't be able > > to ignore. While warnings seem like something that can be > > disregarded. > > Experienced C coders expect assert to behave like that. > > The only reason (I know of) to turn off error checking is to > optimize. However, removing tests won't usually make a big enough > speed difference to be worth the burthen of testing two different > versions of the same source code. I don't know about you, but I tend put very expensive checks in assert statements (or inside an if __debug__). Stuff like checking one-to-one synchronicity between two large trees, checking whether lists are sorted, etc. If all you're doing is asserting that x==0, yeah, who cares. If you're asserting issorted(list), I think you might want to shut that off in production code. > So to me the assert statement is either dubious syntax-sugar or > dangerous, depending on Python's command line arguments. If used as intended (i.e., to claim that a correct program should always meet the condition), it shouldn't be any more dangerous than omitting the test altogether. The danger comes from using it to check for things that aren't indicative of a bug in the program; for instance, to verify input. Then the program can crash and burn if optimization is turned on. Carl Banks From no-spam at no-spam-no-spam.invalid Sat Jan 6 07:03:34 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sat, 06 Jan 2007 13:03:34 +0100 Subject: howto overload with a NOP (empty statement) In-Reply-To: References: Message-ID: Stef Mientki wrote: > How should I overload / disable a method ? > In the example below I have defined the class "Power_Supply", derived > from baseclass "device". > The baseclass has a method "execute", which will be implemented in most > derived classes, but not in all. > Now apparently it's not allowed to overload a method with an empty > statement. > I could write a nonsense dummy statement, like "A= 3", but isn't there > another way ? > > thanks, Stef Mientki > > class device: > def execute (self): > print 'execute not yet implemented for', self.Name > > > class Power_Supply (device): > def execute (self): ; class device: def execute (self): raise NotImplementedError('virtual: should do this and that') This NotImplementedError virtual method scheme will also be detected by pychecker in order to warn correctly: that classes of actual instances have to override all open virtuals. Robert From medicalsounds at hotmail.com Wed Jan 24 23:26:00 2007 From: medicalsounds at hotmail.com (kevin) Date: 24 Jan 2007 20:26:00 -0800 Subject: Using Timing function problem..... Message-ID: <1169699160.119721.9750@v45g2000cwv.googlegroups.com> Hi... I'm having a few problems here... I want to input in my function different values and then time each one to see how long it took to run the function... so right now it doesn't like the "i" inside my function fibonacci(i) but if I put a constant it's fine.... any idea on how to approach this? thanks! Jonathan The Code: ======================================================= for i in (range(1,30)): mytime1 = timeit.Timer( 'fibonacci(i)', 'from prl1 import fibonacci' ) mytime2 = timeit.Timer( 'fibonacci(i)', 'from prl2 import fibonacci' ) fib1 = mytime1.timeit(1) fib2 = mytime2.timeit(1) ======================================================= The Error: ======================================================= Traceback (most recent call last): File "prl3.py", line 23, in ? fib1 = mytime1.timeit(1) File "/usr/lib64/python2.4/timeit.py", line 161, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner NameError: global name 'i' is not defined ======================================================= From zaz600 at gmail.com Sun Jan 28 23:58:39 2007 From: zaz600 at gmail.com (NoName) Date: 28 Jan 2007 20:58:39 -0800 Subject: Random passwords generation (Python vs Perl) =) Message-ID: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Perl: @char=("A".."Z","a".."z",0..9); do{print join("", at char[map{rand @char}(1..8)])}while(<>); !!generate passwords untill U press ctrl-z Python (from CookBook): from random import choice import string print ''.join([choice(string.letters+string.digits) for i in range(1,8)]) !!generate password once :( who can write this smaller or without 'import'? From sturlamolden at yahoo.no Wed Jan 10 13:14:39 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 Jan 2007 10:14:39 -0800 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> Message-ID: <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Nick Maclaren wrote: > as the ones that you have to play for threaded programs. Yes, I know > that it is a bit Irish for the best way to use a shared memory system > to be to not share memory, but that's how it is. Thank you for clearing that up. In any case, this means that Python can happily keep its GIL, as the CPU bound 'HPC' tasks for which the GIL does matter should be done using multiple processes (not threads) anyway. That leaves threads as a tool for programming certain i/o tasks and maintaining 'responsive' user interfaces, for which the GIL incidentally does not matter. I wonder if too much emphasis is put on thread programming these days. Threads may be nice for programming web servers and the like, but not for numerical computing. Reading books about thread programming, one can easily get the impression that it is 'the' way to parallelize numerical tasks on computers with multiple CPUs (or multiple CPU cores). But if threads are inherently designed and implemented to stay idle most of the time, that is obviously not the case. I like MPI. Although it is a huge API with lots of esoteric functions, I only need to know a handfull to cover my needs. Not to mention the fact that I can use MPI with Fortran, which is frowned upon by computer scientists but loved by scientists and engineers specialized in any other field. From gandalf at designaproduct.biz Mon Jan 22 11:54:29 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 22 Jan 2007 17:54:29 +0100 Subject: closing a "forever" Server Socket In-Reply-To: <1169482385.253887.249030@51g2000cwl.googlegroups.com> References: <1169123381.930403.24170@38g2000cwa.googlegroups.com> <1169143715.222186.30530@51g2000cwl.googlegroups.com> <1169482385.253887.249030@51g2000cwl.googlegroups.com> Message-ID: <45B4EC45.80704@designaproduct.biz> alessandro ?rta: > thanks > > infact the server_forever() method is only a serve() method inside an > infinite loop. > > many thanks again, > Here is a snipped that show a "software terminateable threading TCP socker server". The "server" object is a SocketServer instance, server_stopped is a threading.Event instance. You should also import the "select" module. srvfd = server.fileno() while not server_stopped.isSet(): ready = select.select([srvfd], [], [], 1) # Give one second for incoming connection so we can stop the server in seconds if srvfd in ready[0]: server.handle_request() else: pass # log('No incoming connection, retrying') From robin at reportlab.com Wed Jan 17 05:30:36 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 17 Jan 2007 10:30:36 +0000 Subject: 2.3-2.5 what improved? Message-ID: <45ADFACC.6080807@chamonix.reportlab.co.uk> A large cgi based web Python-2.3 application needs to be speed improved. experiments show the following under reasonable testing (these are 2 second reportlab pdf productions) 1) 2.3 --> 2.5 improvement small 1-2% 2) cgi --> fcgi improvement medium 10-12% I sort of remember claims being made about 2.5 being 10% faster than 2.4/2.3 etc etc. Can anyone say where the speedups were? Presumably we have a lot of old cruft that could be improved in some way eg moving loops into comprehensions, using iterator methods etc. Are those sort of things what we should look at? -- Robin Becker From robert.kern at gmail.com Fri Jan 26 13:46:40 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 26 Jan 2007 12:46:40 -0600 Subject: time series data and NumPy In-Reply-To: <51us3uF1mdcpsU1@mid.uni-berlin.de> References: <1169830757.220964.196540@m58g2000cwm.googlegroups.com> <51us3uF1mdcpsU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > I'm pretty sure you're out of luck here - even _if_ NumPy would handle > arbitrary data-types (AFAIK it doesn't, but then I'm not a total expert > there), it certainly won't be able to make its hi-performance functions > work on them. Yes, one can make numpy arrays with "object" as its type. One can even extend the C-level parts as well. For example, we have an experimental package in the scipy sandbox for uniform time series that uses mx.DateTime. http://www.scipy.org/TimeSeriesPackage > What you could do would be to convert the date-column into a timestamp, > which is a int/long, and use that. Would that help? This is frequently what I do. For dates, I like Modified Julian Day Numbers although I am sure that would horrify some people more knowledgeable than I. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From horpner at yahoo.com Tue Jan 9 09:43:00 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 9 Jan 2007 15:43:00 +0100 Subject: Determine an object is a subclass of another References: <1168353205.066357.39530@42g2000cwt.googlegroups.com> Message-ID: On 2007-01-09, abcd wrote: > How can tell if an object is a subclass of something else? > > Imagine... > > class Thing: > pass > > class Animal: > pass > > class Dog: > pass > > d = Dog() > > I want to find out that 'd' is a Dog, Animal and Thing. Such > as... > > d is a Dog > d is a Animal > d is a Thing isinstance(d, Dog) isinstance(d, Animal) isinstance(d, Thing) Note that in your example d is not an instance of anything but Dog. If you want a hierarchy, you must say so. Python doesn't even try to make educated guesses. class Thing: pass class Animal(Thing): pass class Dog(Animal): pass -- Neil Cerutti From vbgunz at gmail.com Wed Jan 3 14:30:36 2007 From: vbgunz at gmail.com (vbgunz) Date: 3 Jan 2007 11:30:36 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <459BCF07.6080302@v.loewis.de> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <1167543262.361311.123700@v33g2000cwv.googlegroups.com> <459BCF07.6080302@v.loewis.de> Message-ID: <1167852636.403469.69220@h40g2000cwb.googlegroups.com> > > I don't understand what all the fuss is about. Add a single page to the > > installer and on it, have 3 radio buttons. The choices could be "add to > > path (recommended)", "add to path with version", "do not add to path > > (not recommended)". > > Please submit a patch to sf.net/projects/python that does so. If I could I would. My only point jumping in here is this; adding python to the path has got to be more beneficially productive for everyone than not adding it at all. I don't even use Windows enough to complain about it and I thought I'll voice my agreement on it. From sjmachin at lexicon.net Tue Jan 2 03:06:01 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 02 Jan 2007 19:06:01 +1100 Subject: Writing more efficient code In-Reply-To: References: <1167700810.404307.148620@k21g2000cwa.googlegroups.com> Message-ID: <459A1269.6090500@lexicon.net> On 2/01/2007 2:23 PM, gonzlobo wrote: > Thanks to John, Paul & Jon for their responses. This list is great for > info. Hi gonzlobo, Please dont use private e-mail; post to the Python mailing-list / newsgroup, so that everybody can see what the eventual outcome is. Please also answer the question that I asked: in effect, what you have showed looks like a hex dump of a binary fiie -- are you saying that the data is actually transmitted over the serial bus in hex with spaces in between? > > Jon, > OCaml might be the best option, but my braincell is only good for 1 > language at a time. Hopefully python doesn't replace English. :^) > > Paul, > Thanks for the snippets. It looks pretty complicated, but worth > looking into. I'm all for reducing line of code (hopefully not for > readability). > > John M, > You're right, my original example contained non-sensical data (I made > it up for example's sake). It wasn't me who wrote that, but I agree. > > Here's a snippet of real data (it's a 10Mb/s serial bus, so there's > *alot* of data). > 0000007a 06 0321 80 00 34 d1 01 0b 3f f7 01 6b > 0000007b 26 0311 00 00 00 00 1a bd 00 00 00 00 > 0000007c 06 0321 80 00 a0 04 81 eb 20 05 81 1b > 0000007d 16 0614 00 00 00 00 00 00 00 00 00 00 > 0000007e 06 0321 80 00 20 00 01 07 a0 43 01 9b > 0000007f 06 0301 80 00 a0 b9 82 2b 3f d6 02 ab > 00000080 06 0321 80 00 bf d4 01 5b a3 f0 01 db > 00000081 06 0301 80 00 31 9c 02 0b bf d7 02 15 > 00000082 0f 0416 01 01 00 00 20 20 20 20 20 20 > 00000083 06 0301 80 00 bf ff 02 6b bf f3 82 eb > 00000084 0f 0416 02 01 00 00 20 20 20 20 20 20 > 00000085 06 0301 80 00 bf ed 82 1b a0 07 02 07 > 00000086 06 0321 00 00 00 00 01 af 00 00 00 00 > 00000087 26 0311 80 00 e0 ce 02 30 80 07 82 86 > 00000088 06 0301 80 00 a0 4a 02 9b 3f df 02 5b > 00000089 06 0301 80 00 80 00 02 ce 80 00 02 b3 > 0000008a 06 0301 80 00 00 00 02 5f e0 00 02 89 > 0000008b 16 0614 00 fe 31 00 00 00 00 00 00 00 > 0000008c 43 03a1 01 00 80 00 02 5d 80 0b 06 5d > 0000008d 06 0301 80 00 60 a1 92 c1 e0 a1 8a 21 > 0000008e 4f 0450 01 10 00 00 80 00 37 00 00 00 > > line = 0000007a 06 0321 80 00 34 d1 01 0b 3f f7 01 6b 0....v....1....v....2....v....3....v....4....v > Label 321 actually contains: > > time = line[:8] > PID = line[12:16] > d2 = line[17:19] > d3 = line[20:22] > d4 = line[23:25] > d5 = line[26:28] > d6 = line[29:31] > d7 = line[32:34] > d8 = line[35:37] > d9 = line[38:40] > d10 = line[41:43] > d11 = line[44:46] That's not Python 101, it's PYBOL :-) I haven't had to resort to the 0....v....1 etc caper for a very long time. Consider doing this: ints = [int(x, 16) for x in line.split()] time = ints[0] d = ints[1:] pid = d[1] # what is the undescribed field in ints[1]? > > d2 + d3 = Pitch Angle (* 0.01) I asked you before what you mean by "combine" ... now I'll ask what you mean by "d2 + d3" Do you mean this: pitch_angle = (d[3] * 256 + d[2]) * 0.01 ? > d4 + d5 = Roll Angle (* 0.05) > d6 + d8 = Magnetic Heading (* 0.05) What happened to d7? > d9 + d10 = Pressure Altitude (* 1.0) > d11 = various flags > > My code is python 101 (uses lots of nested if's), so using > dictionaries would be very helpful. Here's my Python 102 ... we can help you get to 201 level with a bit more disclosure from you on the specifics ... | >>> line = "0000007a 06 0321 80 00 34 d1 01 0b 3f f7 01 6b" | >>> ints = [int(x, 16) for x in line.split()] | >>> ints | [122, 6, 801, 128, 0, 52, 209, 1, 11, 63, 247, 1, 107] | >>> time = ints[0] | >>> time | 122 | >>> d = ints[1:] | >>> d | [6, 801, 128, 0, 52, 209, 1, 11, 63, 247, 1, 107] | >>> unknown = d[0] | >>> unknown | 6 | >>> pid = d[1] | >>> pid | 801 | >>> hex(pid) | '0x321' | >>> pitch_angle = (d[3] * 256 + d[2]) * 0.01 | >>> pitch_angle | 1.28 | >>> Call me crazy, but I'm highly suspicious of 0x8000 becoming a pitch angle of 1.28 degrees ;-) Especially since other lines in your sample with pid == 0x321 have (mostly) d2d3 == 0x8000 also, except for one with 0x000 -- I'm not an aeronautical engineer, but I would have expected other values for pitch angle. HTH, John From emin.shopper at gmail.com Wed Jan 10 17:46:54 2007 From: emin.shopper at gmail.com (Emin) Date: 10 Jan 2007 14:46:54 -0800 Subject: what is the idiom for copy lots of params into self? Message-ID: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> Dear Experts, When writing large classes, I sometimes find myself needing to copy a lot of parameters from the argument of __init__ into self. Instead of having twenty lines that all basically say something like self.x = x, I often use __dict__ via something like: class example: def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n): for name in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']: self.__dict__[name] = locals()[name] This saves a lot of code and makes it easier to see what is going on, but it seems like there should be a better idiom for this task. Any suggestions? Thanks, -Emin From bg_ie at yahoo.com Fri Jan 19 07:42:58 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: 19 Jan 2007 04:42:58 -0800 Subject: Why do I have to call del explicitly for com objects? Message-ID: <1169210578.544593.310100@v45g2000cwv.googlegroups.com> Hi, I'm creating objects in my python script belonging to a COM object which I dispatch using win32com.client.DispatchEx. Hence, dllhost.dll is the concerned process. The problem is that the objects destructor within the com object is not called if the object lives past a certain number of seconds. For example, this function will not call the destructor concerned with obj unless the sleep is commented out. def fnction: obj = comobj.createACertainObject() obj.doStuff() sleep(10) obj.doMoreStuff() #del obj It seems to me that the GC forgets about obj after a certain amount of time. I can force the destructor to be called using del obj at the end of my function, but why do I have to call this explicitly? Thanks for your help, Barry. From Thomas.Ploch at gmx.net Sat Jan 6 15:33:32 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sat, 06 Jan 2007 21:33:32 +0100 Subject: Dividing integers...Convert to float first? In-Reply-To: <1168050050.353467.185040@s80g2000cwa.googlegroups.com> References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> <459E8C77.3020603@rpath.com> <1168050050.353467.185040@s80g2000cwa.googlegroups.com> Message-ID: <45A0079C.8050600@gmx.net> Beliavsky schrieb: > If the C or Fortran committees tried to change > the meaning of int/int, they would be shot. Or hanged... > If you want to be confident that your code will run, unchanged, 10 > years from now on the hardware and OS that will then be common, Python > 2.x is not the language to use, unfortunately. From what I have read, > Python 3 will break things more fundamental than int/int. > Yes, but until then we have to use python 2.x. And I think that python 2.x will be around quite a while after python 3000 has been released if it breaks so much. Thomas From tinodb at gmail.com Wed Jan 3 14:35:29 2007 From: tinodb at gmail.com (TiNo) Date: Wed, 3 Jan 2007 14:35:29 -0500 Subject: bad marshal data in site.py in fresh 2.5 install win In-Reply-To: <459bd136$0$20860$9b622d9e@news.freenet.de> References: <4595B89C.9090208@v.loewis.de> <459bd136$0$20860$9b622d9e@news.freenet.de> Message-ID: <435b46e50701031135k4fc9e944tc4fe2c8daf29557c@mail.gmail.com> Removing aliases.pyc solved it. Thank you. 2007/1/3, "Martin v. L?wis" : > TiNo schrieb: > > File "F:\Python25\lib\encodings\__init__.py", line 32, in > > from encodings import aliases > > ValueError: bad marshal data > > > > also removed site.pyc, and run it again, but with the same result. > > It's likely rather aliases.pyc which is bad, so try removing that. > If in doubt, remove all .pyc files. > > If one of them is bad, it's either because the stick wasn't ejected > properly at some point, or it suffers from data loss. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From steven.bethard at gmail.com Wed Jan 3 16:16:28 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 03 Jan 2007 14:16:28 -0700 Subject: When argparse will be in the python standard installation In-Reply-To: <459C008D.5040404@v.loewis.de> References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> <459C008D.5040404@v.loewis.de> Message-ID: Martin v. L?wis wrote: > PengYu.UT at gmail.com schrieb: >> I feel argparse has some useful things that optparse doesn't have. But >> I can't find it argparse in python library reference. I'm wondering >> when it will be available in the python standard installation. > > On its own, never. Somebody has to contribute it to Python, and that > somebody has to be the author. As the author of argparse, I'm happy to contribute it, though I've been thinking that it would be more appropriate for the Python 3.0 line than the Python 2.X line. > However, it would be better if missing features where provided in > existing libraries, rather than introducing new libraries to replace > the existing ones (i.e. I would likely reject a patch to add yet another > argument parsing library - we already have getopt and optparse). That was my original intention, and argparse started out using the optparse code. But optparse is quite difficult to extend, and in the end, when I found that I had monkey-patched or rewritten just about everything in optparse, I decided to drop the optparse code entirely. If someone has an idea how to include argparse features into optparse, I'm certainly all for it. But I tried and failed to do this myself, so I don't know how to go about it. STeVe From hg at nospam.org Mon Jan 22 10:42:42 2007 From: hg at nospam.org (hg) Date: Mon, 22 Jan 2007 16:42:42 +0100 Subject: beep or sound playing under linux References: Message-ID: hg wrote: > Hi, > > Is there a way to do that ? > > Regards, > > hg PS: I'm actually under wpPython From felipe.lessa at gmail.com Wed Jan 10 09:11:59 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Wed, 10 Jan 2007 12:11:59 -0200 Subject: maximum number of threads In-Reply-To: References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: On 1/10/07, Laurent Pointal wrote: > This is a system configurable limit (up to a maximum). > > See ulimit man pages. > > test > > ulimit -a > > to see what are the current limits, and try with > > ulimit -u 2000 > > to modify the maximum number of user process (AFAIK each thread use a > process entry on Linux) I don't think it's only this. --- $ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited max nice (-e) 20 file size (blocks, -f) unlimited pending signals (-i) unlimited max locked memory (kbytes, -l) unlimited max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) unlimited max rt priority (-r) unlimited stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) unlimited virtual memory (kbytes, -v) unlimited file locks (-x) unlimited --- Well, unlimited number user processes. But: --- $ python test.py 50 100 150 200 250 300 350 Exception raised: can't start new thread Biggest number of threads: 382 --- The test.py script is attached. -- Felipe. -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 427 bytes Desc: not available URL: From jan.dries at dcube-resource.be Tue Jan 2 11:03:47 2007 From: jan.dries at dcube-resource.be (Jan Dries) Date: Tue, 02 Jan 2007 17:03:47 +0100 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> Message-ID: <459A8263.50908@dcube-resource.be> Ivan Voras wrote: > Ramdas wrote: >> Well, >> >> I need to add users from a web interface for a web server, which runs >> only Python. I need to add users, set quotas and in future even look at >> managing ip tables to limit bandwidth. >> >> I know os.system(), but this has to be done through a form entry >> through a web interface. >> >> Anyways thanks, do advise if there more pythonic solutions > > What you're looking for is actually a pretty complex thing. You *could* > in theory manage /etc/passwd (and its "shadow" file) - you can find > crypto primitives like MD5 and DES on the 'net, but note that you must > run your script under the 'root' account in order to write (and even > read!) the passwd database. The same goes for using os.system and the > built-in OS utility. Be aware of security implications if you're running > your web server under the root account. A solution that is both more pythonic and avoids the problems listed above would be to migrate user management from /etc/passwd to an LDAP (though pam_ldap). That's the approach I took in a similar situation. Sure, it adds the overhead of setting up and running an LDAP, but managing users and their quota through python_ldap is much cleaner and more flexible than doing so using os.system(), certainly from within a web application. That doesn't alter the fact though that security must be properly considered in any application that can add users. Regards, Jan From researchbase at gmail.com Sat Jan 20 14:12:28 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 21 Jan 2007 00:42:28 +0530 Subject: python packages and __name__ query. Message-ID: hello all, I had previously mentioned my doubt and confusion about having a main() to be an entry point in my python based software. I am still having a particular doubt. I use cx freze for creating a python executable. my software is essentially a package containing a few modules and one file where I created the main() function. if needed and suggested by experts I may as well put it in my __init__.py file of the package. coming back to the point. where do I put the following code if __name__ == "__main__": main() I have 5 modules in my package each doing a specific task. and a file that contains the main() function. the 5 modules and the exec.py file all are in the same package. if it is a wrong practice please correct me. so plese clear my doubt given the above situation. Krishnakant. From nriley at gmail.com Mon Jan 8 22:31:56 2007 From: nriley at gmail.com (nriley at gmail.com) Date: 8 Jan 2007 19:31:56 -0800 Subject: Evolving doctests for changing output format Message-ID: <1168313515.965895.86730@s80g2000cwa.googlegroups.com> Hi, I've got a number of doctests which rely on a certain output format, and since I wrote the tests I've changed the output format. Now, almost all the tests fail. What I'd like is if I could get doctest to take my tests, and substitute the obtained output for the provided output. Then, I could in this case just replace the doctest file with the generated file, or in general be able to run it through a file comparison tool so I could examine the differences. If it's not clear from the above, here's an example, assuming for the sake of simplicity that Python somehow changed its default output base between runs. INPUT: >> 10 + 10 20 OUTPUT: >> 10 + 10 0x14 Is it possible to use doctest in such a "run-only" mode, or script the above using its API? I read the documentation several times but just got further confused (sorry!). Thanks, --Nicholas From nick at craig-wood.com Sun Jan 21 15:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 21 Jan 2007 14:30:07 -0600 Subject: mmap caching References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > I've been trying to track down a memory leak (which I initially > attributed erroneously to numpy) and it turns out to be caused by a > memory mapped file. It seems that mmap caches without limit the chunks > it reads, as the memory usage grows to several hundreds MBs according > to the Windows task manager before it dies with a MemoryError. I'm > positive that these chunks are not referenced anywhere else; in fact if > I change the mmap object to a normal file, memory usage remains > constant. The documentation of mmap doesn't mention anything about > this. Can the caching strategy be modified at the user level ? I'm not familiar with mmap() on windows, but assuming it works the same way as unix... The point of mmap() is to map files into memory. It is completely up to the OS to bring pages into memory for you to read / write to, and completely up to the OS to get rid of them again. What you would expect is that the file is demand paged into memory as you access bits of it. These pages will remain in memory until the OS feels some memory pressure when the pages will be written out if dirty and then dropped. The OS will try to keep hold of pages as long as possible just in case you need them again. The pages dropped should be the least recently used pages. I wouldn't have expected a MemoryError though... Did you do mmap.flush() after writing? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From S.Mientki-nospam at mailbox.kun.nl Mon Jan 22 13:58:39 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 22 Jan 2007 19:58:39 +0100 Subject: (newbie) new version install (winXP) ? Message-ID: I've been started with Python on winXP, by installing the "Enthought" edition (about half a year old). This works like a charm. As a regular windows user, I'm not used to install partial packages. Now I find interesting application, that require higher versions of certain packages. Can I install only the higher version of a certain package ? Is that done by simply copying them ? Should I make a backup (of what) ? thanks, Stef Mientki From steve at REMOVEME.cybersource.com.au Wed Jan 31 01:39:56 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 31 Jan 2007 17:39:56 +1100 Subject: error messages containing unicode References: <1170122515.980168.150960@p10g2000cwp.googlegroups.com> <1170160464.576122.62230@h3g2000cwc.googlegroups.com> Message-ID: On Tue, 30 Jan 2007 04:34:24 -0800, Jim wrote: > Thank you for the reply. It happens that, as I understand it, none of > the options that you mentioned is a solution for my situation. > > On Jan 29, 9:48 pm, Steven D'Aprano > wrote: >> The easiest ways to fix that are: >> >> (1) subclass an exception that already knows about Unicode; > > But I often raise one of Python's built-in errors. And also, is it > really true that subclassing one of Python's built-ins give me > something that is unicode deficient? I assumed that I had missed > something (because that's happened so many times before :-) ). If the built-in isn't Unicode aware, subclassing it won't magically make it so :-) > For instance, I write a lot of CGI and I want to wrap everything in a > try .. except. > try: > main() > except Exception, err: > print "Terrible blunder: ",str(err) > so that the err can be one of my exceptions, or can be one that came > with Python. > (And, that I can see, err.args can be either the relevant > string or a tuple containing the relevant string and the documentation > is silent on whether in the built-in exceptions if err.args is a tuple > then the string is guaranteed to be first in the tuple.) Does it matter? Just print the tuple. >> (2) convert the file name to ASCII before you store it; or > > I need the non-ascii information, though, which is why I included it > in the error message. If you have the exception captured in "err", then you can grab it with err.where_i_put_the_unicode. >> (3) add a __str__ method to your exception that is Unicode aware. > > I have two difficulties with this: (1) as above I often raise Python's > built-in exceptions and for those __str__() is what it is, and Then don't use the built-in exception. If it won't do what you want it do do, use something else. > (2) this > goes against the meaning of __str__() that I find in the documentation > in ref/customization.html which says that the return value must be a > string object. I didn't mean return a unicode object :) You're absolutely correct. Your __str__ would need to return a string object, which means encoding the Unicode correctly to get a string object without raising an exception. e.g. something like this maybe (untested, not thought-through, probably won't work correctly, blah blah blah): def __str__(self): s = self.args.encode('ascii', 'replace') return "Unicode error converted to plain ASCII:\n" + s or whatever encoding scheme works for your application. [snip] >> >>> class MyBetterException(Exception):... def __init__(self, arg): >> ... self.args = arg.encode('ascii', 'replace') ... >> self.unicode_arg = arg # save the original in case > > This is illuminating. How do you know that for exceptions __init__() > should take one non-self argument? I missed finding this information. It can take whatever you want it to take: class MyStupidException(Exception): def __init__(self, dayofweek, breakfast="spam and baked beans", *everythingelse): self.day = dayofweek self.breakfast = breakfast self.args = everythingelse def __str__(self): s = "On %s I ate %s and then an error '%s' occurred." % \ (self.day.title(), self.breakfast, self.args) return s >>> raise MyStupidException('monday', 'cheese', 'bad things', 'happened', 2) Traceback (most recent call last): File "", line 1, in ? __main__.MyStupidException: On Monday I ate cheese and then an error '('bad things', 'happened', 2)' occurred. -- Steven D'Aprano From paddy3118 at netscape.net Tue Jan 9 02:17:00 2007 From: paddy3118 at netscape.net (Paddy) Date: 8 Jan 2007 23:17:00 -0800 Subject: Colons, indentation and reformatting. (2) In-Reply-To: <1168324924.666258.80030@42g2000cwt.googlegroups.com> References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> <1168324924.666258.80030@42g2000cwt.googlegroups.com> Message-ID: <1168327020.182467.125800@11g2000cwr.googlegroups.com> mensanator at aol.com wrote: > Paddy wrote: > > I was just perusing a Wikipedia entry on the "off side rule" at > > http://en.wikipedia.org/wiki/Off-side_rule . > > It says that the colon in Python is purely for readability, and cites > > our FAQ entry > > http://www.python.org/doc/faq/general.html#why-are-colons-required-fo... > > . > > However, near the top of the Alternatives section, it states that for C > > type, curly braces using languages: > > "An advantage of this is that program code can be automatically > > reformatted and neatly indented without fear of the block structure > > changing". > > > > Thinking about it a little, it seems that a colon followed by > > non-indented code that has just been pasted in could also be used by a > > Python-aware editor as a flag to re-indent the pasted code. > > How would you re-indent this? > > if x>0: print x If pasted as a line , after a line *ending with* a colon then indent it w.r.t. previous line. if pasting full lines after such a line then first pasted line cannot be indented more than this line; if it is then flag for re-indenting pasted block either equal too or less than this line. - Paddy. From attn.steven.kuo at gmail.com Wed Jan 31 00:34:54 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 30 Jan 2007 21:34:54 -0800 Subject: grp.struct_group bug ? In-Reply-To: <6uSvh.830201$5R2.500697@pd7urf3no> References: <6uSvh.830201$5R2.500697@pd7urf3no> Message-ID: <1170221694.174753.256060@p10g2000cwp.googlegroups.com> On Jan 30, 5:42 pm, spam wrote: > Is this a bug ? > > Running the following script with Python 2.3.5: > ................ > #!/usr/bin/python > > import grp > > # groups = grp.getgrall() > > agroup = grp.getgrnam('wheel') > print agroup > print type(agroup) > > print agroup.__contains__('john') > print agroup.__contains__('x') > ................ > > This is the output I get: > ................ > ('wheel', 'x', 199, ['marcel', 'john', 'ben']) > > False > True > ................ > > I expected __contains__ to tell me if a given user is part of a group, but > it seems that it's checking the password field ?? The tuple returned by getgrnam contains four fields: the group id (gr_gid), a list of group members (gr_grmem), the group name (gr_name), and the group password (gr_passwd). If you want to see if user 'john' is in the list of group members, use: if 'john' in agroup.gr_mem: print "Found john in group wheel" If you want to see if a password was set: if agroup.gr_passwd == "": print "No group password was set for group wheel" and so on. -- Hope this helps, Steven From fredrik at pythonware.com Mon Jan 8 11:09:32 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Jan 2007 17:09:32 +0100 Subject: Bizarre floating-point output In-Reply-To: References: <50f5snF1fb5uqU2@mid.individual.net> Message-ID: Nick Maclaren wrote: > The use of different precisions for the two cases is not, however, > and it is that I was and am referring to. that's by design, of course. maybe you should look "repr" up in the documentation ? From Eric_Dexter at msn.com Mon Jan 8 18:55:43 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 8 Jan 2007 15:55:43 -0800 Subject: tkinter with wck Message-ID: <1168300543.523210.308240@s34g2000cwa.googlegroups.com> I am playing around with this code but I am having trouble getting my x to be bigger it only seems to redraw when it becomes smaller than the original size up to full size (in ui_handle_repair). At other window sizes it just seems to center it.. I tried playing around with resize but never got that to do anything... any ideas (I might be willing to try other toolkits but the example looks very close to what I was after) http://www.dexrow.com from Tkinter import Tk from WCK import Widget #from WCK import Widget class CrossWidget(Widget): def ui_handle_repair(self, draw, x0, y0, x1, y1): black = self.ui_pen("black", 5) # draw a black cross draw.line((x0, y0, x1, y1), black) draw.line((x0, y1, x1, y0), black) def ui_handle_resize(self, width,height): black = self,ui_pen("black", 5) #draw.line((x0, y0, x1, y1), black) #draw.line((x0, y1, x1, y0), black) # center the text root = Tk() widget = CrossWidget(root) widget.pack() #(expand=1, fill="both") root.mainloop() From gagsl-py at yahoo.com.ar Wed Jan 31 21:49:27 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Jan 2007 23:49:27 -0300 Subject: ctypes error on exit of win32 application References: <1170281053.423976.85890@j27g2000cwj.googlegroups.com> Message-ID: En Wed, 31 Jan 2007 19:04:13 -0300, Rubic escribi?: > I'm attempting to use ctypes on a DLL with the following > signature: > > __declspec(dllimport) void process_record(char *, char *); > > An example .cpp file has code like this: > > int main(int argc, char **argv) > { > char record[100]; > char code[6]; > ... > process_record(code, record); > > When I invoke it under Python everything fine > while the interpreter is running: > > >>> from ctypes import * > >>> record = create_string_buffer("My Record") > >>> code = create_string_buffer('\000' * 6) > >>> cdll.grouper.process_recode(code, record) > >>> print code.value > '9999' > > But when the interpreter exits, either interactively > or from a script, the following Program Error popup > gets displayed: > > "python.exe has generated errors and will be closed > by Windows. You will need to restart the program." Maybe process_record expects some minimum buffer size? The cpp example uses char record[100], but you are allocating only a few bytes with the string "My Record" -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Mon Jan 15 14:16:43 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 15 Jan 2007 20:16:43 +0100 Subject: How can I integrate RPC with WSGI ??? In-Reply-To: <1168667728.272747.186210@a75g2000cwd.googlegroups.com> References: <1168667728.272747.186210@a75g2000cwd.googlegroups.com> Message-ID: <45abcc9f$0$310$426a74cc@news.free.fr> ?????? a ?crit : > How can I integrate RPC You mean xmlrpc or Soap ? > with WSGI ??? > is any methods for it?? > What's your problem exactly ? From maxerickson at gmail.com Thu Jan 11 10:01:24 2007 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 11 Jan 2007 15:01:24 +0000 (UTC) Subject: Universal Feed Parser - How do I keep attributes? References: <1168450723.340213.235690@o58g2000hsb.googlegroups.com> <7.0.1.0.0.20070111012646.03f5bdb8@yahoo.com.ar> Message-ID: Gabriel Genellina wrote: > At Wednesday 10/1/2007 14:38, snewman18 at gmail.com wrote: > >> >>> d = >> >>> feedparser.parse('http://weather.yahooapis.com/forecastrss?p= > 94089') >> >>> d.feed.yweather_location >>u'' > > You have to feed it the *contents* of the page, not its URL. > > The online documentation disagrees with you: http://feedparser.org/docs/introduction.html max From arkanes at gmail.com Thu Jan 4 10:48:09 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 4 Jan 2007 09:48:09 -0600 Subject: Packaging up a Python/Twisted Matrix application... In-Reply-To: References: Message-ID: <4866bea60701040748w7d67501atf4efaf27aa24c90@mail.gmail.com> On 1/4/07, Chaz Ginger wrote: > I have a rather large Python/Twisted Matrix application that will be run > on Windows, Linux and perhaps Macs. I was wondering if there are any > tools that can be used to create an installer that will bring in Python, > Twisted Matrix, my application libraries and anything else I need? > > I have tried using ezsetup with no luck (it seems not everything can be > installed with it). I was hoping to find something as nice (and > complete) as Perl's CPAN but can't seem to find anything. > > Does anyone have any recommendations? > > Peace, > Chaz. > -- For windows, py2exe is the de facto standard and it works fine with Twisted. There are similar scripts for the other platforms but I'm not familiar with them, I understand py2app is the standard for OS X. Note that OS X and pretty much every version of linux ship with Python, you might re-think your need to distribute a binary and instead just use a distutils install. From martin at v.loewis.de Thu Jan 4 20:15:37 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 05 Jan 2007 02:15:37 +0100 Subject: minidom utf-8 encoding In-Reply-To: <1167930869.836046.86840@42g2000cwt.googlegroups.com> References: <1167868380.481121.154880@42g2000cwt.googlegroups.com> <459cbbce$0$15834$9b622d9e@news.freenet.de> <1167927887.745869.18260@q40g2000cwq.googlegroups.com> <459D2DEF.2060508@v.loewis.de> <1167930869.836046.86840@42g2000cwt.googlegroups.com> Message-ID: <459da6ba$0$21574$9b622d9e@news.freenet.de> fscked schrieb: > # Create the base element > boxes = doc.createElement("boxes") > myfile = open('ClientsXMLUpdate.txt') > csvreader = csv.reader(myfile) > for row in csvreader: > mainbox = doc.createElement("box") > doc.appendChild(boxes) > r2 = csv.reader(myfile) > b = r2.next() > mainbox.setAttribute("city", b[10]) > > And it just works... You should not use it like that: it will only work if the CSV file is encoded in UTF-8. If the CSV file uses any other encoding, the resulting XML file will be ill-formed. What you should do instead is ... encoding_of_csv_file = some_value_that_the_producer_of_the_file_told_you ... ... mainbox.setAttribute("city", b[10].decode(encoding_of_csv_file)) Regards, Martin From shejo284 at gmail.com Wed Jan 3 16:16:38 2007 From: shejo284 at gmail.com (Sheldon) Date: 3 Jan 2007 13:16:38 -0800 Subject: Py_BuildValue or PyList_SetItem() Message-ID: <1167858998.103361.222490@i12g2000cwa.googlegroups.com> Hi, I have a function that creates python objects out of C arrays and returns them to Python. Below is a working example that I later want to expand to return 12 arrays back to Python. The problem is that when I print out the values in Python I get undesired reults. See below. Does anyone know what is going on here? The array values are good before the conversion. ************************************** int createPythonObject(void) { int i,j,k; PyObject *Rva=PyList_New(12); for (i = 0; i < 12; i++) { PyObject *op = PyFloat_FromDouble((double)va[i]); if (PyList_SetItem(Rva,i,op) !=0) { fprintf(stderr,"Error in creating python va object\n"); exit(EXIT_FAILURE); } Py_DECREF(op); op = 0; return Py_BuildValue("N",Rva); } Results in Python: , , , , , , , , , , , Any help is appreciated! /Sheldon From steve at REMOVE.THIS.cybersource.com.au Thu Jan 4 06:30:19 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 04 Jan 2007 22:30:19 +1100 Subject: question on creating class References: <1167895677.041759.230190@42g2000cwt.googlegroups.com> Message-ID: On Wed, 03 Jan 2007 23:27:57 -0800, wcc wrote: > Hello, > > How do I create a class using a variable as the class name? Try a "class factory". def create_class(classname): class Klass(object): def __init__(self): print "Creating object of %s..." % self.__class__.__name__ def method(self): print "This is a method." k = Klass k.__name__ = classname return k >>> K = create_class("TestClass") >>> obj = K() Creating object of TestClass... -- Steven. From gert.cuykens at gmail.com Sun Jan 21 17:16:37 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Sun, 21 Jan 2007 23:16:37 +0100 Subject: instancemethod Message-ID: import MySQLdb class Db: _db=-1 _cursor=-1 @classmethod def __init__(self,server,user,password,database): self._db=MySQLdb.connect(server , user , password , database) self._cursor=self._db.cursor() @classmethod def excecute(self,cmd): self._cursor.execute(cmd) self._db.commit() @classmethod def rowcount(self): return int(self._cursor.rowcount) @classmethod def fetchone(self): return self._cursor.fetchone() @classmethod def close(self): self._cursor.close() self._db.close() if __name__ == '__main__': gert=Db('localhost','root','******','gert') gert.excecute('select * from person') for x in range(0,gert.rowcount): print gert.fetchone() gert.close() gert at gert:~$ python ./Desktop/svn/db/Py/db.py Traceback (most recent call last): File "./Desktop/svn/db/Py/db.py", line 35, in for x in range(0,gert.rowcount): TypeError: range() integer end argument expected, got instancemethod. gert at gert:~$ Can anybody explain what i must do in order to get integer instead of a instance ? From mark.dufour at gmail.com Thu Jan 18 07:49:58 2007 From: mark.dufour at gmail.com (Mark Dufour) Date: Thu, 18 Jan 2007 13:49:58 +0100 Subject: Shed Skin Python-to-C++ Compiler Message-ID: <8180ef690701180449k71a7bd78k41bffc5f00973da2@mail.gmail.com> hi all, I have just released Shed Skin 0.0.18. besides many fixes and optimizations, this release should work on OSX and 64-bit systems (thanks john, larry, gustavo and denis!) more interestingly, I collected 25 'largish' programs (at a total of more than 6,000 lines!) that work fine with Shed Skin. these can be downloaded from the Shed Skin homepage: http://mark.dufour.googlepages.com please let me know if you try out the latest release, and encounter any problems or have any wishes. thanks, mark. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From paddy3118 at netscape.net Sun Jan 21 22:51:40 2007 From: paddy3118 at netscape.net (Paddy) Date: 21 Jan 2007 19:51:40 -0800 Subject: Is any python like linux shell? In-Reply-To: <1169400157.075307.31340@l53g2000cwa.googlegroups.com> References: <1169398326.510530.180860@51g2000cwl.googlegroups.com> <1169400157.075307.31340@l53g2000cwa.googlegroups.com> Message-ID: <1169437900.726137.237650@51g2000cwl.googlegroups.com> George Sakkis wrote: > Frank Potter wrote: > > > I learned some python in windows. > > And now I've turned to linux. > > I read a book and it teaches how to write shell script with bash, > > but I don't feel like the grammar of bash. > > Since I know about python, > > I want to get a linux shell which use python grammar. > > I searched by google and I found pysh, which is not maintained any > > more. > > There's another script named pyshell, which is not likely what I'm > > searching for. > > So, will somebody please tell me if there are any python like shells > > for linux? > > IPython is actually more than a simple shell. Give it a try: > http://ipython.scipy.org/. > > George Frank, IPython is great, but it is not a replacement for a shell like bash. If you have a Linux system then you still need to know the rudiments of bash - Paddy. From dummy at dummy.nl Thu Jan 11 05:14:51 2007 From: dummy at dummy.nl (Cecil Westerhof) Date: Thu, 11 Jan 2007 11:14:51 +0100 Subject: maximum number of threads References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: <45a60e1b$0$336$e4fe514c@news.xs4all.nl> Felipe Almeida Lessa wrote: > $ python test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > Exception raised: can't start new thread I tried your script on a PII 300 MHz and only 150 MB. I broke it of when it reached more as 1,25 million. ;-} From manstey at csu.edu.au Wed Jan 31 00:15:53 2007 From: manstey at csu.edu.au (manstey) Date: 30 Jan 2007 21:15:53 -0800 Subject: parent-child object design question In-Reply-To: References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> Message-ID: <1170220553.843010.258260@a34g2000cwb.googlegroups.com> Hi Ben, Could I also do something like the following? What does it mean to store the parent class as a private variable in the child class? class CacheProperty(object): def __init__(self, obj, parent, properties=None): self.__data = obj self._parent = parent if properties is None: properties = {} self._accumulate_properties(properties) def _accumulate_properties(self, properties): self.properties = [] for key, val in properties.iteritems(): setattr(self, key, val) self.properties.append(key) def __getattr__(self, name): return getattr(self.__data, name) def set(self, property): return self._parent.set(property) the set function allows us to call the parent set function within the child, which is what we need to do. From danb_83 at yahoo.com Sat Jan 13 23:58:30 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Jan 2007 20:58:30 -0800 Subject: indentation in python In-Reply-To: <1168742956.828457.287610@m58g2000cwm.googlegroups.com> References: <1168742956.828457.287610@m58g2000cwm.googlegroups.com> Message-ID: <1168750708.059882.107750@v45g2000cwv.googlegroups.com> On Jan 13, 8:49 pm, "lee" wrote: > Can anyone tell me the basics about indentation in python......how we > use it in loops and constructs..etc.... It's just like indentation in other languages, except that it's syntactically required. From robert.kern at gmail.com Wed Jan 24 14:47:41 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 24 Jan 2007 13:47:41 -0600 Subject: Simple Matrix class In-Reply-To: <1169664540.120687.211350@s48g2000cws.googlegroups.com> References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> <1169664540.120687.211350@s48g2000cws.googlegroups.com> Message-ID: Paul McGuire wrote: > And the purpose/motivation for "reimplementing it better" would be > what, exactly? So I can charge double for it? So you can have accurate results, and you get a good linear solver out of the process. The method you use is bad in terms of accuracy as well as efficiency. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From S.Mientki-nospam at mailbox.kun.nl Sun Jan 21 18:44:33 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 22 Jan 2007 00:44:33 +0100 Subject: Python Windows Editors In-Reply-To: References: Message-ID: <79e7c$45b3facb$d443bb3a$7251@news.speedlinq.nl> W. Watson wrote: > I downloaded python-2.5.msi and installed it. I believe its editor is > IDE. I understand there's a Win editor called pythonwin. I believe it's > in the download pywin32-210.win32-py2.5.exe, but I'm not sure if this > exe file has just the editor or all of Python. Comments? If not how do I > get the PythonWin editor by itself? > > BTW, one of the features I did not like of IDE is the limited file Print > command. It puts everything in 16pt type, and gives no choice over what > pages should be printed. Maybe there's an option? > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Two laws Newton and Einstein didn't discover: > 1. Time is money. > 2. Matter will be damaged in direct proportion > to its value. there a too many (good) IDE's for Python ;-) maybe we should give them a ranking, I tried 2 of them, and only was stable enough: PyScripter http://mmm-experts.com/Products.aspx?ProductID=4 cheers, Stef Mientki From exarkun at divmod.com Wed Jan 31 11:37:05 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Jan 2007 11:37:05 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> Message-ID: <20070131163705.25807.435432639.divmod.quotient.4683@ohm> On 31 Jan 2007 08:23:57 -0800, Frank Potter wrote: >I want to find a multithreaded downloading lib in python, >can someone recommend one for me, please? >Thanks~ There are no threads, but perhaps http://jcalderone.livejournal.com/24285.html would be interesting to you. Jean-Paul From paddy3118 at netscape.net Tue Jan 30 14:06:25 2007 From: paddy3118 at netscape.net (Paddy) Date: 30 Jan 2007 11:06:25 -0800 Subject: data design In-Reply-To: <45bf5763$0$22792$426a34cc@news.free.fr> References: <45bf5763$0$22792$426a34cc@news.free.fr> Message-ID: <1170183985.871094.155720@q2g2000cwa.googlegroups.com> On Jan 30, 2:34 pm, Imbaud Pierre wrote: > The applications I write are made of, lets say, algorithms and data. > I mean constant data, dicts, tables, etc: to keep algorithms simple, > describe what is peculiar, data dependent, as data rather than "case > statements". These could be called configuration data. > > The lazy way to do this: have modules that initialize bunches of > objects, attributes holding the data: the object is somehow the row of > the "table", attribute names being the column. This is the way I > proceeded up to now. > Data input this way are almost "configuration data", with 2 big > drawbacks: > - Only a python programmer can fix the file: this cant be called a > configuration file. > - Even for the author, these data aint easy to maintain. > > I feel pretty much ready to change this: > - make these data true text data, easier to read and fix. > - write the module that will make python objects out of these data: > the extra cost should yield ease of use. > > 2 questions arise: > - which kind of text data? > - csv: ok for simple attributes, not easy for lists or complex > data. > - xml: the form wont be easier to read than python code, > but an xml editor could be used, and a formal description > of what is expected can be used. > - how can I make the data-to-object transformation both easy, and able > to spot errors in text data? > > Last, but not least: is there a python lib implementing at least part > of this dream? Google for YAML and JSON formats too. http://www.yaml.org/ http://www.json.org/ -Paddy From george.sakkis at gmail.com Wed Jan 10 12:00:15 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 10 Jan 2007 09:00:15 -0800 Subject: An iterator with look-ahead References: Message-ID: <1168448415.599561.63420@77g2000hsv.googlegroups.com> Neil Cerutti wrote: > For use in a hand-coded parser I wrote the following simple > iterator with look-ahead. I haven't thought too deeply about what > peek ought to return when the iterator is exhausted. Suggestions > are respectfully requested. As it is, you can't be sure what a > peek() => None signifies until the next iteration unless you > don't expect None in your sequence. There is a different implementation in the Cookbook already: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 George From http Sun Jan 7 22:37:07 2007 From: http (Paul Rubin) Date: 07 Jan 2007 19:37:07 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> Message-ID: <7xhcv2195o.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > I'd be quite concerned about the design environment rather than the > immediate code... Probably need something ugly like... > > from mod1 import B as B1 > from mod2 import B as B2 > class A(B1, B2): > .... Interesting. I just tried that. mod1.py contains: class B: def foo(self): self.__x = 'mod1' mod2.py contains: class B: def bar(self): self.__x = 'mod2' And the test is: from mod1 import B as B1 from mod2 import B as B2 class A(B1, B2): pass a = A() a.foo() print a._B__x a.bar() print a._B__x Sure enough, mod2 messes up mod1's private variable. From gagsl-py at yahoo.com.ar Sun Jan 28 21:15:44 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Jan 2007 23:15:44 -0300 Subject: Trouble with max() and __cmp__() In-Reply-To: <1170019291.084041.150780@h3g2000cwc.googlegroups.com> References: <1170017167.165222.325800@a34g2000cwb.googlegroups.com> <1170019291.084041.150780@h3g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20070128231242.04743e10@yahoo.com.ar> At Sunday 28/1/2007 18:21, Thomas Nelson wrote: > wrote: > >Define method __gt__. > >This works, thanks. I was a little surprised though. is __cmp__ used >by any builtin functions? The problem is, rich comparison functions take precedence over __cmp__, so if your base class (list in this case) already defines rich comparison, you have to redefine them all. For simple cases, you can just redefine __cmp__ and reimplement all others __gt__, __lt__ etc using it. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gdamjan at gmail.com Sat Jan 27 10:17:11 2007 From: gdamjan at gmail.com (Damjan) Date: Sat, 27 Jan 2007 16:17:11 +0100 Subject: problems with pyzeroconf and linux References: Message-ID: <45bb6d30$0$49196$14726298@news.sunsite.dk> > I am trying to get pyzeroconf (http://sourceforge.net/projects/pyzeroconf) > running on my machine but having trouble... Running the Zeroconf.py file > seems to register the service, but is unable to find it. You should be running avahi.. it also comes python support. Here's an example that registers a CNAME that points to your hostname (that avahi itself publishes) #! /usr/bin/env python import avahi, dbus from encodings.idna import ToASCII # Got these from /usr/include/avahi-common/defs.h CLASS_IN = 0x01 TYPE_CNAME = 0x05 TTL = 60 def publish_cname(cname): bus = dbus.SystemBus() server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP) rdata = createRR(server.GetHostNameFqdn()) cname = encode_dns(cname) group.AddRecord(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), cname, CLASS_IN, TYPE_CNAME, TTL, rdata) group.Commit() def encode_dns(name): out = [] for part in name.split('.'): if len(part) == 0: continue out.append(ToASCII(part)) return '.'.join(out) def createRR(name): out = [] for part in name.split('.'): if len(part) == 0: continue out.append(chr(len(part))) out.append(ToASCII(part)) out.append('\0') return ''.join(out) if __name__ == '__main__': import time, sys, locale for each in sys.argv[1:]: name = unicode(each, locale.getpreferredencoding()) publish_cname(name) try: while 1: time.sleep(60) except KeyboardInterrupt: print "Exiting" -- damjan From http Mon Jan 8 02:49:21 2007 From: http (Paul Rubin) Date: 07 Jan 2007 23:49:21 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> <7xlkke19he.fsf@ruckus.brouhaha.com> Message-ID: <7xirfiyn3y.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Just how often do you inherit from two identically-named classes > both of which use identically-named private attributes? I have no idea how often if ever. I inherit from library classes all the time, without trying to examine what superclasses they use. If my subclass happens to have the same name as a superclass of some library class (say Tkinter) this could happen. Whether it ever DOES happen, I don't know, I could only find out by examining the implementation details of every library class I ever use, and I could only prevent it by remembering those details. That is an abstraction leak and is dangerous and unnecessary. The name mangling scheme is a crock. How often does anyone ever have a good reason for using it, except maybe in something like a debugger that can just as easily reach inside the actual class descriptors and get all the variables out? From nmm1 at cus.cam.ac.uk Sun Jan 14 06:54:52 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 14 Jan 2007 11:54:52 GMT Subject: Maths error References: Message-ID: In article , "Hendrik van Rooyen" writes: |> "Tim Peters" wrote: |> |> > What you will still see stated is variations on Kahan's telegraphic |> > "binary is better than any other radix for error analysis (but not very |> > much)", listed as one of two techincal advantages for binary fp in: |> > |> > http://www.cs.berkeley.edu/~wkahan/MktgMath.pdf Which I believe to be the final statement of the matter. It was a minority view 30 years ago, but I now know of little dissent. He has omitted that mid-point invariant as a third advantage of binary, but I agree that it could be phrased as "one or two extra mathematical invariants hold for binary (but not very important ones)". |> My basic error of thinking ( ? - more like gut feel ) was that the |> bigger bases somehow lose "more bits" at every round, |> forgetting that half a microvolt is still half a microvolt, whether |> it is rounded in binary, decimal, or hex... That is not an error, but only a mistake :-) Yes, you have hit the nail on the head. Some people claimed that some important algorithms did that, and that binary was consequently much better. If it were true, then the precision you would need would be pro rata to the case - so the decimal equivalent of 64-bit binary would need 160 bits. Experience failed to confirm their viewpoint, and the effect was seen in only artificial algorithms (sorry - I can no longer remember the examples and am reluctant to waste time trying to reinvent them). But it was ALSO found that the converse was not QUITE true, either, and the effective numerical precision is not FULLY independent of the base. So, at a wild guesstimate, 64-bit decimal will deliver a precision comparable to about 56-bit binary, and will cause significant numerical problems to a FEW applications. Hence people will have to convert to the much more expensive 128-bit decimal format for such work. Bloatware rules. All your bits are belong to us. Regards, Nick Maclaren. From mike.klaas at gmail.com Wed Jan 24 20:07:49 2007 From: mike.klaas at gmail.com (Klaas) Date: 24 Jan 2007 17:07:49 -0800 Subject: The reliability of python threads In-Reply-To: <7xveiwklt0.fsf@ruckus.brouhaha.com> References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169683654.672020.136820@q2g2000cwa.googlegroups.com> <7xveiwklt0.fsf@ruckus.brouhaha.com> Message-ID: <1169687269.885833.285410@a34g2000cwb.googlegroups.com> On Jan 24, 4:11 pm, Paul Rubin wrote: > "Klaas" writes: > > POSIX issues aside, Python's threading model should be less susceptible > > to memory-barrier problems that are possible in other languages (this > > is due to the GIL). > But the GIL is not part of Python's threading model; it's just a > particular implementation artifact. Programs that rely on it are > asking for trouble. CPython is more that "a particular implementation" of python, and the GIL is more than an "artifact". It is a central tenet of threaded python programming. I don't advocate relying on the GIL to manage shared data when threading, but 1) it is useful for the reasons I mention 2) the OP's question was almost certainly about an application written for and run on CPython. > > Double-checked locking, frinstance, is safe in python even though it > > isn't in java. > What's that? google.com -Mike From nyenyec at gmail.com Sun Jan 7 13:48:17 2007 From: nyenyec at gmail.com (nyenyec) Date: 7 Jan 2007 10:48:17 -0800 Subject: urlib.quote gives KeyError in Python 2.4.4 but workin 2.3.5 Message-ID: <1168195697.483795.71160@38g2000cwa.googlegroups.com> urllib.quote chokes on unicode in 2.4.4. >>> print sys.version 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] >>> urllib.quote(u"\xe9") Traceback (most recent call last): File "", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/urllib.py", line 1117, in quote res = map(safe_map.__getitem__, s) KeyError: u'\xe9' but it seems to work in Python 2.3.5 Python 2.3.5 (#1, Aug 19 2006, 21:31:42) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys, urllib >>> print sys.version 2.3.5 (#1, Aug 19 2006, 21:31:42) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] >>> urllib.quote(u'\xe9') '%E9' Is this a known bug? What's the workaround? Thanks, nyenyec From duncan.booth at invalid.invalid Mon Jan 8 05:33:54 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jan 2007 10:33:54 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: Laszlo Nagy wrote: > parallelpython at gmail.com wrote: >> Has anybody tried to run parallel python applications? >> It appears that if your application is computation-bound using 'thread' >> or 'threading' modules will not get you any speedup. That is because >> python interpreter uses GIL(Global Interpreter Lock) for internal >> bookkeeping. The later allows only one python byte-code instruction to >> be executed at a time even if you have a multiprocessor computer. >> To overcome this limitation, I've created ppsmp module: >> http://www.parallelpython.com >> It provides an easy way to run parallel python applications on smp >> computers. >> I would appreciate any comments/suggestions regarding it. >> > I always thought that if you use multiple processes (e.g. os.fork) then > Python can take advantage of multiple processors. I think the GIL locks > one processor only. The problem is that one interpreted can be run on > one processor only. Am I not right? Is your ppm module runs the same > interpreter on multiple processors? That would be very interesting, and > something new. > The GIL locks all processors, but just for one process. So, yes, if you spawn off multiple processes then Python will take advantage of this. For example we run Zope on a couple of dual processor dual core systems, so we use squid and pound to ensure that the requests are spread across 4 instances of Zope on each machine. That way we do get a fairly even cpu usage. For some applications it is much harder to split the tasks across separate processes rather than just separate threads, but there is a benefit once you've done it since you can then distribute the processing across cpus on separate machines. The 'parallel python' site seems very sparse on the details of how it is implemented but it looks like all it is doing is spawning some subprocesses and using some simple ipc to pass details of the calls and results. I can't tell from reading it what it is supposed to add over any of the other systems which do the same. Combined with the closed source 'no redistribution' license I can't really see anyone using it. From gigs at hi.t-com.hr Mon Jan 8 16:32:12 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Mon, 08 Jan 2007 22:32:12 +0100 Subject: Bitwise expression Message-ID: Can someone explain me bitwise expression? few examples for every expression will be nice x << y Left shift x >> y Right shift x & y Bitwise AND x | y Bitwise OR x ^ y Bitwise XOR (exclusive OR) ~x Bitwise negation thanks people From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 10:19:19 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 16:19:19 +0100 Subject: help: code formatter? References: Message-ID: <50f5nnF1fb5uqU1@mid.individual.net> siggi wrote: > as a newbie I have problems with formatting code of downloaded > programs, because IDLE's reformatting capabilities are limited . > Incorrect indentation, mixing of TAB with BLANKs or eol are often > very nasty to correct. > Is there a simple code formatter that first removes all > indentations and then refomats correctly? Why don't you just write one? :) Seriously: Try. BTW: Guessing to what amount of space TABs must be converted in mixed source can be non-trivial. Regards, Bj?rn -- BOFH excuse #289: Interference between the keyboard and the chair. From martin.witte at gmail.com Thu Jan 25 08:10:32 2007 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 25 Jan 2007 05:10:32 -0800 Subject: While loop with "or"? Please help! In-Reply-To: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> Message-ID: <1169730632.268861.321070@a75g2000cwd.googlegroups.com> On Jan 25, 11:26 am, wd.jons... at gmail.com wrote: > Hmm, my while loop with "or" doesn't seem to work as I want it to... > How do I tell the while loop to only accept "Y" or "y" or "N" or "n" > input from the str(raw_input)? > > Thank's in advance! > > Snippet of code: > > import os > > def buildfinder(): > os.system("CLS") > GameRoot = os.getenv("GAME_ROOT") + "\\" > > print "Do you want to use " + GameRoot + " as your source > directory?" > usr = str(raw_input('Y/N: ')) > return usr > > #Runs the buildfinder function > usrinp = buildfinder() > > def buildwhiler(): > > while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM > print "Enter Y or N!" > usr = str(raw_input('Y/N: ')) > else: > code continues also note that your naming of variables contains two different names for one variable... better usrinp = '' while usrinp.lower() not in ('y', 'n'): usrinp = raw_input('Y/N: ') # and not usr.... From usenet at marlowa.plus.com Thu Jan 18 02:57:26 2007 From: usenet at marlowa.plus.com (Andrew Marlow) Date: Thu, 18 Jan 2007 08:57:26 +0100 (CET) Subject: cannot import libxml2 python module on windoze using activePerl or Python IDLE References: <2%trh.15630$X72.3002@newsread3.news.pas.earthlink.net> Message-ID: On Wed, 17 Jan 2007 18:34:38 +0000, Dennis Lee Bieber wrote: >> I am not sure how python packages get installed on windoze. >> Please can anyone help? > > http://www.google.com/search?hl=en&q=libxml2+python&btnG=Google+Search > http://users.skynet.be/sbi/libxml-python/ Thanks very much! -Andrew Marlow -- There is an emerald here the size of a plover's egg! Don't top-post http://www.catb.org/~esr/jargon/html/T/top-post.html Plain text mails only, please http://www.expita.com/nomime.html From cjw at sympatico.ca Sun Jan 14 08:52:57 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 14 Jan 2007 08:52:57 -0500 Subject: Decorators inside of class and decorator parameters In-Reply-To: References: <1168728983.541526.202320@l53g2000cwa.googlegroups.com> Message-ID: Gabriel Genellina wrote: [snip] > As said in the beginning, there is no use for decorators as methods (perhaps > someone can find a use case?) Except, perhaps to indicate to the script reader that the decorator only applies within the class? Colin W. > If you move the example above inside the class, you get exactly the same > results. > > HTH, > > From jwaixs at gmail.com Thu Jan 11 17:20:14 2007 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Thu, 11 Jan 2007 22:20:14 +0000 Subject: Rational Numbers In-Reply-To: References: Message-ID: On 1/11/07, Facundo Batista wrote: > > Python does not have rational numbers. Ah, oke. Thank you, it seems I have enough information why they aren't included in the core. Question: Why do you say that it's a problem? Well... Perhaps I word it wrong. It's not really a problem and if I need rational numbers I'm smart enough to make an other algorithm that doesn't need a build-in function for rational numbers. I'm a mathematician (in learning, with a bad feeling for English) and don't trust irrational numbers in programming languages. It's, for example, in some cases it could be more efficient to compute an irrational number with a rational numbers then using an advanced algorithm of Euclides to compute the same. To give a small example: pi ~ 355/113 pi ~ 3.1415926 In my opinion the first one is better. But now I realise it's also the slowest of the two implemented in python. There are a (small) couple of other issues where rational numbers could be handy. That's because rational numbers are exact, irrational numbers (in python) aren't. But these issues are probably too mathematical to be used in a programming language like python. Regards, Noud Aldenhoven -- <:3 )~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at websiteburo.com Tue Jan 9 10:08:37 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Tue, 09 Jan 2007 16:08:37 +0100 Subject: Determine an object is a subclass of another In-Reply-To: <1168354891.334807.58940@s80g2000cwa.googlegroups.com> References: <1168353205.066357.39530@42g2000cwt.googlegroups.com> <1168353975.285391.212350@m30g2000cwm.googlegroups.com> <1168354891.334807.58940@s80g2000cwa.googlegroups.com> Message-ID: <45a3aff4$0$308$426a34cc@news.free.fr> abcd a ?crit : > yea i meant to have animal extend thing and dog extend animal....my > mistake. > > anyways, is there a way to check without having an instance of the > class? > > such as, > > isinstance(Dog, (Animal, Thing)) ?? > > issubclass(Dog, Animal) Note that such tests should only be used in a very few specific cases - certainly not to try&implement some kind of static typing... In Python, inheritance is mostly about implementation. From martin at v.loewis.de Thu Jan 4 11:40:15 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Jan 2007 17:40:15 +0100 Subject: minidom utf-8 encoding In-Reply-To: <1167927887.745869.18260@q40g2000cwq.googlegroups.com> References: <1167868380.481121.154880@42g2000cwt.googlegroups.com> <459cbbce$0$15834$9b622d9e@news.freenet.de> <1167927887.745869.18260@q40g2000cwq.googlegroups.com> Message-ID: <459D2DEF.2060508@v.loewis.de> fscked schrieb: > Well, let me clarify. If I just print it to the screen/console it works > fine, but when I do: > > out.write( doc.toprettyxml()) > > it just removes the character that would be the "?". > > I can post the code if anyone wants to see it, but it is fairly > straightforward. I find that hard to believe. There is no code in Python that does removal of characters, and I can't see any other reason why it gets removed. OTOH, what I do get when writing to a file is a UnicodeError, when it tries to convert the Unicode string that toxml gives to a byte string. So I recommend you pass encoding="utf-8" to the toprettyxml invocation also. Regards, Martin From gagsl-py at yahoo.com.ar Thu Jan 4 22:51:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 00:51:19 -0300 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> Message-ID: <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> At Thursday 4/1/2007 23:52, jeremito wrote: >I am writing a class that is intended to be subclassed. What is the >proper way to indicate that a sub class must override a method? If any subclass *must* override a method, raise NotImplementedError in the base class (apart from documenting how your class is supposed to be used). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From piet at cs.uu.nl Tue Jan 2 16:44:43 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 02 Jan 2007 22:44:43 +0100 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: >>>>> Sebastian 'lunar' Wiesner (SW) wrote: >SW> Linux seems to ignore SUID bit on scripts: The reason is that obeying SUID bits on scripts would be a security risk. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From hg at nospam.org Mon Jan 15 03:55:50 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 09:55:50 +0100 Subject: check if there is data in stdin without blocking References: <4PMqh.47441$X97.9536@newsfe18.lga> Message-ID: <9uNqh.48239$X97.14123@newsfe18.lga> Laurent Pointal wrote: > hg a ?crit : >> hg wrote: >> >>> Hi, >>> >>> Is there a way ? ... select ? >>> >>> >>> >>> hg >> PS: >> >> import sys >> import select >> >> l_r = select.select([sys.stdin],[],[],0) >> >> gives me: >> File "select.py", line 2, in ? >> import select >> File "/home/philippe/Desktop/select.py", line 4, in ? >> l_r = select.select([sys.stdin],[],[],0) >> TypeError: 'module' object is not callable >> >> > > Wont work under Windows: >>>> help(select.select) > ...... > *** IMPORTANT NOTICE *** > On Windows, only sockets are supported; on Unix, all file descriptors. > > > > If under Unix, maybe sys.stdin.fileno() is a valid descriptor for > select. Just test it. > > And if under Windows, you may take a look at > 22.1 msvcrt - Useful routines from the MS VC++ runtime > 22.1.2 Console I/O > kbhit( ) - Return true if a keypress is waiting to be read. Well I'm testing under Linux but need support under Windows ... is there any way to poll stdin somehow under both plateform ? thanks, hg From egbert.bouwman at hccnet.nl Wed Jan 24 13:04:39 2007 From: egbert.bouwman at hccnet.nl (egbert) Date: Wed, 24 Jan 2007 19:04:39 +0100 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <20070124180439.GA18506@hccnet.nl> On Wed, Jan 24, 2007 at 06:24:37AM +0000, Harry George wrote: > > Perl - excellent modules and bindings for just about everything ... > Java - a world of its own. They reinvent the wheel instead of ... > PHP - are we talking web scripts or serious programs? Are you ... > C - the portable assembler. Solid, trusted, tunable ... > C++ - objects tacked onto C; but that didn't work so invent ... > Python - it just works. Same scripts run on every platform ... What about C# ? e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From rrr at ronadam.com Thu Jan 18 17:12:17 2007 From: rrr at ronadam.com (Ron Adam) Date: Thu, 18 Jan 2007 16:12:17 -0600 Subject: Module name to filename and back? In-Reply-To: References: Message-ID: Ron Adam wrote: > Is there a function to find a filename from a dotted module (or package) name > without importing it? > > The imp function find_module() doesn't work with dotted file names. And it > looks like it may import the file as it raises an ImportError error exception if > it can't find the module. (Shouldn't it raise an IOError instead?) > > What I'm looking for is to be able to get the full module name when I have a > filename. And get the full filename when I have the module name. And do both > of these without importing the module. > > modulename <==> filename > filename <==> modulename I found a partial answer in trace.py. It has a fullmodname() function, but it doesn't do any validation so the name it returns is a guess. Starting with it I tried to make it a bit more complete, but it still needs work. Seems like there should be an easier way. Ron def importname(path): """ Get module or package name from a path name. Return None if path is invalid, or name is not a valid (reachable) package or module. """ path = os.path.normcase(path) if not os.path.exists(path): return if path.endswith(os.sep): path = path[:-1] longest = "" for dir in sys.path: dir = os.path.normcase(dir) + os.sep if path.startswith(dir): if len(dir) > len(longest): longest = dir if longest: base = path[len(longest):] else: # should check if in current dir? return # path not in search sys.path # This need a bit more work, it should also check # for valid parent packages too. if os.path.isdir(path): valid = False for ext in ['.py', '.pyc', '.pyo']: if os.path.isfile(os.path.join(path, '__init__' + ext)): valid = True break else: return base, ext = os.path.splitext(base) name = base.replace(os.sep, ".") if os.altsep: name = name.replace(os.altsep, ".") return name path = "c:\\python25\\lib\\xml\\sax\\handler.py" print importname(path) prints --> xml.sax.handler From bruno.desthuilliers at websiteburo.com Tue Jan 23 03:17:11 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Tue, 23 Jan 2007 09:17:11 +0100 Subject: How to use dynamic properties? <-- Noob In-Reply-To: References: Message-ID: <45b5c44c$0$22813$426a34cc@news.free.fr> Sean Schertell a ?crit : > person.name = 'Joe' > person.age = 20 > person.sex = 'm' > > info_I_need = name > > print person.info_I_need > > # How can I make it print 'Joe' ? > print getattr(person, "name") From malaclypse2 at gmail.com Tue Jan 9 08:34:44 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 9 Jan 2007 08:34:44 -0500 Subject: formattazione cifra con decimali In-Reply-To: <1168335821.473566.220190@38g2000cwa.googlegroups.com> References: <1168335548.504284.287150@q40g2000cwq.googlegroups.com> <1168335821.473566.220190@38g2000cwa.googlegroups.com> Message-ID: <16651e80701090534n49176d9dtaf9d929fda548173@mail.gmail.com> On 9 Jan 2007 01:43:41 -0800, Nuke wrote: > I need to visualize a number (or a string of that number) using the > decimal separator. > i have this number visualized: 50320,12 and i need that the > visualization of this number is: 50.320,13. > There is a function that directly convert the number (or the string) ? I'm not very familiar with locale-aware programming in Python, but this may get you started: >>> import locale >>> locale.setlocale(locale.LC_ALL, 'it') 'Italian_Italy.1252' >>> locale.format("%0.2f", 50320.12, grouping=True) '50.320,12' See http://docs.python.org/lib/module-locale.html for documentation on the locale module. -- Jerry From james-netnews at and.org Tue Jan 16 15:33:52 2007 From: james-netnews at and.org (James Antill) Date: Tue, 16 Jan 2007 14:33:52 -0600 Subject: Globbing files by their creation date References: <1168954453.954486.188680@m58g2000cwm.googlegroups.com> Message-ID: <6L2dnaxFNt0tqzDYnZ2dnUVZ_vPinZ2d@99main.com> On Tue, 16 Jan 2007 07:44:29 -0600, skip wrote: > Thomas> I've used glob.glob to create a list of all files whose name > Thomas> matches a substring, but I don't see how I can use it to > Thomas> identify files by their creation date. > > Sumthin' like: > > files = [f for f in glob.glob(globpat) > if os.path.getctime(f) > timethreshold] > > Define globpat and timethreshold accordingly. You sure you don't mean > modification time? If so, change getctime to getmtime. help(os.path.getctime) getctime(filename) Return the metadata change time of a file, reported by os.stat(). Note that _change_ time != creation time. Also for all files you probably want os.listdir() instead of glob. -- James Antill -- james at and.org http://www.and.org/and-httpd/ -- $2,000 security guarantee http://www.and.org/vstr/ From ptmcg at austin.rr._bogus_.com Sat Jan 13 11:04:17 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 13 Jan 2007 10:04:17 -0600 Subject: Boilerplate in rich comparison methods References: <1168674664.792869.213260@m58g2000cwm.googlegroups.com> Message-ID: <45a90301$0$7677$4c368faf@roadrunner.com> "George Sakkis" wrote in message news:1168674664.792869.213260 at m58g2000cwm.googlegroups.com... > Steven D'Aprano wrote: > >> I'm writing a class that implements rich comparisons, and I find myself >> writing a lot of very similar code. If the calculation is short and >> simple, I do something like this: >> >> >> class Parrot: >> def __eq__(self, other): >> return self.plumage() == other.plumage() >> If the comparison requires a lot of work, I'll do something like this: >> >> class Aardvark: >> def __le__(self, other): >> return lots_of_work(self, other) >> def __gt__(self, other): >> return not self <= other > Once upon a time I had written a metaclass to generate the boilerate, > filling in the gaps. It doesn't impose any constraints on which > comparisons you must implement, e.g you may implement __le__ and > __eq__, or __gt__ and __ne__, etc. Season to taste. > > http://rafb.net/p/mpvsIQ37.nln.html > > George > Just a side note on writing these comparison operators. I remember when learning Java that this was really the first time I spent so much time reading about testing-for-identity vs. testing-for-equality. The Java conventional practice at the time was to begin each test-for-equality method by testing to see if an object were being compared against itself, and if so, cut to the chase and return True (and the converse for an inequality comparison). The idea behind this was that there were ostensibly many times in code where an object was being compared against itself (not so much in an explicit "if x==x" but in implicit tests such as list searching and filtering), and this upfront test-for-identity, being very fast, could short-circuit an otherwise needless comparison. In Python, this would look like: class Parrot: def __eq__(self, other): return self is other or self.plumage() == other.plumage() def __ne__(self, other): return self is not other and self.plumage() != other.plumage() def __lt__(self, other): return self is not other and self.plumage() < other.plumage() def __gt__(self, other): return self is not other and self.plumage() > other.plumage() def __le__(self, other): return self is not other and self.plumage() <= other.plumage() def __ge__(self, other): return self is not other and self.plumage() >= other.plumage() and George's metaclass would have similar changes. On the other hand, I haven't seen this idiom in any Python code that I've read, and I wonder if this was just a coding fad of the time. Still, in cases such as Steven's Aardark class, it might be worth bypassing something that calls lots_of_work if you tested first to see if self is not other. -- Paul From fredrik at pythonware.com Fri Jan 5 07:30:08 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 Jan 2007 13:30:08 +0100 Subject: Change coords of a canvas.line item References: Message-ID: Matthias Vodel wrote: > I want to change the beginning/end-coordinates of a canvas.line item. > > Something like: > > self.myCanvas.itemconfigure(item_id, coords=(x1_new, y1_new, x2_new, y2_new)) self.myCanvas.coords(item_id, x1_new, y1_new, x2_new, y2_new) From bjourne at gmail.com Mon Jan 22 07:33:07 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 22 Jan 2007 13:33:07 +0100 Subject: Getting to an SSH account over a HTTP proxy Message-ID: <740c3aec0701220433j7620a090i2ad72f06150f079c@mail.gmail.com> I want to use Python to connect to a SSH account over a HTTP proxy to automate some operations. I thought paramiko would be able to do that, but it can not (it seems). Is there some other Python module that can do what I want? -- mvh Bj?rn From scott.daniels at acm.org Mon Jan 15 23:13:07 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 15 Jan 2007 20:13:07 -0800 Subject: Maths error In-Reply-To: References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <45ac45fa$1@nntp0.pdx.net> Tim Peters wrote: > ... Alas, most people wouldn't read that either <0.5 wink>. Oh the loss, you missed the chance for a <0.499997684987 wink>. --Scott David Daniels scott.daniels at acm.org From gherron at islandtraining.com Fri Jan 26 04:08:57 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 26 Jan 2007 01:08:57 -0800 Subject: how to remove c++ comments from a cpp file? In-Reply-To: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> Message-ID: <45B9C529.3000308@islandtraining.com> Frank Potter wrote: > I only want to remove the comments which begin with "//". > I did like this, but it doesn't work. > > r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) > f=file.open("mycpp.cpp","r") > f=unicode(f,"utf8") > r.sub(ur"",f) > > Will somebody show me the right way? > Thanks~~ > > If you expect help with a problem, it would be nice if you told us what the problem is. What error did you get? But even without that I see lots of errors: You must import re before you use it: import re Open a file with open((..) not file.open(...). Once you open the file you must *read* the contents and operate on that: data = f.read() Then you ought to close the file: f.close() Now you can do your sub on the string in data -- but note, THIS WON'T CHANGE data, but rather returns a new string which you must assign to something: new_data = r.sub(ur"", data) Then do something with the new string. Also I fear your regular expression is incorrect. Cheers, Gary Herron From tundra at tundraware.com Mon Jan 8 11:43:53 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 08 Jan 2007 10:43:53 -0600 Subject: Walking The Right Path In-Reply-To: References: <1168252155.427645.316470@38g2000cwa.googlegroups.com> Message-ID: <2v8a74-c45.ln1@eskimo.tundraware.com> Tim Daneliuk wrote: > Jakub Stolarski wrote: >> Tim Daneliuk napisal(a): >>> IOW, is there a way to return a symlink-based path which contains >>> the symlink pointer as is was *defined* not as it expands? >>> >> >> One way (but very ugly): >> print os.path._resolve_link('/bar') >> > > Yup, that does just what I want. By why, pray tell, do you consider it > ugly ...? > > Whoops - that doesn't do it either. If I have this: /foo -> /usr/bar /usr/bar -> /usr1/bar Then realpath or _resolve_link both return "/usr1/bar" when given "/foo" (when what I want is "/usr/bar"). There is obviously some underlying OS support to do this (in this case FreeBSD 4.x) because 'ls' shows things as I prefer them - i.e. Links are shown as assigned not how they actually resolve... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From chris at telestatic.net Wed Jan 3 00:32:33 2007 From: chris at telestatic.net (Chris Ashurst) Date: Wed, 03 Jan 2007 00:32:33 -0500 Subject: Synchronization methodology Message-ID: <459B3FF1.9030604@telestatic.net> Hi, I'm coming in from a despised Java background, and I'm having some trouble wrapping my head around sharing an object between multiple instances of a single class (in simpler terms, I would say imagine a simple chat server that has to share a list of connected users to each instance of a connected user). Usually, I would have a synchronized list instantiated inside each instance of a client class, which would do the trick, but since there's no synchronization in Python, I'm stuck staring at little tests involving a standalone non-threaded class instance that holds the list of users, and each connected user being passed this instance to be "synchronized". Now, whilst this *works*, it just doesn't feel right, and I would appreciate it if anyone has any more Pythonic expressions of this paradigm. Note that I have looked at Twisted (and I use it for other stuff), but I'm wanting to do things at a lower level (because I'm masochistic), and I feel like all the fun has been sucked out of programming by basically telling Twisted what I want and have it do it for me invisibly. Thanks! ~Chris From banaouas.medialog at wanadoo.fr Tue Jan 16 11:06:53 2007 From: banaouas.medialog at wanadoo.fr (m.banaouas) Date: Tue, 16 Jan 2007 17:06:53 +0100 Subject: urllib2 and HTTPBasicAuthHandler Message-ID: <45acf775$0$5070$ba4acef3@news.orange.fr> Hi all, I started to use urllib2 library and HTTPBasicAuthHandler class in order to authenticate with a http server (Zope in this case). I don't know why but it doesn't work, while authenticating with direct headers manipulation works fine! WinXP Sp2 Python 2.4.4 Thanks in advance for your help/comments # TestAuthHandler.py import base64, httplib, urllib2 httplib.HTTPConnection.debuglevel = 1 # def TestAuth(method): data = {'prot':'http','user':'admin','pass':'xxxxxx','host':'localhost','port':'8080','path':'manage','realm':'Zope'} url = '%(prot)s://%(host)s:%(port)s/%(path)s' % data req = urllib2.Request(url) # if (method == 'headers'): base64string = base64.encodestring('%s:%s' % (data['user'], data['pass']))[:-1] req.add_header("Authorization", "Basic %s" % base64string) elif (method == 'handler'): auth_url = '%(host)s:%(port)s/%(path)s' % data auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(data['realm'], auth_url, data['user'], data['pass']) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) # f = urllib2.urlopen(req) data = f.read() print data # TestAuth('headers') TestAuth('handler') ------------------------- output: ------------------------- Zope on http://localhost:8080 ... all right page ... Traceback (most recent call last): File "C:\Test\TestAuthHandler.py", line 25, in ? TestAuth('handler') File "C:\Test\TestAuthHandler.py", line 20, in TestAuth f = urllib2.urlopen(req) File "C:\Python\Lib\urllib2.py", line 130, in urlopen return _opener.open(url, data) File "C:\Python\Lib\urllib2.py", line 364, in open response = meth(req, response) File "C:\Python\Lib\urllib2.py", line 471, in http_response response = self.parent.error( File "C:\Python\Lib\urllib2.py", line 402, in error return self._call_chain(*args) File "C:\Python\Lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Python\Lib\urllib2.py", line 480, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized Process "Python" completed with Exit Code 1, at 16/01/2007 16:51:18. From shejo284 at gmail.com Wed Jan 3 17:15:58 2007 From: shejo284 at gmail.com (Sheldon) Date: 3 Jan 2007 14:15:58 -0800 Subject: Py_BuildValue or PyList_SetItem() In-Reply-To: References: <1167858998.103361.222490@i12g2000cwa.googlegroups.com> Message-ID: <1167862558.280976.58490@k21g2000cwa.googlegroups.com> Jack Diederich skrev: > On Wed, Jan 03, 2007 at 01:16:38PM -0800, Sheldon wrote: > > I have a function that creates python objects out of C arrays and > > returns them to Python. Below is a working example that I later want to > > expand to return 12 arrays back to Python. The problem is that when I > > print out the values in Python I get undesired reults. See below. Does > > anyone know what is going on here? > > The array values are good before the conversion. > > > > ************************************** > > int createPythonObject(void) { > > int i,j,k; > > PyObject *Rva=PyList_New(12); > > > > for (i = 0; i < 12; i++) { > > PyObject *op = PyFloat_FromDouble((double)va[i]); > > if (PyList_SetItem(Rva,i,op) !=0) { > > fprintf(stderr,"Error in creating python va object\n"); > > exit(EXIT_FAILURE); > > } > > Py_DECREF(op); > > op = 0; > > return Py_BuildValue("N",Rva); > > } > > > > Results in Python: > > > > , , > 0x80d885c>, , , > at 0x80d885c>, , , > > , , > 0x80d885c>, > > > > PyList_SetItem steals a reference to "op" so DECREF'ing it reduces > the refcount to zero. > > http://docs.python.org/api/listObjects.html > > -Jack Thanks Jack, It works now! /Sheldon From kernel1983 at gmail.com Tue Jan 16 22:18:19 2007 From: kernel1983 at gmail.com (kernel1983) Date: 16 Jan 2007 19:18:19 -0800 Subject: How can I write code using FP Message-ID: <1169003899.592015.300290@s34g2000cwa.googlegroups.com> In Function Program?Language can use like this: define a function: f = lambda x,y:x,y then we use f to define another function: f2 = f(1) the f2 should equal to: f2=lambda y:1,y we should be able call f2 with one parameter:f2(2) just return 1,2 but how can I implement the characteristic in Python??I think it could do like this but HOW-TO? thanks~~~ I'm a English beginner! I wish somebody understand my meaning From rrr at ronadam.com Tue Jan 16 00:27:40 2007 From: rrr at ronadam.com (Ron Adam) Date: Mon, 15 Jan 2007 23:27:40 -0600 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: References: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> Message-ID: Steven D'Aprano wrote: > On Mon, 15 Jan 2007 21:01:35 -0600, Ron Adam wrote: > > >> There have been times where I would like assert to be a little more assertive >> than it is. :-) >> >> ie.. not being able to turn them off with the -0/-00 switches, and having them >> generate a more verbose traceback. > > If you want something more verbose, you have it: > >>>> assert False, "verbose traceback" > Traceback (most recent call last): > File "", line 1, in ? > AssertionError: verbose traceback > > If you want something that won't be turned off by -O, you maybe need to > write your own: > > def assert_(condition, msg=""): > if not condition: > raise AssertionError(msg) > >> Maybe have an alternative 'warn' as an alternative debugging version that could >> be set to ignore, soft (print to log), and hard (raise an error). > > Check out the warnings module. Yes, I know it's there. It just seems like assert and warn() overlap currently. Assert doesn't quite fill warn()'s shoes, and warn() isn't as unassertive as assert when it's turned off. A warn statement could be completely ignored and not even cost a function call when it's turned off like assert does now. I don't think it does that currently. Isn't there always some overhead when using the warn() function. Or is there some magic there? An if-raise is just as fast as assert when evaluating as True, so there's no speed advantage there unless you have a large percentage of raises. But it does looks a lot nicer when you want a short positive test, verses a longer negative test with a raise stuck on it. But I think the developers would not consider this to be a big enough matter to be worth changing. So I'll continue to ignore warn(), and also continue to be un-assertive in my python code. Cheers, Ron From bj_666 at gmx.net Wed Jan 31 03:22:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 31 Jan 2007 09:22:36 +0100 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170088693.768440.26580@h3g2000cwc.googlegroups.com> <1170090408.495646.85720@v33g2000cwv.googlegroups.com> <1170108446.671609.169400@j27g2000cwj.googlegroups.com> <1170216508.396176.187780@v33g2000cwv.googlegroups.com> Message-ID: In <1170216508.396176.187780 at v33g2000cwv.googlegroups.com>, Hieu.D.Hoang at gmail.com wrote: > And can anyone explain why this is so? >>>> while 1: input(__import__('os').urandom(6).encode('base64')) > ... > BgiWdv// > > Traceback (most recent call last): > File "", line 1, in > File "", line 0 > > ^ > SyntaxError: unexpected EOF while parsing It's `input()` that expects a valid Python expression. An empty one doesn't work, it has to evaluate to something. In [2]: input() ------------------------------------------------------------ File "", line 0 ^ SyntaxError: unexpected EOF while parsing Ciao, Marc 'BlackJack' Rintsch From gandalf at designaproduct.biz Mon Jan 8 13:20:51 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 08 Jan 2007 19:20:51 +0100 Subject: xmlrpc and auth-digest In-Reply-To: References: Message-ID: <45A28B83.2040107@designaproduct.biz> Thomas Liesner ?rta: > Hi all, > > this may have been asked before, but as a newbie with xmlrpc i can't > find any suitable info on that. Sorry. > I am trying to write a simple xmlrpc-client in python and the server i > am trying to receive data from requires http auth digest. > The info on xmlrpclib covers auth basic thrugh url econding such as > "user:pass at server", but no auth digest. > > Is there any other library i could use for that or can i write some sort > of wrapper around this using a differnt library like urllib? > What I did before is that I added additional parameters of my published functions for the username and the password, and used xmlrpc over https. This is secure, but somewhat clumsy. You can also implement this by creating a persistent "session" when logging in, then use the session identifier for identification. If you are interested in XML/RPC over HTTPS: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496786 Regarding basic or digest http authentication, I believe it has nothing to do with the XML/RPC protocol itself. The basic and digest authentication is defined at the HTTP level. It is implemented with HTTP headers. Probably you can do this but not with the built-in xmlrpclib. If you look at xmlrpclib.py, then you will see that the ServerProxy class is an old style class that uses the xmlrpclib.Transport class for communication. The Transport class itself uses httplib to post the information. In theory, you can copy your own xmlrpclib and send/check extra http headers. In my opinion, it would be too much work, too much trouble and still not secure. Regards, Laszlo From khemkaamit at gmail.com Thu Jan 11 23:55:27 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Fri, 12 Jan 2007 10:25:27 +0530 Subject: Explanation about for loop In-Reply-To: <1168577299.485773.8160@q2g2000cwa.googlegroups.com> References: <1168577299.485773.8160@q2g2000cwa.googlegroups.com> Message-ID: <1360b7230701112055o1ce37e0eqafab1e8027f17900@mail.gmail.com> On 11 Jan 2007 20:48:19 -0800, raghu wrote: > can any one help me explaining for loop and its execution and its > syntax with a simple example. Well Guido did that: http://docs.python.org/tut/node6.html#SECTION006200000000000000000 -- ---- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. From Laurent.LAFFONT-ST at adixen.fr Mon Jan 15 02:27:30 2007 From: Laurent.LAFFONT-ST at adixen.fr (Laurent.LAFFONT-ST at adixen.fr) Date: Mon, 15 Jan 2007 08:27:30 +0100 Subject: Class list of a module Message-ID: Hi, I want to get all classes of a module in a list. I wrote this code but I wonder if there's not a simpler solution import inspect def getClassList(aModule): return [getattr(aModule, attName) \ for attName in aModule.__dict__ \ if inspect.isclass(getattr(aModule, attName))] Regards, Laurent Laffont From Bulkan at gmail.com Wed Jan 17 22:35:20 2007 From: Bulkan at gmail.com (placid) Date: 17 Jan 2007 19:35:20 -0800 Subject: Projects anyone? In-Reply-To: References: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> Message-ID: <1169091320.842359.181010@m58g2000cwm.googlegroups.com> Thanks for all the help. I have some projects that i will look into and see if i can contribute anything Cheers Ben Finney wrote: > "placid" writes: > > > I'm looking for anyone who is working on a project at the moment that > > needs help (volunteer). > > The Volunteer Opportunities page is a bit thin at the moment. I'd hope > people can respond to this thread and update that page with other > projects that need help. > > > > The Coding Project Ideas page is more specifically focussed on getting > programmer help. > > > > Browse the Cheese Shop for packages that you'd like to improve, and > offer your help to the project maintainer. > > > > -- > \ "A 'No' uttered from deepest conviction is better and greater | > `\ than a 'Yes' merely uttered to please, or what is worse, to | > _o__) avoid trouble." -- Mahatma Gandhi | > Ben Finney From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 12:50:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 18:50:39 +0100 Subject: Why less emphasis on private data? In-Reply-To: <45a0b4e3$0$19089$4fafbaef@reader4.news.tin.it> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <45a0b4e3$0$19089$4fafbaef@reader4.news.tin.it> Message-ID: <45a12cb0$0$300$426a74cc@news.free.fr> Andrea Griffini a ?crit : > Paul Rubin wrote: > > > Yes I've had plenty of > >> pointer related bugs in C programs that don't happen in GC'd >> languages, so GC in that sense saves my ass all the time. > > > My experience is different, I never suffered a lot for > leaking or dangling pointers in C++ programs; and on > the opposite I didn't expect that fighting with object > leaking in complex python applications was that difficult > (I've heard of zope applications that just gave up and > resorted to the "reboot every now and then" solution). > Zope is a special case here, since it relies on an object database... From steven.bethard at gmail.com Sun Jan 21 23:20:26 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 21 Jan 2007 21:20:26 -0700 Subject: pyparsing Combine without merging sub-expressions In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Sat, 20 Jan 2007 13:49:52 -0700, Steven Bethard > declaimed the following in comp.lang.python: > >> Within a larger pyparsing grammar, I have something that looks like:: >> >> wsj/00/wsj_0003.mrg >> >> When parsing this, I'd like to keep around both the full string, and the >> AAA_NNNN substring of it, so I'd like something like:: >> >> >>> foo.parseString('wsj/00/wsj_0003.mrg') >> (['wsj/00/wsj_0003.mrg', 'wsj_0003'], {}) >> > If working file name/paths, why not use the functions in os.path? Two reasons. First, as I mentioned, this is within a larger pyparsing grammar so it's not as easy to switch back and forth between the two. Second, I do want to do some data validation (e.g. the name of the file needs to be in a particular format) so I either need to post-process the os.path approach or just do it in pyparsing. >> But that then allows whitespace between the pieces of the path, which >> there shouldn't be:: >> > If you didn't have whitespace coming in, there shouldn't be any > going out. If you do, you likely have malformed data and probably should > detect it earlier... Well that's the intention of using pyparsing here. With a proper grammar, pyparsing can detect the malformed data for me and throw an error. STeVe From pythonnews at nospam.jmbc.fr Wed Jan 17 04:26:57 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Wed, 17 Jan 2007 10:26:57 +0100 Subject: smtplib question In-Reply-To: References: Message-ID: <45adebf2$0$21147$7a628cd7@news.club-internet.fr> >> The mail server in my organization is MS exchange. Obviously I can >> email to >> any email address from my MS outlook. >> >> What's the easiest way to fix the program? > > You will need to get smtplib to authenticate when connecting to the > exchange server. Use the login function and the same username/pw > that you use to login to Outlook. > > server.login(user, password) > > Note: Your exchange administrator may have disabled this function. ( > Your Outlook will almost certainly be using MAPI not SMTP to talk to > the server). > It's very often a pain to talk with Exchange. If Outlook Web Access is enabled, you can use urlib/urllib2 to send your emails exactly like you'd do it by a web browser. It's sometimes easier than using the regular smtplib capabilities. Regards, jm From lrahuel.notgood at voila.fr Fri Jan 26 10:23:39 2007 From: lrahuel.notgood at voila.fr (Laurent Rahuel) Date: Fri, 26 Jan 2007 16:23:39 +0100 Subject: how to remove c++ comments from a cpp file? References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> <1169805244.879280.235660@v45g2000cwv.googlegroups.com> Message-ID: <45ba1cfe$0$5084$ba4acef3@news.orange.fr> And using the codecs module [CODE] import codecs f = codecs.open("show_btchina.user.js","r","utf-8") modf = codecs.open("modified.js","w","utf-8") for line in f: idx = line.find(u"//") if idx==0: continue elif idx>0: line = line[:idx]+u'\n' modf.write(line) modf.close() f.close() [/CODE] Gabriel Genellina wrote: > At Friday 26/1/2007 06:54, Frank Potter wrote: > >>[CODE] >>import re >> >>f=open("show_btchina.user.js","r").read() >>f=unicode(f,"utf8") >> >>r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) >>f_new=r.sub(ur"",f) >> >>open("modified.js","w").write(f_new.encode("utf8")) >>[/CODE] >> >>And, the problem is, it seems that only the last comment is removed. >>How can I remove all of the comments, please? > > Note that it's not as easy as simply deleting from // to end of line, > because those characters might be inside a string literal. But if you > can afford the risk, this is a simple way without re: > > f = open("show_btchina.user.js","r") > modf = open("modified.js","w") > for line in f: > uline=unicode(line,"utf8") > idx = uline.find("//") > if idx==0: > continue > elif idx>0: > uline = uline[:idx]+'\n' > modf.write(uline.encode("utf8")) > modf.close() > f.close() > > From simon at brunningonline.net Fri Jan 12 15:07:04 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 12 Jan 2007 20:07:04 +0000 Subject: Rational Numbers In-Reply-To: <45A7E8E9.8060105@gmx.net> References: <8c7f10c60701121134q35bf7c27h7c4b5cf1dcfe44ca@mail.gmail.com> <45A7E8E9.8060105@gmx.net> Message-ID: <8c7f10c60701121207s31ec614dnea5d4b543deb2d12@mail.gmail.com> On 1/12/07, Thomas Ploch wrote: > Do not forget: > > - Time > - Personal Data (like birthdays, age) The datetime module has perfectly good classes for holding date and time values, and age sounds like an integer to me. -- Cheers, Simon B simon at brunningonline.net From nszabolcs at gmail.com Mon Jan 29 10:24:25 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 07:24:25 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170083692.114100.109100@k78g2000cwa.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <7x3b5uwfa2.fsf@ruckus.brouhaha.com> <1170082883.393745.244840@a34g2000cwb.googlegroups.com> <7x64apzx8f.fsf@ruckus.brouhaha.com> <1170083692.114100.109100@k78g2000cwa.googlegroups.com> Message-ID: <1170084265.620244.276140@v45g2000cwv.googlegroups.com> > Is os.urandom cryptographically strong on all platforms? http://docs.python.org/lib/os-miscfunc.html "The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation." From beej at beej.us Tue Jan 30 02:29:30 2007 From: beej at beej.us (Beej) Date: 29 Jan 2007 23:29:30 -0800 Subject: Data structure and algorithms In-Reply-To: References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> <1170095416.261460.157660@a34g2000cwb.googlegroups.com> <1170107403.836795.211280@k78g2000cwa.googlegroups.com> Message-ID: <1170142170.842412.147370@a34g2000cwb.googlegroups.com> On Jan 29, 10:15 pm, Dennis Lee Bieber wrote: > The instructor learned his lesson: no more assignments > done in "any language I can understand" Without naming names, there was a person at my university who gained a certain amount of notoriety by implementing a file system for OS class in Bourne Shell. That prof also changed the rule the very next semester. :-) -Beej From paul at boddie.org.uk Fri Jan 12 05:21:28 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Jan 2007 02:21:28 -0800 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> Message-ID: <1168597288.571937.176430@s34g2000cwa.googlegroups.com> parallelpyt... at gmail.com wrote: > > The main difference between MPI python solutions and ppsmp is that with > MPI you have to organize both computations > {MPI_Comm_rank(MPI_COMM_WORLD, &id); if id==1 then ... else ....} and > data distribution (MPI_Send / MPI_Recv) by yourself. While with ppsmp > you just submit a function with arguments to the execution server and > retrieve the results later. Couldn't you just provide similar conveniences on top of MPI? Searching for "Python MPI" yields a lot of existing work (as does "Python PVM"), so perhaps someone has already done so. Also, what about various grid toolkits? [...] > Overall ppsmp is still work in progress and there are other interesting > features which I would like to implement. This is the main reason why I > do not open the source of ppsmp - to have better control of its future > development, as advised here: http://en.wikipedia.org/wiki/Freeware :-) Despite various probable reactions from people who will claim that they're comfortable with binary-only products from a single vendor, I think more people would be inclined to look at your software if you did distribute the source code, even if they then disregarded what you've done. My own experience with regard to releasing software is that even with an open source licence, most people are likely to ignore your projects than to suddenly jump on board and take control, and even if your project somehow struck a chord and attracted a lot of interested developers, would it really be such a bad thing? Many developers have different experiences and insights which can only make your project better, anyway. Related to your work, I've released a parallel execution solution called parallel/pprocess [1] under the LGPL and haven't really heard about anyone really doing anything with it, let alone forking it and showing my original efforts in a bad light. Perhaps most of the downloaders believe me to be barking up the wrong tree (or just barking) with the approach I've taken, but I think the best thing is to abandon any fears of not doing things the best possible way and just be open to improvements and suggestions. Paul [1] http://www.python.org/pypi/parallel From jgodoy at gmail.com Sat Jan 13 13:42:16 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 13 Jan 2007 16:42:16 -0200 Subject: template engine References: Message-ID: <8764ba7oqf.fsf@gmail.com> piotr writes: (...) > for user was not empty call function again with argument "user/name" > then engine should replace specific placeholders with results of my > callback function > obviously this is just example syntax, I hope you catch the idea > > that would be nice if engine could work with non HTML documents. > > thanks in advance for your help, and sorry for my English :) Take a look at Kid (http://www.kid-templating.org/) and Genshi (http://genshi.edgewall.org/). -- Jorge Godoy From hg at nospam.org Tue Jan 9 04:24:16 2007 From: hg at nospam.org (hg) Date: Tue, 09 Jan 2007 10:24:16 +0100 Subject: Xah's Edu Corner: Introduction to 3D Graphics Programing References: <1166836083.084101.25870@73g2000cwn.googlegroups.com> <458d7899$0$8725$ed2619ec@ptn-nntp-reader02.plus.net> <1167208399.089326.213540@a3g2000cwd.googlegroups.com> Message-ID: Xah Lee wrote: > I don't know OpenGL, but i think it is a low-level crap, and have done > the industry huge irreparable damage the same way unix has. So you _are_ psychic ! is the end of the world be in 2007 ? From parallelpython at gmail.com Sat Jan 6 18:52:35 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 6 Jan 2007 15:52:35 -0800 Subject: Parallel Python Message-ID: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Has anybody tried to run parallel python applications? It appears that if your application is computation-bound using 'thread' or 'threading' modules will not get you any speedup. That is because python interpreter uses GIL(Global Interpreter Lock) for internal bookkeeping. The later allows only one python byte-code instruction to be executed at a time even if you have a multiprocessor computer. To overcome this limitation, I've created ppsmp module: http://www.parallelpython.com It provides an easy way to run parallel python applications on smp computers. I would appreciate any comments/suggestions regarding it. Thank you! From gagsl-py at yahoo.com.ar Mon Jan 8 12:35:03 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 14:35:03 -0300 Subject: multi-threaded webcam with SimpleAsyncHTTPServer.py In-Reply-To: <6.2.3.4.2.20070107203507.02e77240@pop-server.san.rr.com> References: <6.2.3.4.2.20070107203507.02e77240@pop-server.san.rr.com> Message-ID: <7.0.1.0.0.20070108143117.05c36860@yahoo.com.ar> At Monday 8/1/2007 02:44, Ray Schumacher wrote: >Question, though: how can I unblock asyncore.loop(), or at least be >able to interrupt it? To kill this server I need to hit CNTRL-C and >then attempt to GET an image from Firefox, Python then throws >KetboardInterrupt. Why do you want to do that? (The usual reason is to have a place to do *other* things besides serving the channels). Anyway, you can use the count argument to asyncore.loop(). Ctrl-C gets recognised after the timeout expires; the default is 30sec so you may have to wait up to 30 sec before the KeyboardInterrupt. You can lower it. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bdesth.quelquechose at free.quelquepart.fr Fri Jan 5 10:17:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Jan 2007 16:17:19 +0100 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167974907.497878.61070@i15g2000cwa.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1167974907.497878.61070@i15g2000cwa.googlegroups.com> Message-ID: <459e65ce$0$311$426a74cc@news.free.fr> Carl Banks a ?crit : > jeremito wrote: > >>I am writing a class that is intended to be subclassed. What is the >>proper way to indicate that a sub class must override a method? > > > You can't (easily). > > If your subclass doesn't override a method, then you'll get a big fat > AttributeError when someone tries to call it. "override" implies that the method is already defined in one of the parent classes. So there's no reason for an AttributeError here... (snip) From harlinseritt at yahoo.com Tue Jan 16 15:03:33 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 16 Jan 2007 12:03:33 -0800 Subject: How to determine what exceptions a method might raise? In-Reply-To: <12qq98ijkn5mld8@corp.supernews.com> References: <12qq98ijkn5mld8@corp.supernews.com> Message-ID: <1168977813.362594.160470@m58g2000cwm.googlegroups.com> Hi Ed, Generally checking the sources give a very good clue as to what exceptions the interpreter can raise. Look around _builtins_ for this. Harlin Seritt Ed Jensen wrote: > I'm really enjoying using the Python interactive interpreter to learn > more about the language. It's fantastic you can get method help right > in there as well. It saves a lot of time. > > With that in mind, is there an easy way in the interactive interpreter > to determine which exceptions a method might raise? For example, it > would be handy if there was something I could do in the interactive > interpreter to make it tell me what exceptions the file method might > raise (such as IOError). > > Thanks in advance. From rridge at csclub.uwaterloo.ca Mon Jan 22 16:56:01 2007 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 22 Jan 2007 13:56:01 -0800 Subject: mmap caching References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <1169415139.515834.233700@a75g2000cwd.googlegroups.com> <4X7th.13145$pQ3.5671@newsread4.news.pas.earthlink.net> <1169496803.518305.275750@s34g2000cwa.googlegroups.com> Message-ID: <1169502961.034481.264830@11g2000cwr.googlegroups.com> George Sakkis wrote: > It's around 400MB. On Windows you may not be able to map a file of this size into memory because of virtual address space fragmentation. A Win32 process has only 2G of virtual address space, and DLLs tend to get scattered through out that address space. > As I said, I cannot reproduce the MemoryError > locally since I have 1GB physical space but IIRC the user who reported > it had less. Virtual address space fragmentation isn't affected by the amount of physical memory in your system. A system with 64MB of RAM might be able to map a 400MB file while system with 3G of RAM might not be able to map it because of how DLLs got loaded in to the process. > Actually I am less concerned about whether a MemoryError > is raised or not in this case and more about the fact that even if > there's no exception, the program may suffer from severe thrashing due > to constant swapping. Well, that's what you're asking for when you use mmap. The same mechanism that creates virtual memory using a swap file is used to create a virtual memory mapping of your file. When you read from the mmap file pages from the file a swapped into memory and stay in memory until they need to be swapped out to make room for something else. If you don't want this behaviour, don't use mmap. Ross Ridge From fredrik at pythonware.com Wed Jan 3 09:43:13 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 Jan 2007 15:43:13 +0100 Subject: a question on python dict References: <1166684796.856425.235810@i12g2000cwa.googlegroups.com> Message-ID: Tim Peters wrote: > Taking my response out of context to begin with doesn't really change that > I answered the question he asked ;-) welcome to comp.lang.python. From jstroud at mbi.ucla.edu Mon Jan 29 07:01:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 29 Jan 2007 04:01:37 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170046719.708692.243290@s48g2000cws.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: NoName wrote: > Perl: > @char=("A".."Z","a".."z",0..9); > do{print join("", at char[map{rand @char}(1..8)])}while(<>); > > !!generate passwords untill U press ctrl-z > > > > Python (from CookBook): > > from random import choice > import string > print ''.join([choice(string.letters+string.digits) for i in > range(1,8)]) > > !!generate password once :( Make a loop. > who can write this smaller I won't write it for you, but I'll tell you how: Write a function for the whole loop and the password generator and from then on it will be a one-liner (as a function call). > or without 'import'? Yes, make sure you do the import inside the function. If you follow my advice, you will be able to get as many passwords as you want with one line (and no spaces, even!): generate_passwords() It also reads much clearer than the perl version, don't you think? By the way, you can also make a script. Call it "genpass", then at the command prompt, it will be far less than one line: % genpass Or, if you are using DOS/Windows: C:> genpass A lot of systems don't have a standard command called "g", so then you can turn it into *ONE LETTER*!!! That beats the pants off perl! % g Or, of course, for DOS: C:> g Good luck! James From skip at pobox.com Mon Jan 29 12:27:31 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Jan 2007 11:27:31 -0600 Subject: Can I undecorate a function? In-Reply-To: References: Message-ID: <17854.11907.74767.252147@montanaro.dyndns.org> Matt> In some instances I want to access just the function f, though, Matt> and catch the values before they've been decorated. def f(x): return x * x @as_string def fs(x): return f(x) Call the one you want. Skip From danielkleinad at gmail.com Thu Jan 11 09:39:39 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Thu, 11 Jan 2007 09:39:39 -0500 Subject: __init__ vs __new__ Message-ID: <7sicq25i3qbddgst5fdjhu5i7d1p8j5qg1@4ax.com> I've have a program that is using both of the methods below (in different classes of course) for initializing the class. The example below shows a class with the 2 methods with one commented out. class JsubroutineParameters(list): "Represents a list of arguments for external subroutine calls." # We only need to override methods which add objects to the list. def __init__(self, alist = []): for objekt in alist: _validateParameter(objekt) self.extend(alist) #def __new__(cls, alist = []): # for objekt in alist: _validateParameter(objekt) # return list.__new__(cls, alist) I don't really notice any behavioral difference. Is there in fact any difference in using one over the other? Performance? Side effects? ??? I am using Python version 2.5. Thanks, Daniel Klein From bruno.desthuilliers at websiteburo.com Wed Jan 17 11:41:59 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Wed, 17 Jan 2007 17:41:59 +0100 Subject: 2.3-2.5 what improved? In-Reply-To: <1169040587.340057.11040@m58g2000cwm.googlegroups.com> References: <1169040587.340057.11040@m58g2000cwm.googlegroups.com> Message-ID: <45ae51d7$0$4263$426a74cc@news.free.fr> billie a ?crit : > robert wrote > >> Robin Becker wrote: >>> A large cgi based web Python-2.3 application needs to be speed improved. >>> experiments show the following under reasonable testing (these are 2 >>> second reportlab pdf productions) >>> >>> 1) 2.3 --> 2.5 improvement small 1-2% >>> 2) cgi --> fcgi improvement medium 10-12% >>> >>> I sort of remember claims being made about 2.5 being 10% faster than >>> 2.4/2.3 etc etc. Can anyone say where the speedups were? Presumably we >>> have a lot of old cruft that could be improved in some way eg moving >>> loops into comprehensions, using iterator methods etc. Are those sort of >>> things what we should look at? >> Python 2.5 became quite fat. For bare CGI the Python load/init >> time eats all improvements. Smaller scripts even loose lot of speed. >> I still like Python 2.3 for many other reasons for many >> applications - especially for CGI's, on Windows, for deployable >> apps, GUI's etc. because the fat coming with Python 2.4 is not >> balanced by necessary goods - mostly just fancy things. > > What do you mean? Fat of libraries or fat itself? > I tought that 2.5 was faster than precedent versions! :-\ > It is. But it takes a bit more time to launch the interpreter. Which is barely noticiable in most cases, but can be start to be a problem with CGI. From horpner at yahoo.com Tue Jan 2 13:42:32 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 2 Jan 2007 19:42:32 +0100 Subject: DOS, UNIX and tabs References: <1167243140.687557.93320@f1g2000cwa.googlegroups.com> Message-ID: On 2007-01-02, Peter Decker wrote: > On 1/1/07, Tom Plunket wrote: >> Maybe I'm also weird, but I use a variable-pitch font when >> programming in Python. So a "tab equals some number of >> spaces" really isn't useful to me. My setup is, "tab equals >> this much space". > > A year ago I would have thought you were weird, but after > reading a post by Ed Leafe, one of the creators of Dabo about > using proportional fonts for readability, I thought I'd try it > out, thinking that it was pretty wacky. Turns out that after a > very brief adjustment period, I liked it! I've been using > proportional fonts ever since, and have found only one > drawback: code that is indented with spaces looks butt-ugly. > I'm glad I switched to tabs for my code. I first came accross it in Stroustrup's _The C++ Programming Language_. I liked the look and the idea immediately, but my editor of choice (by historical accident) Vim, doesn't yet support it. -- Neil Cerutti I've had a wonderful evening, but this wasn't it. --Groucho Marx From bignose+hates-spam at benfinney.id.au Tue Jan 16 17:11:21 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Jan 2007 09:11:21 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <740c3aec0701160837r33340866w5ddef3e09a0de537@mail.gmail.com> Message-ID: <873b6abp12.fsf@benfinney.id.au> "BJ?rn Lindqvist" writes: > import rational > rational.rational(45) > rational.rational(45.0) > rational.rational([45, 45.5]) > > def rational(obj): > initers = [(int, from_int), (basestring, from_str), (list, from_list)] > for obj_type, initer in initers: > if isinstance(obj, obj_type): > return initer(obj) > raise ValueError("Can not create a rational from a %r" % type(obj).__name__) You've just broken polymorphism. I can't use your factory function with an instance of my custom type that behaves like a list, but is not derived from list (or a non-'int' int, or a non-'basestring' string). Use the supplied value as you expect to be able to use it, and catch the exception (somewhere) if it doesn't work. That will allow *any* type that exhibits the correct behaviour, without needlessly restricting it to a particular inheritance. -- \ "This sentence contradicts itself -- no actually it doesn't." | `\ -- Douglas Hofstadter | _o__) | Ben Finney From steve at REMOVE.THIS.cybersource.com.au Thu Jan 18 07:44:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 18 Jan 2007 23:44:38 +1100 Subject: classes: need for an explanation References: <1169121502.779509.138890@m58g2000cwm.googlegroups.com> Message-ID: On Thu, 18 Jan 2007 03:58:22 -0800, 0k- wrote: > hello! > > i started to write a game in python in which i want to implement > "dynamically attachable" attributes. All attributes in Python are dynamically attachable. >>> class Parrot: ... pass ... >>> p = Parrot() >>> hasattr(p, "plumage") False >>> p.plumage = "beautiful red" >>> p.plumage 'beautiful red' [snip] > class Thing(object): > props = {} > def __init__(self): > self.props["text"] = TxtAttr("something important") > > t1 = Thing() > t2 = Thing() > > t2.props["text"].value = "another string" Have you considered a simpler class like this? class Thing(object): def __init__(self, value="something important"): self.text = TxtAttr(value) t2 = Thing("another string") Then, instead of writing t2.props["text"].value (four lookups) you would just write t2.text (two lookups). -- Steve. From yankeeinexile at gmail.com Tue Jan 9 12:10:38 2007 From: yankeeinexile at gmail.com (Lawrence Statton XE2/N1GAK) Date: 09 Jan 2007 11:10:38 -0600 Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> Message-ID: <87mz4s9ldd.fsf@gmail.com> zoara writes: Link NOT removed to encourage more abuse ... > > http://www.octabox.com/productivity_poll.php I somehow missed this the first time. Thanks for the pointer -- I gave them some nice PDP-10 related responses. I truly hope to have my TOPS-20 productivity improved soon, thanks to these people. -- Lawrence Statton - lawrenabae at abaluon.abaom s/aba/c/g Computer software consists of only two components: ones and zeros, in roughly equal proportions. All that is required is to sort them into the correct order. From oliphant.travis at ieee.org Thu Jan 25 00:35:58 2007 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 24 Jan 2007 22:35:58 -0700 Subject: numpy or _numpy or Numeric? In-Reply-To: References: Message-ID: auditory wrote: >>> While trying to install numpy accroding to its homepage. >>> (http://numpy.scipy.org/numpydoc/numdoc.htm). >>> i am quite confused. >> You are reading old documentation for Numeric and so any installation >> description is how to install the Numeric module (not its newer >> replacement which is called NumPy). > > I found the above website from googling with "numpy" keyword, > and supprised at that the top matching page is old one. > The website is not the old one. http://numpy.scipy.org is correct. But, the documentation is old. But, it is still useful (except for Numeric specific information like how to install it). Therefore we still make a link to it. -Travis From pydecker at gmail.com Tue Jan 23 17:54:30 2007 From: pydecker at gmail.com (Peter Decker) Date: Tue, 23 Jan 2007 17:54:30 -0500 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: Message-ID: On 1/23/07, Daniel Jonsson wrote: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! I strongly prefer the look and feel of wxPython, but I have to write apps that run on Windows and Linux, and wxPython looks great on both. If you do go with wxPython, I'd strongly recommend using the Dabo framework, as they wrap the raw and somewhat ugly wxPython code (inherited from its C++ roots) into something much more Pythonic and consistent. Apps that took me all day in wxPython take me a couple of hours using the dabo.ui module. -- # p.d. From david.bear at asu.edu Mon Jan 29 15:31:55 2007 From: david.bear at asu.edu (David Bear) Date: Mon, 29 Jan 2007 13:31:55 -0700 Subject: python 2.3 module ref Message-ID: <6178735.qJi6sMvOM0@teancum> Since redhat packages python2.3 with their distro (RHEL 4..) I was looking for a module reference for that version. Looking at python.org I only see current documentation. any pointers to a 2.3 module ref? -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From rzantow at gmail.com Mon Jan 22 15:08:25 2007 From: rzantow at gmail.com (rzed) Date: Mon, 22 Jan 2007 15:08:25 -0500 Subject: Are there sprintf in Python??? References: <1169496238.925052.311660@l53g2000cwa.googlegroups.com> Message-ID: "questions?" wrote in news:1169496238.925052.311660 at l53g2000cwa.googlegroups.com: > Are there any sprintf in Python? > I know you can print to files(or redefine sys.stout) and later > open the file content. > > Are there similar function to sprintf in C? Something like this? x = 9 vbl = "One digit: %d, four digits: %04d" % (x,x) print vbl From pavlovevidence at gmail.com Wed Jan 31 15:24:21 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 31 Jan 2007 12:24:21 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170271023.955808.314010@q2g2000cwa.googlegroups.com> References: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> <1170271023.955808.314010@q2g2000cwa.googlegroups.com> Message-ID: <1170275061.786779.74910@a34g2000cwb.googlegroups.com> Michele Simionato wrote: > On Jan 31, 5:23 pm, "Frank Potter" wrote: > > I want to find a multithreaded downloading lib in python, > > can someone recommend one for me, please? > > Thanks~ > > Why do you want to use threads for that? Twisted is the > obvious solution for your problem, Overkill? Just to download a few web pages? You've got to be kidding. > but you may use any > asynchronous framework, as for instance the good ol > Tkinter: Well, of all the things you can use threads for, this is probably the simplest, so I don't see any reason to prefer asynchronous method unless you're used to it. One Queue for dispatching should be enough to synchronize everything; maybe a Queue or simple lock at end as well depending on the need. The OP might not even care whether it's threaded or asynchronous. Carl Banks From chris.cavalaria at free.fr Wed Jan 31 05:33:39 2007 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 31 Jan 2007 11:33:39 +0100 Subject: Help me understand this In-Reply-To: References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> <1170146755.446429.90720@v45g2000cwv.googlegroups.com> Message-ID: <45c0708d$0$26734$426a74cc@news.free.fr> James Stroud a ?crit : > Beej wrote: >>>>> (2).__add__(1) > > Nice. I would have never thought to put parentheses around an integer to > get at its attributes. > > James You can also do it like that : >>> 2 .__add__(1) 3 From heikki at osafoundation.org Thu Jan 11 18:29:05 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Thu, 11 Jan 2007 15:29:05 -0800 Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error In-Reply-To: <1168543799.097737.127930@i56g2000hsf.googlegroups.com> References: <1168543799.097737.127930@i56g2000hsf.googlegroups.com> Message-ID: nagle at animats.com wrote: > That's a problem for me. I need short timeouts; I'm accessing sites > that might or might not have SSL support, and I need to quickly time > out when there's no SSL server. You should be able to do short timeouts, just not using the global setdefaulttimeout. Have you tried Connection.set_socket_read/write_timeout? Also like I mentioned before, if you use the Twisted wrapper and let Twisted handle network stuff you should be fine. > Python needs a merge here. Read Guido van Rossum's rant on M2Crypto: > > http://www.artima.com/weblogs/viewpost.jsp?thread=95863 That's old news, I believe I have fixed all of the issues mentioned there already in the 0.16 release. > What's probably needed is to implement the additional API functions of > the M2Crypto wrapper in the PyOpenSSL wrapper, so that the M2Crypto > components written in Python could be used with it. Then we'd have one > good implementation instead of two broken ones. M2Crypto and pyOpenSSL (and pyOpenSSL-extended, which you might want to take a look at as well) are implemented pretty differently, so merging seems unlikely. They are pretty small code wise, though, so it is not an impossible task. Personally I think I'd prefer if Python stdlib contained a better SSL module that did at least all the checks required for safe SSL connection. (Yeah, yeah, maybe I need to write it myself if nobody else gets to it;) -- Heikki Toivonen From bj_666 at gmx.net Sun Jan 7 12:21:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 07 Jan 2007 18:21:42 +0100 Subject: low level python read's References: <1168184689.924811.305290@42g2000cwt.googlegroups.com> Message-ID: In <1168184689.924811.305290 at 42g2000cwt.googlegroups.com>, gz wrote: > So how do i stop python from trying to be smart and just read *at most* > 1000 chars and let it go if he(it?*) reads less? For low level file stuff use the functions in the `os` module, i.e. `os.read()`. > p.s *is python a "he" or an "it"? I'd say "it". Ciao, Marc 'BlackJack' Rintsch From Thomas.Ploch at gmx.net Sun Jan 7 16:57:44 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 22:57:44 +0100 Subject: how to find the longst element list of lists In-Reply-To: References: Message-ID: <45A16CD8.5070006@gmx.net> Michael M. schrieb: > How to find the longst element list of lists? > > I think, there should be an easier way then this: > > s1 = ["q", "e", "d"] > s2 = ["a", "b"] > s3 = ["a", "b", "c", "d"] > > if len(s1) >= len(s2) and len(s1) >= len(s3): > sx1=s1 ## s1 ist l?ngster > if len(s2) >= len(s3): > sx2=s2 > sx3=s3 > else: > sx2=s3 > sx3=s2 > > if len(s2) >= len(s3) and len(s2) >= len(s1): > sx1=s2 ## s2 ist l?ngster > if len(s3) >= len(s1): > sx2=s3 > sx3=s1 > else: > sx2=s1 > sx3=s3 > > if len(s3) >= len(s1) and len(s3) >= len(s2): > sx1=s3 ## s3 ist l?ngster > if len(s1) >= len(s2): > sx2=s1 > sx3=s2 > else: > sx2=s2 > sx3=s1 > > After, the list ist sorted: > > sx1 = ["a", "b", "c", "d"] > sx2 = ["q", "e", "d"] > sx3 = ["a", "b"] > I don't really get that. You have three lists, you want to sort them after their length. You should put them into one list. I think you should rather implement this as: >>> list = [a1, s2, s3] >>> list.sort(lambda x,y: cmp(len(y), len(x))) >>> list [['a', 'b', 'c', 'd'], ['q', 'e', 'd'], ['a', 'b']] Thomas From rzantow at gmail.com Wed Jan 3 09:46:49 2007 From: rzantow at gmail.com (rzed) Date: Wed, 03 Jan 2007 09:46:49 -0500 Subject: function without brackets ? References: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> Message-ID: Stef Mientki wrote in news:57668 $459bbf95$d443bb3a$16218 at news.speedlinq.nl: > If I call a parameterless function without brackets at the end, > the function is not performed, but ... > I don't get an error message ??? > > Is this normal behavior ? > Yes, it's normal, but you did not in fact call the function, if you were using Python. Functions are objects that, for example, can be passed to other functions. The way to refer to the functions themselves is to omit the arguments and parentheses. So by simply stating the name of a function, that's all you've done. -- rzed From homeyland at ghetonews.com Tue Jan 16 22:25:56 2007 From: homeyland at ghetonews.com (Kelvin) Date: Wed, 17 Jan 2007 03:25:56 GMT Subject: Acc#2049850557 Activation Code Please Message-ID: <8Hgrh.671126$1T2.630559@pd7urf2no> An HTML attachment was scrubbed... URL: From researchbase at gmail.com Sat Jan 20 14:06:43 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 21 Jan 2007 00:36:43 +0530 Subject: confused on python rpc with apache, is it possible? In-Reply-To: <51etfpF1kappuU1@mid.uni-berlin.de> References: <51ce8uF1k0tl5U1@mid.uni-berlin.de> <1169276359.477277.17930@q2g2000cwa.googlegroups.com> <51etfpF1kappuU1@mid.uni-berlin.de> Message-ID: On 20/01/07, Diez B. Roggisch wrote: > > There is nothing an apache will do for you - except from possibly > proxing python. > > Go read up upon xmlrpc and python, possibly doing it with twisted, but > there are other options. > > Don't bother with the apache. well in that case I don't need apache. can I do xml-rpc using the default libraries that come with every python installer? is there some added advantage of using twisted? Krishnakant. From gagsl-py at yahoo.com.ar Wed Jan 3 19:35:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Jan 2007 21:35:49 -0300 Subject: static object In-Reply-To: <459c306c$0$314$426a74cc@news.free.fr> References: <459c306c$0$314$426a74cc@news.free.fr> Message-ID: <7.0.1.0.0.20070103212056.0566f190@yahoo.com.ar> At Wednesday 3/1/2007 19:38, meelab wrote: >I am looking for a way to create a "static object" or a "static class" - >terms might be inappropriate - having for instance: > >class StaticClass: > . > . > >and then >staticObject1 = StaticClass() >staticObject2 = StaticClass() > >so that staticObject1 and staticObject2 refers exactly to the same >instance of object. This is usually known as a Singleton. If you only want it to store values, or use "normal" methods, the most direct way is a simple module - modules are already singletons in Python. If you want to include properties, descriptors, and such, look for the Singleton (or Borg) pattern in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/ -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From paul at boddie.org.uk Mon Jan 22 13:22:20 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 22 Jan 2007 10:22:20 -0800 Subject: Is there a better way to implement this: References: Message-ID: <1169490140.401270.226830@l53g2000cwa.googlegroups.com> Michael Yanowitz wrote: > > I guess I am looking for something portable (both > Windows and Linux) where I can abort a function after > a certain time limit expires. Doing a search for "timeout function Python" on Google reveals a number of approaches. Using signals: * http://nick.vargish.org/clues/python-tricks.html * http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871 Using threads: * http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473878 Using processes: * http://lfw.org/python/delegate.html Paul From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 15:53:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 21:53:52 +0100 Subject: where is python on linux? In-Reply-To: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> Message-ID: <45a157a0$0$289$426a74cc@news.free.fr> Frank Potter a ?crit : > I installed fedora core 6 and it has python installed. > But the question is, where is the executable python file? > I can't find it so I come here for help. man which From m.sloyko at gmail.com Wed Jan 24 08:04:38 2007 From: m.sloyko at gmail.com (Maxim Sloyko) Date: 24 Jan 2007 05:04:38 -0800 Subject: Thoughts on using isinstance In-Reply-To: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> Message-ID: <1169643877.156673.207550@k78g2000cwa.googlegroups.com> On Jan 24, 3:38 pm, "abcd" wrote: > In my code I am debating whether or not to validate the types of data > being passed to my functions. For example > > def sayHello(self, name): > if not name: > rasie "name can't be null" > if not isinstance(name, str): > raise "name must be a string" > print "Hello " + name > > Is the use of isinstance a "bad" way of doing things? is it a "heavy" > operation? for example, if I use this in each function validate input > will it slow things down a lot? > > just curious how you might handle this type of situation (other than > not validating at all). > > thanks My opinion is that validation is generally good. However, you have to make it not too strict. For example, instead of print "Hello " + name you could have written print "Hello " + str(name) In this case requirement isinstance() will be too strict. The only thing you have to check is that hasattr(name, "__str__") and callable(name.__str__) In this case you can have validation, while at the same time enjoy full flexibility of dynamic typing. -- Maxim From deets at nospam.web.de Mon Jan 29 02:51:13 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 Jan 2007 08:51:13 +0100 Subject: Data structure and algorithms In-Reply-To: <1170027873.650783.172500@l53g2000cwa.googlegroups.com> References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> <1170025297.838143.191740@j27g2000cwj.googlegroups.com> <1170027873.650783.172500@l53g2000cwa.googlegroups.com> Message-ID: <525nccF1motuaU1@mid.uni-berlin.de> azrael schrieb: > i'd like to get more control like in c with pointers. I want to loose > the data after disabling: > >>>> list=[] >>>> list.append(Node(1)) >>>> list.append(Node(2)) >>>> list[0].next=list[1] > > > 1, 2 > > >>>> list.append(Node(3)) >>>> list[1].next=list[2] > > > 1,2,3 > > >>>> list[0].next=list[2] > > 1,3 (but 2 still exists as list[2]) So what? Then do del list[2] This is what happens in C also - if you store references to structures, they don't magically go away just because you refer to them from other places. Diez From robert.kern at gmail.com Thu Jan 11 13:08:00 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 Jan 2007 12:08:00 -0600 Subject: Frequency spectrum with fft of a real valued array...? In-Reply-To: References: Message-ID: Holger wrote: > What does it mean to me? How do I get to the wanted frequenca spectrum??? It's packed in the conventional FFT format. Here is a function in numpy (the successor to Numeric, which I assume that you are using) that generates the corresponding frequencies in the same packed format: In [324]: import numpy In [325]: numpy.fft.fftfreq? Type: function Base Class: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/numpy-1.0.2.dev3507-py2.5-macosx-10.4-i386.egg/numpy/fft/helper.py Definition: numpy.fft.fftfreq(n, d=1.0) Docstring: fftfreq(n, d=1.0) -> f DFT sample frequencies The returned float array contains the frequency bins in cycles/unit (with zero at the start) given a window length n and a sample spacing d: f = [0,1,...,n/2-1,-n/2,...,-1]/(d*n) if n is even f = [0,1,...,(n-1)/2,-(n-1)/2,...,-1]/(d*n) if n is odd -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mkeller.dci at gmail.com Wed Jan 24 22:20:33 2007 From: mkeller.dci at gmail.com (mukappa) Date: 24 Jan 2007 19:20:33 -0800 Subject: Subclassing cElementTree.XMLTreeBuilder Message-ID: <1169695233.737016.95950@a75g2000cwd.googlegroups.com> I found an earlier post about subclassing cElementTree.Element which can't be done because it is a factory method. I am trying to subclass XMLTreeBuilder with success using the python implementation, but not with cElementTree. [1013]$ python Python 2.3.4 (#1, Feb 22 2005, 04:09:37) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import elementtree.ElementTree >>> class X(elementtree.ElementTree.XMLTreeBuilder): ... pass ... >>> import cElementTree >>> class Y(cElementTree.XMLTreeBuilder): ... pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: cannot create 'builtin_function_or_method' instances >>> Is it possible to subclass cElementTree.XMLTreeBuilder? Thanks, Mike From ghirai at ghirai.com Sun Jan 7 09:19:11 2007 From: ghirai at ghirai.com (Ghirai) Date: Sun, 7 Jan 2007 16:19:11 +0200 Subject: Manually installing PIL Message-ID: <771449155.20070107161911@ghirai.com> Hello, My host doesn't have PIL installed, and from what i can tell, they won't install it. Is there any way i can copy the needed files near my python script? I'm using Image, ImageFont, ImageDraw and ImageFilter. Thanks. -- Best regards, Ghirai. From http Sun Jan 7 05:01:44 2007 From: http (Paul Rubin) Date: 07 Jan 2007 02:01:44 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <7x7ivz88af.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > __ (two leading underscores) results in name-mangling. This /may/ be > used to specify "private" data, but is really more useful when one is > designing with multiple super classes: Trouble with this is you can have two classes with the same name, perhaps because they were defined in different modules, and then the name mangling fails to tell them apart. From exarkun at divmod.com Wed Jan 31 20:10:29 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Jan 2007 20:10:29 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <45C122B7.6000701@mvista.com> Message-ID: <20070201011029.25807.1696981903.divmod.quotient.5293@ohm> On Wed, 31 Jan 2007 15:13:59 -0800, "Carl J. Van Arsdall" wrote: >Jean-Paul Calderone wrote: >> [snip] >>> >>> >> >> You're right. Learning new things is bad. My mistake. >> >> Jean-Paul >> >That isn't what I said at all. You have to look at it from a >cost/benefit relationship. Its a waste of time/money to learn something >complex to do something simple. For the simple things, use a simple >solution. KISS. When he has an application that would require >something more complex, it would be at that point he should consider >using it for a project. Unless the OP has a desire to learn this >technology, then more power to him. I, however, do not believe that >would be the best approach for a simple problem. > >Knowing the appropriate tool for the job is a trait of an good engineer. > You are assuming that he already knows how to use threads, and so there is no investment required for a threaded solution. In my experience, it's much safer to assume the opposite. _Even_ (often _especially_ when a threaded solution is explicitly requested. Jean-Paul From michele.simionato at gmail.com Sun Jan 14 03:35:27 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Jan 2007 00:35:27 -0800 Subject: Decorators inside of class and decorator parameters In-Reply-To: References: <1168728983.541526.202320@l53g2000cwa.googlegroups.com> Message-ID: <1168763727.677028.149640@51g2000cwl.googlegroups.com> Gabriel Genellina wrote: > see this article by M. Simoniato > http://www.phyast.pitt.edu/~micheles/python/documentation.html for a better > way using its decorator factory. Actually the name is Simionato ;) I have just released version 2.0, the new thing is an update_wrapper function similar to the one in the standard library, but with the ability to preserve the signature on demand. For instance def traced(func): def wrapper(*args, **kw): print 'calling %s with args %s, %s' % (func, args, kw) return func(*args, **kw) return update_wrapper(wrapper, func, create=False) works exactly as functools.update_wrapper (i.e. copies__doc__, __module__,etc. from func to wrapper without preserving the signature), whereas update_wrapper(wrapper, func, create=True) creates a new wrapper with the right signature before copying the attributes. Michele Simionato From vinay_sajip at yahoo.co.uk Tue Jan 9 05:07:39 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 9 Jan 2007 02:07:39 -0800 Subject: line duplication using logging to file References: <1168329975.491514.282000@11g2000cwr.googlegroups.com> Message-ID: <1168337259.283886.307050@s34g2000cwa.googlegroups.com> seb wrote: > Hi, I am writing to a file some basic information using the logging > module. It is working but in the log file some line are printed > several time. I had put some print debugging messages in the logging > function (so they appear on the consile) and they are called once only. > Obviously there is some understantding of the logging module that I am > missing. > > My simple logging program (see below) is called by several processes. > In this way I can collect the information from various sources (and not > use the network enabled logging module) > > I am using python 2.4 on WinXP SP2. > > Do you have any idea ? Thanks in advance. > I copied your two scripts into "appel_main.py" and "appel_log.py" and when I run, I get a single line in main_log.txt: 2007-01-09 10:01:42,766 - INFO -C:\temp\appel_main.py___?something On the console is printed: time.asctime() Tue Jan 09 10:04:25 2007 received level= info message= C:\temp\appel_main.py___?something logger info _________ C:\temp\appel_main.py___?something I didn't see any repetitions. Perhaps it's to do with multiple processes in your environment? If you call write_log several times you will add a handler several times - this is not a normal pattern of use. You should separate setup of Loggers/Handlers/Formatters from actually logging events via debug(), info() etc. Best regards, Vinay Sajip From bignose+hates-spam at benfinney.id.au Tue Jan 16 17:04:29 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Jan 2007 09:04:29 +1100 Subject: Projects anyone? References: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> Message-ID: <877ivmbpci.fsf@benfinney.id.au> "placid" writes: > I'm looking for anyone who is working on a project at the moment that > needs help (volunteer). The Volunteer Opportunities page is a bit thin at the moment. I'd hope people can respond to this thread and update that page with other projects that need help. The Coding Project Ideas page is more specifically focussed on getting programmer help. Browse the Cheese Shop for packages that you'd like to improve, and offer your help to the project maintainer. -- \ "A 'No' uttered from deepest conviction is better and greater | `\ than a 'Yes' merely uttered to please, or what is worse, to | _o__) avoid trouble." -- Mahatma Gandhi | Ben Finney From alain.walter at thalesgroup.com Tue Jan 30 05:07:14 2007 From: alain.walter at thalesgroup.com (awalter1) Date: 30 Jan 2007 02:07:14 -0800 Subject: thread and processes with python/GTK Message-ID: <1170151634.019690.320310@k78g2000cwa.googlegroups.com> Hello, I'm developping an application with python, pyGTK and GTK+. I've performed many tests by using methods as Popen, popen2, os.system ... to communicate with Unix (HPUX), The last attempt is this code written in a thread : fin,fout = popen2.popen2('ps -def') line = fin.readline() while 1 : if not line : break print "line=",line line = fin.readline() fin.close() In that case, lines are printed only when I exit my application. Usually the behavior is not as expected and I cannot understand why. I am wondering that it could be a constraint from the use of GTK (mainloop() existence ???). Is somebody aware about conflict between GTK use and unix mechanism. Thanks for you help From wolfgang.grafen at marconi.com Mon Jan 22 13:19:05 2007 From: wolfgang.grafen at marconi.com (Wolfgang Grafen) Date: Mon, 22 Jan 2007 19:19:05 +0100 Subject: Program eating memory, but only on one machine? In-Reply-To: References: Message-ID: <45B50019.7040509@marconi.com> I had a similar problem with an extension module on Solaris years ago. My problem at that time: I requested memory and released it and requested more memory in the next step and so on. The reason that the memory was eaten up: An answer out of this group was that the operating system doesn't release the memory space because it assumes you will need it soon again. The memory will only be released with the end of the process. The solution was always to request memory for the largest array the process will demand and it worked for me. Regards Wolfgang Per B.Sederberg wrote: > Wolfgang Draxinger darkstargames.de> writes: >>> So, does anyone have any suggestions for how I can debug this >>> problem? >> Have a look at the version numbers of the GCC used. Probably >> something in your C code fails if it interacts with GCC 3.x.x. >> It's hardly Python eating memory, this is probably your C >> module. GC won't help here, since then you must add this into >> your C module. >> >>> If my program ate up memory on all machines, then I would know >>> where to start and would blame some horrible programming on my >>> end. This just seems like a less straightforward problem. >> GCC 3.x.x brings other runtime libs, than GCC 4.x.x, I would >> check into that direction. >> > > Thank you for the suggestions. Since my C module is such a small part of the > simulations, I can just comment out the call to that module completely (though I > am still loading it) and fill in what the results would have been with random > values. Sadly, the program still eats up memory on our cluster. > > Still, it could be something related to compiling Python with the older GCC. > > I'll see if I can make a really small example program that eats up memory on our > cluster. That way we'll have something easy to work with. > > Thanks, > Per > > > From http Sat Jan 13 02:28:06 2007 From: http (Paul Rubin) Date: 12 Jan 2007 23:28:06 -0800 Subject: Boilerplate in rich comparison methods References: Message-ID: <7x8xg71j3t.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > class Parrot: > def __eq__(self, other): > return self.plumage() == other.plumage() > def __ne__(self, other): > return self.plumage() != other.plumage() > def __lt__(self, other): > return self.plumage() < other.plumage() > def __gt__(self, other): > return self.plumage() > other.plumage() > def __le__(self, other): > return self.plumage() <= other.plumage() > def __ge__(self, other): > return self.plumage() >= other.plumage() If it's that uniform I think you can just use __cmp__: class Parrot: def __cmp__(self, other): return cmp(self.plumage(), other.plumage()) Did I miss something? The idea of rich comparison is that the different relations aren't so similar to each other, e.g. some kind of partial ordering. > If the comparison requires a lot of work, I'll do something like this: > > class Aardvark: > def __le__(self, other): > return lots_of_work(self, other) > def __gt__(self, other): > return not self <= other > # etc. > > But I can't help feeling that there is a better way. What do others do? Same as above. From phil at riverbankcomputing.co.uk Wed Jan 24 08:51:20 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Wed, 24 Jan 2007 13:51:20 +0000 Subject: Missing .dlls when installing PyQt!? :( In-Reply-To: <1169645779.368746.157750@l53g2000cwa.googlegroups.com> References: <1169645779.368746.157750@l53g2000cwa.googlegroups.com> Message-ID: <200701241351.20931.phil@riverbankcomputing.co.uk> On Wednesday 24 January 2007 1:36 pm, wd.jonsson at gmail.com wrote: > Hello! > > I must be doing something wrong here because I'm getting all these > missing .dll messages after installing PyQT. This is what I've done (no > step excluded): > > 1. Fresh installation of Python25 > 2. I run the PyQt-gpl-4.1.1-Py2.5-Qt4.2.2.exe file which should include > SIP > 3. I run the qt-win-opensource-4.2.2-mingw.exe file > 4. I try to launch the C:\Program > Files\PyQt4\examples\tools\qtdemo\qtdemo.pyw file > > Result: > Error message says: Can't find mingwm10.dll > > After searching for the file I found it in the C:\Qt\4.2.2\bin > directory. I copied the dll to the windows dir just to run in to the > next missing dll error (QtCore4.dll) which is also located in the same > directory. What have I missed? I've been trying to install QT for 6 > hours now... > > Gah, please help! :) Make sure your PATH includes the directory containing the MinGW DLL. Phil From eric_brunel at despammed.com Wed Jan 31 03:47:48 2007 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 31 Jan 2007 09:47:48 +0100 Subject: Resizing widgets in text windows References: <1169847315.631951.295830@a75g2000cwd.googlegroups.com> <1170195187.058117.14830@q2g2000cwa.googlegroups.com> Message-ID: On Tue, 30 Jan 2007 23:13:07 +0100, wrote: > I'm using a text widget to hold a set of plots, one plot per line, > such that the scrolling capability of the text widget can be taken > advantage of to display only a subset of the plots at any given time. > In the analyses my program automates, there are at least several plots > are typically loaded into the text widget. This works out splendidly, > but the width of the plots has thus far been a static thing. Now, I'll > be able to adjust the plots widths so that when the owner window is > resized, the width of each plot in the text widget is adjusted and the > plot continues to occupy the entire text widget but no more, making > for a much more professional looking product. IMHO, "abusing" the text widget to do that is quite likely to cause problems in the future. For this use case, I would have used a Canvas with scrollbars containing a Frame where the plots are packed or gridded vertically. The Canvas's scrollregion should then be adjusted each time a plot is added, removed or resized, and you'd still have to use the event to resize the Frame to the Canvas's width. But at least, that's what Canvases and Frames are for; the Text widget is for... well, displaying text. Also note that Pmw (http://pmw.sourceforge.net/) has a ScrolledFrame megawidget that just does what you want. > Muchas gracias. You're welcome. HTH again... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From jweida at gmail.com Wed Jan 24 23:40:27 2007 From: jweida at gmail.com (Jerry) Date: 24 Jan 2007 20:40:27 -0800 Subject: newbie - returned values from cscript.exe In-Reply-To: <1169666769.242698.70730@j27g2000cwj.googlegroups.com> References: <1169666769.242698.70730@j27g2000cwj.googlegroups.com> Message-ID: <1169700027.846610.234310@a75g2000cwd.googlegroups.com> I would probably start with a look at popen. With it you can make your call to cscript and capture the output. Then, you don't need to set any environment variables. On Jan 24, 1:26 pm, "Rich" wrote: > I am writing my first python script and I'm guessing this is something > obvious but I can't find any examples of doing something like this. I > have a python script that is running a vbscript through cscript.exe. > The vbscript looks up a server name, username, password etc and returns > these values in a delimited list using wscript.echo. I can assign > these values to variables using a Windows batch files with the > following code > > FOR /F "tokens=1-6" %%a in ('cscript /nologo GetServerAccessInfo.vbs"') > do ( > SET DB_SERVER_NAME=%%a > SET DB_NAME=%%b > SET NMDBO_USERNAME=%%c > SET NMDBO_PASSWORD=%%d > SET SU_USERNAME=%%e > SET SU_PASSWORD=%%f > > I can't figure out how to do the same thing using a python script to > call this instead of a batch file. > > I am running the vbscript by using the following command > os.system('cscript /nologo GetServerAccessInfo.vbs') From carsten at uniqsys.com Tue Jan 9 08:40:28 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 09 Jan 2007 08:40:28 -0500 Subject: Maths error In-Reply-To: References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: <1168350028.3722.3.camel@dot.uniqsys.com> On Tue, 2007-01-09 at 11:38 +0000, Nick Maclaren wrote: > |> Rory Campbell-Lange wrote: > |> > |> > Is using the decimal module the best way around this? (I'm > |> > expecting the first sum to match the second). It seem > |> > anachronistic that decimal takes strings as input, though. > > As Dan Bishop says, probably not. The introduction to the decimal > module makes exaggerated claims of accuracy, amounting to propaganda. > It is numerically no better than binary, and has some advantages > and some disadvantages. Please elaborate. Which exaggerated claims are made, and how is decimal no better than binary? -Carsten From __peter__ at web.de Thu Jan 4 12:02:48 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Jan 2007 18:02:48 +0100 Subject: Sorting on multiple values, some ascending, some descending References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> Message-ID: Neil Cerutti wrote: > Another trick is to factor the key application out of the sort. > This may be a good idea if when you want to minimize the number > of times your key function is called. > > The idea is to mangle the list temporarily so you can use an > unkeyed sort, and then unmangle the sorted data. Here's a silly > example using a phone directory that's not stored in a format > that's easy to sort. No need to jump through these hoops; list.sort(key=keyfunc) calls keyfunc() exactly once per list item: >>> from random import shuffle >>> items = range(-5, 10) >>> shuffle(items) >>> count = 0 >>> def key(value): ... global count ... count += 1 ... return abs(value) ... >>> items.sort(key=key) >>> count 15 Peter From exarkun at divmod.com Wed Jan 31 12:03:39 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Jan 2007 12:03:39 -0500 Subject: What is the dummy statement that do nothing in Python? In-Reply-To: Message-ID: <20070131170339.25807.1722520908.divmod.quotient.4715@ohm> On Wed, 31 Jan 2007 11:49:53 -0500, Dongsheng Ruan wrote: >I remember that in python there is some kind of dummy statement that just >holds space and does nothing. > >I want it to hold the place after a something like if a>b: do nothing > >I can't just leave the space blank after if statement because there will be >error message. > >Does anybody know what to insert there? http://python.org/doc/tut/node6.html#SECTION006500000000000000000 Jean-Paul From fdelente at mail.cpod.fr Sat Jan 27 02:43:59 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 27 Jan 2007 07:43:59 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> <12rl5mq4nnqoea0@corp.supernews.com> <45bafda7$0$2417$426a74cc@news.free.fr> Message-ID: <45bb02bf$0$26684$426a34cc@news.free.fr> Incidentally, I noticed something about the environment: in my script, I use the LINES and COLUMNS environment vars that are set in my shell: columns=int(os.environ.get("COLUMNS")) lines=int(os.environ.get("LINES")) In the shell, I get $ echo $LINES $COLUMNS 89 199 but python doesn't get these values. I have to start the script with $ LINES=$LINES COLUMNS=$COLUMNS ./sort_entries.py How come? -- Fabrice DELENTE From seandavi at gmail.com Tue Jan 9 08:49:32 2007 From: seandavi at gmail.com (Sean Davis) Date: 9 Jan 2007 05:49:32 -0800 Subject: mxODBC problems Message-ID: <1168350572.375852.212740@i15g2000cwa.googlegroups.com> I have just installed mxODBC on my x86_64 suse linux machine, where I use unixODBC for connection. Running queries from isql or DataManager works fine for the DSN that I am using. However, under mxODBC, I can get a connection object and a cursor object, but all attempts to execute even the simplest selects result in empty resultsets. Any ideas on what might be wrong? >>> from mx.ODBC.unixODBC import * >>> con = connect('Postgresql',user='username',password='passwd') >>> cur = con.cursor() >>> cur.execute('SELECT * FROM g_rif') >>> rs = cur.execute('SELECT * FROM g_rif') >>> rs >>> cur.execute('SELECT * FROM g_rif').fetchall() Traceback (most recent call last): File "", line 1, in AttributeError: 'NoneType' object has no attribute 'fetchall' Thanks, Sean From ndbecker2 at gmail.com Fri Jan 12 06:52:43 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 12 Jan 2007 06:52:43 -0500 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: parallelpython at gmail.com wrote: > Has anybody tried to run parallel python applications? > It appears that if your application is computation-bound using 'thread' > or 'threading' modules will not get you any speedup. That is because > python interpreter uses GIL(Global Interpreter Lock) for internal > bookkeeping. The later allows only one python byte-code instruction to > be executed at a time even if you have a multiprocessor computer. > To overcome this limitation, I've created ppsmp module: > http://www.parallelpython.com > It provides an easy way to run parallel python applications on smp > computers. > I would appreciate any comments/suggestions regarding it. > Thank you! > Looks interesting, but is there any way to use this for a cluster of machines over a network (not smp)? From michele.simionato at gmail.com Fri Jan 26 23:27:29 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Jan 2007 20:27:29 -0800 Subject: instancemethod In-Reply-To: References: Message-ID: <1169872049.261689.263820@j27g2000cwj.googlegroups.com> On Jan 22, 2:58 am, "Gert Cuykens" wrote: > http://www.faqts.com/knowledge_base/view.phtml/aid/16824 There is a factual mistake on that reference. The last sentence > One final note: the single most common use for classmethod is probably > in overriding __new__(). It is always needed when overriding __new__() > because __new__() is a classmethod. is wrong, since __new__ is a staticmethod, NOT a classmethod. Somebody (possibly me, if I find their emails somewhere) should probably send a note to the authors (Michael Chermside, Dennis Peterson, Ian Bicking) asking to fix that. Michele Simionato From steve at REMOVE.THIS.cybersource.com.au Mon Jan 8 05:29:30 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Jan 2007 21:29:30 +1100 Subject: how to find the longst element list of lists References: Message-ID: On Sun, 07 Jan 2007 20:55:19 -0500, Dan Sommers wrote: > On Sun, 07 Jan 2007 22:23:22 +0100, > "Michael M." wrote: > >> How to find the longst element list of lists? >> I think, there should be an easier way then this: > >> s1 = ["q", "e", "d"] >> s2 = ["a", "b"] >> s3 = ["a", "b", "c", "d"] > > [ snip ] > > One more thing to think about: if your list of lists grows (i.e., if > you end up with thousands of lists instead of just three), then sorting > may not be the way to go. Assuming that list_of_lists is your list of > lists, then something like this: > > longest_list, longest_length = list_of_lists[ 0 ], len( longest_list ) > for a_list in list_of_lists[ 1 : ]: > a_length = len( a_list ) > if a_length > longest_length: > longest_list, longest_length = a_list, a_length > > will run faster than sorting the list just to pick off one element (O(n) > vs. O(n log n) for all of you Big-Oh notation fans out there; you know > who you are!). But your O(n) code is running in relatively slow Python, while the sort method, while O(n log n), is some of the fastest, most highly optimized C code out there. Unless your list is truly gigantic, chances are the sort version will win. Here's my timing code: import timeit def getlongest1(list_of_lists): longest_list = list_of_lists[ 0 ] longest_length = len( longest_list ) for a_list in list_of_lists[ 1 : ]: a_length = len( a_list ) if a_length > longest_length: longest_list, longest_length = a_list, a_length return longest_list def getlongest2(list_of_lists): list_of_lists.sort(key=len) return list_of_lists[0] def make_list_of_lists(length): return [[None]*i for i in xrange(length)] t1 = timeit.Timer("getlongest1(L)", "from __main__ import getlongest1, L") t2 = timeit.Timer("getlongest2(L)", "from __main__ import getlongest2, L") Note that my test list_of_lists grows very big quite fast, like O(n**2). Assuming Python pointers are eight bytes, a mere length=10000 will require over 760MB just for the pointers. More realistic data may allow more extensive testing. And here are my timing results: >>> L = make_list_of_lists(1) >>> print t1.timeit(1000), t2.timeit(1000) 0.00209903717041 0.00367403030396 >>> L = make_list_of_lists(10) >>> print t1.timeit(1000), t2.timeit(1000) 0.00871086120605 0.00775289535522 >>> L = make_list_of_lists(100) >>> print t1.timeit(1000), t2.timeit(1000) 0.121382951736 0.0518100261688 >>> L = make_list_of_lists(1000) >>> print t1.timeit(1000), t2.timeit(1000) 0.809508085251 0.508343935013 >>> L = make_list_of_lists(10000) >>> print t1.timeit(100), t2.timeit(100) 0.906499147415 0.732254981995 >>> L = make_list_of_lists(20000) >>> print t1.timeit(100), t2.timeit(100) 1.83560800552 1.58732700348 For a list of 1 item, sorting is 1.8 times SLOWER; For a list of 10 items, sorting is 1.1 times FASTER; For 100 items, sorting is 2.3 times faster; For 1000 items, sorting is 1.6 times faster; For 10,000 items, sorting is 1.2 times faster; For 20,000 items, sorting is 1.1 times faster. The precise results depend on the version of Python you're running, the amount of memory you have, other processes running, and the details of what's in the list you are trying to sort. But as my test shows, sort has some overhead that makes it a trivial amount slower for sufficiently small lists, but for everything else you're highly unlikely to beat it. -- Steven. From kylotan at gmail.com Tue Jan 2 12:08:41 2007 From: kylotan at gmail.com (Ben Sizer) Date: 2 Jan 2007 09:08:41 -0800 Subject: Why does Python never add itself to the Windows path? In-Reply-To: References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> Message-ID: <1167757721.883547.70530@42g2000cwt.googlegroups.com> Chris Lambacher wrote: > On Sat, Dec 30, 2006 at 04:55:09PM -0800, Ben Sizer wrote: > > Yet many scripts and applications require parameters, or to be executed > > from a certain directory. For example, setup.py. Or the various > > turbogears scripts. Or easy_install. > Martin's point was that if you need to pass arguments, you can call the script > from the command line like so: > setup.py install > > The python part of the 'python setup.py install' idiom needs to be omitted on > Windows, but that does not mean that the solution is to automatically add it > to PATH. Firstly, that solution only works for actual Python scripts; it doesn't solve the utility scripts that are often installed to the /scripts directory. It's a shame that many responses on this thread don't address that half of the issue. Am I the only person who installs packages that add scripts (not all of which are Python ones)? Secondly, it's still a significant difference from the Unix-based installs. You're right, the solution doesn't automatically have to be adding it to the PATH - but I'm yet to see a good argument for choosing not to, apart from "I don't like it when apps do that". > The documentation is misleading... time for a but report: > http://sourceforge.net/tracker/index.php?func=detail&aid=1626300&group_id=5470&atid=105470 Fixing the docs is better than nothing, but I believe fixing the install to encourage uniform usage across all platforms is preferable, and that in this regard the documentation shows how it 'should' work. > > There appears to be a freely-available binary at this address that may > > suffice: > > http://legroom.net/modules.php?op=modload&name=Open_Source&file=index&page=software&app=modpath > Unfortunately the Python installer is not an InnoSetup installer. The page I linked to is a bit misleading but there is an executable on that page. All you then have to do is invoke it with the relevant parameter. -- Ben Sizer From nagle at animats.com Thu Jan 25 23:43:35 2007 From: nagle at animats.com (John Nagle) Date: Fri, 26 Jan 2007 04:43:35 GMT Subject: Python does not play well with others In-Reply-To: <7xzm864y36.fsf@ruckus.brouhaha.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> <7xzm864y36.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Nagle writes: > >> That's the problem. We now have four SSL implementations for >>Python, none of which let you do all the things OpenSSL can do. > > > I'm aware of some OpenSSL wrappers plus TLSlite. Am I missing a > couple more? I guess maybe the OpenSSL wrappers also work on GnuTLS. > > >> Can you build the built-in SSL package without building all of >>Python? > > > I thought there was no built-in SSL package-- it just calls OpenSSL. "import SSL" brings in a .dll or .so object called "_ssl.pyd". This contains C glue code which connects Python to the C-based OpenSSL library. That's the component which needs work. Its source code is at http://svn.python.org/view/python/trunk/Modules/_ssl.c Part of the problem is that the build of _ssl.pyd is too integrated into the main Python build to work on easily. You can't just build and test a new SSL module and give it to others to test. You have to rebuild the whole Python system, and people who want to test the modified module need to run a custom Python build. SSL is somewhat integrated into the socket module internally, although from the code I don't see that this is absolutely necessary. The build machinery for SSL is in http://svn.python.org/view/python/trunk/setup.py After looking at that for a while, and the directory structure, it looks like the Python directory layout and build system makes the assumption that anything in the standard distribution is built as part of the basic Python build. The module itself could be separated from the trunk build; Python will run without it. It's the build process and directory structure which ties it up. As far as I can tell, there's no concept in the Python build system of a module that's built separately but ships with the standard Python distribution. Is that correct? So now I understand why the standard SSL module doesn't get fixed, and why there are three or four alternative re-implementations of it. It's easier to replace than to repair. John Nagle From bj_666 at gmx.net Tue Jan 9 19:13:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 10 Jan 2007 01:13:38 +0100 Subject: find.find References: Message-ID: In , Gigs_ wrote: > import fnmatch, os > > def find(pattern, startdir=os.curdir): > matches = [] > os.path.walk(startdir, findvisitor, (matches, pattern)) > matches.sort() > return matches > > def findvisitor((matches, pattern), thisdir, nameshere): # > for name in nameshere: > if fnmatch.fnmatch(name, pattern): > fullpath = os.path.join(thisdir, name) > matches.append(fullpath) > > can someone explain why (matches, pattern) is doing in this two funct? It's the first argument to `findvisitor()` which is invoked for every directory level by `os.path.walk()`. `findvisitor()` adds all file names that match `pattern` to the `matches` list. Ciao, Marc 'BlackJack' Rintsch From nagle at animats.com Thu Jan 25 12:17:16 2007 From: nagle at animats.com (John Nagle) Date: Thu, 25 Jan 2007 17:17:16 GMT Subject: Python does not play well with others In-Reply-To: <1169726842.719104.304300@v45g2000cwv.googlegroups.com> References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> Message-ID: Paul Boddie wrote: > On 25 Jan, 12:01, "Ben Sizer" wrote: > >> I think that is why many of the SIGs are stagnant, why the standard library >> has so much fluff yet still lacks in key areas such as multimedia and web >> development, etc. > ... I think this is also a good insight into why things are as they are > within the core development section of the community, although one can wonder > what some people actively developing the language are actually doing with it > if they are satisfied with the state of some of the standard library > solutions. However, there are lots of factors which motivate people and the > proliferation (or otherwise) of solutions to common problems: whether one > develops one's own solutions as separate projects and/or tries to push for a > consensus, whether one cares about other people using such solutions, whether > one aspires to contributing to the standard library. > > Over the years, people have tended towards building their own communities > around their projects rather than attempting to engage the wider Python > community, and I think a motivation behind that has been the intractability > of improving parts of the standard library. Yes. Working on "frameworks" is perceived as cooler than working on libraries. Things like Ruby on Rails, Struts, Zope, and Twisted get attention. There are papers and conferences on these things. It's hard to get people excited about overhauling the CGI library, or making mod_python work securely in shared-hosting environments. The key distinction between a framework and a library is that users are expected to make their code fit the framework. In particular, frameworks aren't expected to play well with each other. If you need something from Zope and something from Twisted, you're probably not going to be able to make it work. Libraries, on the other hand, are expected to play well together. Which means that they have to handle the hard cases correctly, not just the easy ones. > True. It also doesn't address the issue of development priorities and their > role in defining the platform's own standards ... > I do wonder whether the interests of language/runtime project developers > eventually become completely aligned with the needs of such projects, making > things like "multimedia and web development" seem irrelevant, uninteresting > or tangential. This has worrying implications for the perceived relevance of > Python with regard to certain kinds of solutions, despite the wealth of > independently produced libraries available for the language. Something like that happened to the C++ standards committee. The committee was captured by the template fanatics, and most new standards work involves doing computation at compile time via template expansion. That's seldom done in production code, yet most of the standards effort is devoted to making cool template hacks work better. Meanwhile, real problems, like doing something about memory leaks and buffer overflows, are ignored by the C++ committee. As a result, C++ is being displaced by Java and C#, which don't have elaborate templates but do have memory safety. I'm not sure how the Python development community will deal with this problem. But what's happened in the C++ standards world has clearly been very bad for users of the language. Learn from the mistakes there. My main concern is with glue code to major packages. The connections to OpenSSL, MySQL, and Apache (i.e. mod_python) all exist, but have major weaknesses. If you're doing web applications, those are standard pieces which need to work right. There's a tendency to treat those as abandonware and re-implement them as event-driven systems in Twisted. Yet the main packages aren't seriously broken. It's just that the learning curve to make a small fix to any of them is substantial, so nobody new takes on the problem. John Nagle Animats From pavlovevidence at gmail.com Sat Jan 27 07:51:19 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 27 Jan 2007 04:51:19 -0800 Subject: New vs Old Style Python Classes in C Extensions? In-Reply-To: References: Message-ID: <1169902279.509258.62290@q2g2000cwa.googlegroups.com> On Jan 27, 6:11 am, Jeff Rush wrote: > While I have a reasonable understanding of the differences in new-style versus > old-style classes, tonight while working a C extension module I realized I > don't know how to indicate which style my C extension module should appear as. > > I'm following the Python docs for extended modules, but it doesn't say in > there anyplace I can find which style I'm creating. My clue that something > was wrong is when this: > > from cextension import Context > > class MyContext(Context): > > def __init__(self): > super(Context, self).__init__() > > repeatedly and reliably failed with a corrupted C data structure, while this: > > class MyContext(Context): > > def __init__(self): > Context.__init__() > > worked without any problems. As I understand it, the former uses new-style > semantics while the latter uses old-style, and -thats- when I realized I have > no idea which my C extension implemented. > > Any enlightenment? Short answer: It has nothing to do with old-style classes, and is probably just due to a mistake in your extension. Longer answer: C extention types have never implemented old-style classes. Before Python 2.2, classes and types were different things. All class instances were of the same type. However, C extension objects were a different type, and weren't class instances at all. Nowadays, new-style classes are types, but the converse isn't necessary true. In particular, the typical way of defining old extension types didn't work as a new-style type. So, as part of type- class unification, they added some new fields (tp_members, tp_new, and so on) and new idioms to replace some of the old idioms, effectively creating "new-style types". Unless you've adopted the new ways, your type isn't going to work as a class. If you have adopted the new ways, then it's probably just a mistake in your code. I suspect you have adopted the new ways, because I'd expect Python to raise TypeError when trying to subclass a function. So you probably just have a bug. Carl Banks From steve at holdenweb.com Fri Jan 26 10:53:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 26 Jan 2007 15:53:25 +0000 Subject: loose methods: Smalltalk asPython In-Reply-To: <1167260492.174445.98470@n51g2000cwc.googlegroups.com> References: <1167260492.174445.98470@n51g2000cwc.googlegroups.com> Message-ID: Carl Banks wrote: > Jan Theodore Galkowski wrote: >>> We've not had >>> an excellent dynamic OO language since Smalltalk, IMO. > > I would say that "excellence" in object oriented programming is not a > strong design goal of Python. Python tries to support OOP well, but > not to enhance OOP to the detriment of other, more important goals. > > [snip] >>> Guido was opposed to modifying builtin types before Java existed. It's >>> similar to his opposition to dynamic syntax. >> Opposition or not, the language definition is there. Surely Smalltalk's >> OO style can be respected. Smalltalkers have been doing OO in a dynamic >> context longer than many. There are things to learn there. > > Well, that Smalltalk and Ruby do this at least suggests that it won't > be the end of the world as we know it if it were to happen in Python. > Personally, I'm with Guido here. Allowing this might make Python's OOP > more "excellent", but it would be to the detriment of other, more > important goals, like minimizing surprise. > >> There are two things here that need to be kept straight, I think. >> >> One is the primacy of builtin types. >> >> The other is placing those builtins at the top of their own object >> hierarchy. Is "int", properly speaking, a descendent of "object"? No, >> it's the root of its own tree. > > Are you saying that it shouldn't be a descendant of "object", or that > it isn't? "int" is certainly a subclass of "object" in Python (as are > all objects). > >> Smalltalk has "int" as well, as a >> *subclass* of Number. It's primitive. > > Number is primitive? I thought all types in Smalltalk had a common > base type. > > Anyways, Python 3000 is exploring the idea of an abstract hierarchy > that has classes (interfaces?) like Number and Sequence. In fact, I > even saw some talk about somehow being able to retrofit classes to > support one of these interfaces/ABCs, though it was pretty conjectural. > >> In any case, as respectful of Mr/Dr van Rossum as I am, simply because >> so-and-so says something is bad and therefore it must be true is a >> fallacious response. > > The same could be said of Smalltalk, i.e., because Smalltalk does it > therefore it is good is just as fallacious. > > Regardless, whatever Guido pronounces is what happens. If he's > adamantly against something, it's pretty much an academic discussion. > Just to be perverse, there was an example recently where a developer asked (on python-dev) about the best way to trap and note the creation of all objects. With a proper hierarchy, in which everything calls its parent's constructor all the way up to object, in theory (and ignoring old-style classes) it would be possible to simply modify the behaviour of object. Unfortunately this is a no-no because object's behaviour is hard-wired into the CPython interpreter. The general feeling on python-dev seems to be that this is a step too far, and that the confusion engendered by this kind of patching would not be worth the benefits gained. Certainly it appears to this reader that such a feature woudl be more abused than used. The principle of least surprise thus reigns for now. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From exarkun at divmod.com Fri Jan 19 10:16:38 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 19 Jan 2007 10:16:38 -0500 Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error In-Reply-To: Message-ID: <20070119151638.17245.139266307.divmod.quotient.1609@ohm> On Fri, 12 Jan 2007 05:54:42 GMT, John Nagle wrote: >Heikki Toivonen wrote: >> nagle at animats.com wrote: >> >>> That's a problem for me. I need short timeouts; I'm accessing sites >>>that might or might not have SSL support, and I need to quickly time >>>out when there's no SSL server. >> >> >> You should be able to do short timeouts, just not using the global >> setdefaulttimeout. Have you tried Connection.set_socket_read/write_timeout? > > Yes. That does not affect the connect timeout; it's only effective once >the connection has been opened. And adjusting the session timeout >just recreates the blocking/non blocking problem. > > Incidentally, "get_socket_read_timeout()" doesn't work. Generates >"EXCEPTION at socket level: unpack str size does not match format", >every time, at least with Python 2.4 on Windows. The lower level >function returns one number as a string, like "7200", and the unpack >function tries to unpack it as "ll", which fails. > >> Also like I mentioned before, if you use the Twisted wrapper and let >> Twisted handle network stuff you should be fine. > > That would mean struggling with Twisted and dealing with its bugs. >(For example, has the MySQLdb mess been resolved for Twisted's API?) http://twistedmatrix.com/trac/search?q=MySQLdb&noquickjump=1&ticket=on I'd say so, unless you're referring to a bug you never reported (we only fix those at about half the rate of reported bugs). Jean-Paul From elrondrules at gmail.com Mon Jan 29 21:42:07 2007 From: elrondrules at gmail.com (elrondrules at gmail.com) Date: 29 Jan 2007 18:42:07 -0800 Subject: Convert raw data to XML Message-ID: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> Hi I am running a HTTP server which receives post from a process. In my do_POST method am receiving raw data. I know that this raw data has a valid XML content and I need to convert this into an XML file. Are there any routines to do this.. if not how to write one.. For example the raw data is as follows SomeText PassorFail without spaces or new lines. I need this to be written into an XML file as SomeText PassorFail The tags in the raw data are not the same alaways.. Hence I need a generic routine that does the trick Any pointers for this issue would help Thanks From ahmad_6132 at yahoo.com Tue Jan 16 16:05:04 2007 From: ahmad_6132 at yahoo.com (ahmad6132) Date: 16 Jan 2007 13:05:04 -0800 Subject: Very beautiful Message-ID: <1168981504.269881.215660@51g2000cwl.googlegroups.com> 1) If you are looking for the truth to soothe and please your self, just click on this link. 2) If you are looking for the secrt of the family happiness, just click on this link. 3) If you are looking for solving any social problem you face, just click on this link. http://www.sultan.org/articles/purposeoflife.htm From gagsl-py at yahoo.com.ar Mon Jan 29 23:55:01 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 01:55:01 -0300 Subject: creating a dictionary References: Message-ID: En Mon, 29 Jan 2007 23:45:40 -0300, mark escribi?: > i have few variables and i want to create a dictionary with these > variables > such that the keys are the variable names and the corresponding values > are the variable values.how do i do this easily? > for ex: > var1='mark' > var2=['1','2','3'] > my_dict = create_my_dictionary(var1, var2) > > and my_dict is {'var1':'mark', 'var2':['1','2','3']} > > is there a function for create_my_dictionary? var1='mark' var2=['1','2','3'] my_dict = dict(var1=var1, var2=var2) In addition, if you are inside a function, and these are the only variables, using locals() may be useful too: def f(): a = 1 b = 2 c = locals() print c d = 3 prints {'a': 1, 'b': 2} -- Gabriel Genellina From perica.zivkovic at gmail.com Sat Jan 13 05:36:11 2007 From: perica.zivkovic at gmail.com (perica.zivkovic at gmail.com) Date: 13 Jan 2007 02:36:11 -0800 Subject: Portable Python - free portable development environment ! In-Reply-To: References: <1168533423.224355.221390@k58g2000hse.googlegroups.com> <1168639781.763133.319580@s34g2000cwa.googlegroups.com> Message-ID: <1168684571.205607.277920@s34g2000cwa.googlegroups.com> yes on both last messages :) More platforms will be included if there is enoug people interested in that. and something like Enthought edition will be there :) with even more packages and options :) at least that is my goal for the future :) But I must say I will also always be carefull with size of the distro :) thats also important right? :) in this first release I focused on making it possible to work with django (because that is what I needed) and more functionality, libs, ide's will be added in future versions. more ideas? grtz Perica s... at pobox.com wrote: > perica> but this is first release and I have big plans ;) > > Including maybe other platforms than Windows? > > Skip From mikael at isy.liu.se Tue Jan 30 10:33:02 2007 From: mikael at isy.liu.se (Mikael Olofsson) Date: Tue, 30 Jan 2007 16:33:02 +0100 Subject: Please take me off the list In-Reply-To: References: Message-ID: <45BF652E.6090201@isy.liu.se> Daniel kavic wrote: > Sorry to waste email space , but I wish to be off this list because I have tried python and it is too difficult for me. > That's sad. Go to http://mail.python.org/mailman/listinfo/python-list and follow instructions. /MiO From bjourne at gmail.com Tue Jan 30 09:33:59 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 30 Jan 2007 15:33:59 +0100 Subject: How can I know both the Key c and Ctrl on the keyboard are pressed? In-Reply-To: <1170164680.123191.206630@p10g2000cwp.googlegroups.com> References: <1170147029.261981.322740@a75g2000cwd.googlegroups.com> <1170164680.123191.206630@p10g2000cwp.googlegroups.com> Message-ID: <740c3aec0701300633o3480c8acu8a01c7c5b37e96d4@mail.gmail.com> On 30 Jan 2007 05:44:40 -0800, Szabolcs Nagy wrote: > however Ctrl+C is a special key combination: running python in a unix > terminal it raises KeyboardInterrupt exception, imho in a windows cmd > promt it raises SystemExit No it is KeyboardInterrupt in Windows too. -- mvh Bj?rn From kay.schluehr at gmx.net Tue Jan 23 16:43:27 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 Jan 2007 13:43:27 -0800 Subject: Overloading assignment operator In-Reply-To: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1169588607.163039.216270@a75g2000cwd.googlegroups.com> Achim Domma schrieb: > Hi, > > I want to use Python to script some formulas in my application. The user > should be able to write something like > > A = B * C > > where A,B,C are instances of some wrapper classes. Overloading * is no > problem but I cannot overload the assignment of A. I understand that > this is due to the nature of Python, but is there a trick to work around > this? Not that I know about it but what shall be the behaviour of assignment when being overloaded? Kay From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 21:22:52 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 13:22:52 +1100 Subject: OT Annoying Habits (Was: when format strings attack) References: Message-ID: On Fri, 19 Jan 2007 12:20:26 -0800, Carroll, Barry wrote: > It took me about 3 seconds to realize that Mr. D'Aprano' Q&A session was > laid out bottom-to-top instead of top-to-bottom. After that, it made > perfect sense. Three seconds, compared to about thirty milliseconds if it were written in the normal fashion. That's an inefficiency of about two orders of magnitude. Multiply that by a few hundred news posts and emails that you might read in a day, and, well, I think that makes it a big deal. That means top posting is to effective communication what exchange-sort is to quicksort. I use the analogy advisably: just as there is overhead to quicksort that makes it slower for sufficiently small lists, so there is overhead to in-line posting that makes top posting easier for the reader under quite restricted circumstances: you're reading the posts in order, and the entire thread (or at least the relevant parts of it) are still in short term memory. > While it was a excellent way to demonstrate his > argument, it failed to prove his point, because, while top-to-bottom may > be the way he reads things, it isn't the way _everyone_ reads things. There are, as far as I know, no human languages that write from the bottom of the page upwards. But even if there are such languages, we're on an English language newsgroup, not Martian, and so we should (whenever possibly) adapt English conventions. > So, as far as I'm concerned, post your posts in whatever manner works > for you. If it's in English, I'll figure it out. If not, well, there's > always Babelfish. ;^) Or perhaps I should say: .snoitnevnoc hsilgnE tpada )ylbissop revenehw( dluohs ew os dna ,naitraM ton ,puorgswen egaugnal hsilgnE na no er'ew ,segaugnal hcus era ereht fi neve tuB -- Steven. From steve at REMOVE.THIS.cybersource.com.au Wed Jan 24 16:43:14 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 25 Jan 2007 08:43:14 +1100 Subject: Re-thinking my if-thens - a software engineering question References: <1169668287.517657.24450@l53g2000cwa.googlegroups.com> Message-ID: On Wed, 24 Jan 2007 11:51:27 -0800, metaperl wrote: > Ok, I have a module called textgen.py. The point of this module is to > generate a csv file from an array of dictionaries. You probably should use the csv module to do the grunt work, leaving your module just to massage the dicts into a form that csv can handle. > As I iterate through > each dictionary, I "massage" the dictionary values before writing them > out to csv. Now, for one dictionary entry, I have the following code: > > if dict_key == 'PCN': > fields = dict_val.split("/") > mo = re.match( '(\w{2})(\d{2})(\d{2})' , fields[1] ) > if mo: > dict_val = "%s/%s%s/%s" % (fields[0], mo.group(1), mo.group(3), > fields[2][1:]) > else: > dict_val = dict_val Your indentation seems very inconsistent -- the lines starting with "fields = ..." and "mo = ..." should have the same indentation. The line "dict_val = dict_val" is a no-op. You could just as easily write that as "pass", or even better, leave out the entire else clause. Reading between the lines, it sounds like you have a mass of if...elif clauses, like this: if dict_key == 'PCN': # some processing elif dict_key == 'NCP': # some different processing elif ... # blah blah blah else: # default processing This is an excellent candidate for dictionary-based dispatching. First, write a function for each processing block: def process_PCN(value): # do stuff to value return result and then create a dispatch table: dispatcher = {"PCN": process_PCN, "NCP": process_NCP, ...} Now your huge if...elif block becomes one line: # no default processing dispatcher[dict_key](dict_value) # with default processing dispatcher.get(dict_key, process_default)(dict_value) > Ok, so now here is what has happened. This code was based on the > assumption that dict_val would have 2 forward slashes in it. It turns > out that I need to follow a different process of massaging when no > slashes are present. A naive solution would be something like: > > if dict_key == 'PCN': > fields = dict_val.split("/") > if fields == 3: That can't possibly work. fields is a list, not an integer. I think you want if len(fields) == 3. > dict_val = pcn_three(fields) # where pcn_three > is the code above > else: > # new logic > > But I am wondering if I should abstract the flow of control into a > class or something. Nope. Abstract it into functions. -- Steven. From mccredie at gmail.com Wed Jan 3 10:53:49 2007 From: mccredie at gmail.com (Matimus) Date: 3 Jan 2007 07:53:49 -0800 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: References: Message-ID: <1167839629.435980.311750@k21g2000cwa.googlegroups.com> I don't know of a converter, one may exist. I have seen similar requests though and will give you a similar response to what I have seen. A converter, if it exists, may be able to produce working code but _not_ readable code. Python is a language whose strength comes from, among other things, its readability and conventions. Learning python is best done by using the online documentation (http://docs.python.org/tut/tut.html) and reading existing code (take a look at the built in modules). My biggest fear of teaching someone to program by using a program to convert perl to python is that they will end up writing python that still looks like perl. I don't know if it helps, but I know others will give you similar advice. -Matt From gigs at hi.t-com.hr Thu Jan 11 10:02:00 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 11 Jan 2007 16:02:00 +0100 Subject: os.mkfifo Message-ID: is os.mkfifo available on windows xp thx From larry.bates at websafe.com Tue Jan 30 09:57:09 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 30 Jan 2007 08:57:09 -0600 Subject: data design In-Reply-To: <45bf5763$0$22792$426a34cc@news.free.fr> References: <45bf5763$0$22792$426a34cc@news.free.fr> Message-ID: <45BF5CC5.5060306@websafe.com> Imbaud Pierre wrote: > The applications I write are made of, lets say, algorithms and data. > I mean constant data, dicts, tables, etc: to keep algorithms simple, > describe what is peculiar, data dependent, as data rather than "case > statements". These could be called configuration data. > > The lazy way to do this: have modules that initialize bunches of > objects, attributes holding the data: the object is somehow the row of > the "table", attribute names being the column. This is the way I > proceeded up to now. > Data input this way are almost "configuration data", with 2 big > drawbacks: > - Only a python programmer can fix the file: this cant be called a > configuration file. > - Even for the author, these data aint easy to maintain. > > I feel pretty much ready to change this: > - make these data true text data, easier to read and fix. > - write the module that will make python objects out of these data: > the extra cost should yield ease of use. > > 2 questions arise: > - which kind of text data? > - csv: ok for simple attributes, not easy for lists or complex > data. > - xml: the form wont be easier to read than python code, > but an xml editor could be used, and a formal description > of what is expected can be used. > - how can I make the data-to-object transformation both easy, and able > to spot errors in text data? > > Last, but not least: is there a python lib implementing at least part > of this dream? Use the configurations module. It was built to provide a way to parse configuration files that provide configuration data to program. It is VERY fast so the overhead to parse even thousands of lines of config data is extremely small. I use it a LOT and it is very flexible and the format of the files is easy for users/programmers to work with. -Larry Bates From nogradi at gmail.com Tue Jan 30 08:44:30 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 30 Jan 2007 14:44:30 +0100 Subject: subway code Message-ID: <5f56302b0701300544u4c64c1cao7a2b97460e7a3b23@mail.gmail.com> Does anyone know what happened to the subway project? The sites gosubway.org and subway.python-hosting.com have been down for a long time now. Actually, I would like to have the code just to look at it and maybe learn something, but it seems it completely disappeared from the net. Does anyone has access to it and the rights to make it publically available? From nospam at riddergarn.dk Mon Jan 29 10:47:10 2007 From: nospam at riddergarn.dk (Scripter47) Date: Mon, 29 Jan 2007 16:47:10 +0100 Subject: SQL connecting Message-ID: <45BE16FE.4040703@riddergarn.dk> Hey It got a problem with python to connect to my SQL DBs, that's installed on my apache server. how do i connect to sql? Gettting data? Insert into it? it is a localserver with php if that means something here is a *REALLY* dirty solution that a have used: [CODE] from urllib import * # sql query s = 'INSERT INTO `test` (`test`) VALUES ("1");' # encode and insert into db params = urlencode({'sql': sql}) urlopen("http://localhost/in/sql.php?%s" % params) [/CODE] -- _________ .__ __ ______________ / _____/ ___________|__|______/ |_ ___________ / | \______ \ \_____ \_/ ___\_ __ \ \____ \ __\/ __ \_ __ \/ | |_ / / / \ \___| | \/ | |_> > | \ ___/| | \/ ^ / / / /_______ /\___ >__| |__| __/|__| \___ >__| \____ | /____/ \/ \/ |__| \/ |__| From gagsl-py at yahoo.com.ar Sat Jan 13 23:29:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Jan 2007 01:29:55 -0300 Subject: Tkinter code (with pmw) executing to soon please help References: <1168746063.322340.10410@l53g2000cwa.googlegroups.com> Message-ID: escribi? en el mensaje news:1168746063.322340.10410 at l53g2000cwa.googlegroups.com... > Instead of creating my buttons and waiting for me to press them to > execute they are executing when I create them and won't do my callback > when I press them.. thanks for any help in advance This is a very frequent beginner's mistake. You are *calling* the event handler at the moment you create the buttons. You have to provide a *callable* but not call it yet. > button[num] = Tkinter.Button(frame,text = returnstring, > command=callback(returnstring))# So `callback` should return a function, like this: def callback(text): def handler(event): print text -- Gabriel Genellina From jstroud at mbi.ucla.edu Fri Jan 19 17:07:56 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 19 Jan 2007 14:07:56 -0800 Subject: How to comment code? In-Reply-To: <45b13876$0$323$e4fe514c@news.xs4all.nl> References: <45b13876$0$323$e4fe514c@news.xs4all.nl> Message-ID: Martin P. Hellwig wrote: > Hi all, > > I've been toying with python for about two years now. Not every day, > just when I encounter something in my job (sysadmin) repetitively dull. > The amazing thing is that like any other language (natural or not) > learning it more gives you power to express your thoughts better and > create something from nothing, for me this is something I can only > compare to freedom. > > However since I'm learning more of python I've struggled with > commenting, how should I've comment my code? I'm not talking about the > style but more on the concept itself, things that where a couple of > month ago a bunch of monkey poop is now as easy as reading a comic. > > I always give a brief description on what the code is supposed to do and > I suppose that any serious coder knows way more then me about > programming so I don't bother to comment that much since it mostly (in > my eyes) just clutters up the code and makes it actually harder to read. > > Though this makes me uncomfortably, commenting so little, I was thinking > that perhaps something like doctest (I'm not so much into unit testing > or the equivalents at this moment) has the side affect to make my code > more understandable and readable. Any practical experience you'd like to > share with me, any other comments are welcome too of course :-) I have found it useful to familiarize myself some tool such as epydoc and write comments in the function doc-string. For example, def doit(stuff, beta, cycles): """ Does nothing with I{stuff} in an infinite loop by applying a null operation. The I{cycles} parameter is multiplied by infinity. @param beta: null operator not to be applied to stuff @type beta: callable @type cycles: int """ This explains paramaters, etc., for you and other users of your API and paves the way for automatically generated documentation. Note that it would be excessive to comment each and every parameter, etc. Once the code is working correctly, a lot of in-line comments can be removed. Usually, in python, correctly working code is self explanatory at the implementation level, especially if you attempt to code "pythonically" (which can roughly be defined as the best practices according to the python community or the community subset who post to comp.lang.python). If you find that your code gets very complicated and needs excessive commenting to understand, try to factor it into hierarchically related simpler functions and classes and comment each individually using doc-strings. In essence, think about commenting the interface rather than the implementation. Use module level doc-strings (comments) to gather usage and explanation notes for the most useful functions. This allows users (for example, you) to use your libraries without burrowing into the automatically generated documentation for each and every function. Other tools may be as useful as epydoc, but this is the general strategy I have converged upon. James From colinlandrum at gmail.com Tue Jan 2 12:01:45 2007 From: colinlandrum at gmail.com (hubritic) Date: 2 Jan 2007 09:01:45 -0800 Subject: popen on windows In-Reply-To: References: <1167239813.187357.206240@73g2000cwn.googlegroups.com> Message-ID: <1167757305.044294.312140@k21g2000cwa.googlegroups.com> Thanks for your reply. I figured it out. I was not closing the file that path pointed to before executing the command. D'oh! So sometimes it read the file that was created on the previous test run ... Anyway, for the benefit of anyone who might be googling for a similar question, what seems to work for running a command in Windows and having it wait for the command to finish was (after closing the file before I refer to it) was: (this is python 2.4.3. I think subprocess was new in 2.4. See documentation for subprocess module) from subprocess import Popen r = Popen(string_with_the_command, shell=True) r.wait() Sometimes the hardest part of python is to resist the urge to imagine that things *must* be complicated and therefore the simpliest possible solution can't possibly work ... Daniel Klein wrote: > On 27 Dec 2006 09:16:53 -0800, "hubritic" > wrote: > > >I am trying to set off commands on Windows 2003 from python. > >Specifically, I am trying to use diskpart with a script file (pointed > >to with path). > > > > cmd = ["diskpart", "/s", path] > > p = Popen(cmd, shell=True) > > > >The script is meant to loop through twice. It will do so if I comment > >out the Popen call and print cmd instead. But when Popen is called, one > >disk will be formated, but not the next. > > What is the value of 'path' ? > > Does the command work from a Windows command prompt ? > > Dan From hg at nospam.org Tue Jan 23 01:54:34 2007 From: hg at nospam.org (hg) Date: Tue, 23 Jan 2007 07:54:34 +0100 Subject: beep or sound playing under linux References: Message-ID: hg wrote: > Hi, > > Is there a way to do that ? > > Regards, > > hg Thanks to all ... got some reading to do. hg From nmm1 at cus.cam.ac.uk Tue Jan 16 04:56:31 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 16 Jan 2007 09:56:31 GMT Subject: Maths error References: In article , "Hendrik van Rooyen" writes: |> |> [ Interval arithmetic ] |> |> > |> For people just getting into it, it can be shocking to realize just how |> > |> wide the interval can become after some computations. |> > |> > Yes. Even when you can prove (mathematically) that the bounds are |> > actually quite tight :-) |> |> This sounds like one of those pesky: |> "but you should be able to do better" - kinds of things... It's worse :-( It is rather like global optimisation (including linear programming etc.) The algorithms that are guaranteed to work are so catastrophically slow that they are of theoretical interest only, but almost every practical problem can be solved "well enough" with a hack, IF it is coded by someone who understands both the problem and global optimisation. This is why the "statistical" methods (so disliked by Kahan) are used. In a fair number of cases, they give reasonable estimates of the error. In others, they give a false sense of security :-( Regards, Nick Maclaren. From wanjunfeng at gmail.com Tue Jan 16 21:54:19 2007 From: wanjunfeng at gmail.com (Kevin Wan) Date: 16 Jan 2007 18:54:19 -0800 Subject: I wrote a C++ code generator in Python, would anyone please help me to review the code? :) In-Reply-To: <1168991250.445208.159020@v45g2000cwv.googlegroups.com> References: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> <1168991250.445208.159020@v45g2000cwv.googlegroups.com> Message-ID: <1169002459.483365.304190@38g2000cwa.googlegroups.com> Sorry, I didn't write that much document. But you can use fgen --help to get the usage. I'm writing document now. :) Thanks, Kevin mensanator at aol.com wrote: > Kevin Wan wrote: > > fgen is a free command line tool that facilitates cross platform c++ > > development, including header generation, cpp file generation, makefile > > generation, unit test framework generation, etc. > > > > http://sf.net/projects/fgen > > > > I'm not very familiar with Python. Any feedback are appreciated! > > No documentation? > > Am I supposed to reverse engineer all the source files to figure out > how I'm > supposed to use it? > > > Or > > anyone like to develop it with me? > > > > Thanks. From huayang.xia at gmail.com Fri Jan 12 11:28:06 2007 From: huayang.xia at gmail.com (Huayang Xia) Date: 12 Jan 2007 08:28:06 -0800 Subject: How to modify object attribute by python C API In-Reply-To: <1168551428.114028.278940@77g2000hsv.googlegroups.com> References: <1168551428.114028.278940@77g2000hsv.googlegroups.com> Message-ID: <1168619286.432190.104550@11g2000cwr.googlegroups.com> Thanks for the replies. For the checking, I found we have to spend a lot of codes to check the Python API's results. That is a pain. Is it reasonable to ignore the result check of APIs like PyString_FromString and PyString_AsString which will fail only when out of memory. Unfortunately there is no exception thrown (in C++) so that we can integrate the error handling. What is the best way(less code) to handle the error checking in normal practice? On Jan 11, 4:37 pm, "Huayang Xia" wrote: > I get a python object by running a class' constructor. Then I need to > modify the instance's attribute just like obj.attr1.attr2 = 'a' if in > python's term. > > PyObject* py_obj_attr1 = PyObject_GetAttrString(obj, "attr1"); > PyObject_SetAttrString(py_obj_attr1, "attr2", > PyString_FromString("a")); > Py_DECREF(py_obj_attr1); > > The object py_obj_attr1 is said to be a "New reference". It's > confusing, does it refer to the same object as "obj.attr1" in python's > term? So that the above code equals: obj.attr1.attr2 = 'a' in python's > term. > > I From paddy3118 at netscape.net Thu Jan 11 08:37:38 2007 From: paddy3118 at netscape.net (Paddy) Date: 11 Jan 2007 05:37:38 -0800 Subject: dot operations In-Reply-To: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> References: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> Message-ID: <1168522658.128216.199310@77g2000hsv.googlegroups.com> jm.suresh at no.spam.gmail.com wrote: > Hi, > Frequently I get to do like this: > a = (1, 2, 3, 4) # some dummy values > b = (4, 3, 2, 1) > import operator > c = map(operator.add, a, b) > > I am finding the last line not very readable especially when I combine > couple of such operations into one line. Is it possible to overload > operators, so that, I can use .+ for element wise addition, as, > c = a .+ b > which is much more readable. > > Similarly, I want to use .- , .*, ./ . Is it possible to do? > > thanks. > > - > Suresh List comprehensions? >>> a = (1, 2, 3, 4) >>> b = (4, 3, 2, 1) >>> import operator >>> c = map(operator.add, a, b) >>> c [5, 5, 5, 5] >>> c1 = [a1+b1 for a1,b1 in zip(a,b)] >>> c1 [5, 5, 5, 5] >>> - Paddy. From metaperl at gmail.com Fri Jan 19 10:33:19 2007 From: metaperl at gmail.com (metaperl) Date: 19 Jan 2007 07:33:19 -0800 Subject: PyMeld for html templates? In-Reply-To: References: Message-ID: <1169220799.498403.168500@51g2000cwl.googlegroups.com> Sean Schertell wrote: > > Of course I'm going to try them all but I wonder if anyone has any > thoughts on PyMeld as a template system for churning out general > websites? > meld3 evolved from pymeld. I use meld3 - http://plope.com/software/meld3/ this whole style of templating is known as push-style (coined by Terence Parr). Most systems are pull-style. > sorted. But how about PyMeld, any ideas on how to do it or whether it > will even work as I've described? > the meat and bread problem: each page has meat and you want to wrap it with some standard bread. it's a basic tree rewrite and since meld3 uses ElementTree underneath, it is a piece of cake. From paul at boddie.org.uk Mon Jan 8 06:28:24 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 8 Jan 2007 03:28:24 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> <7xlkke19he.fsf@ruckus.brouhaha.com> <7xirfiyn3y.fsf@ruckus.brouhaha.com> Message-ID: <1168255704.559027.36020@s80g2000cwa.googlegroups.com> Steven D'Aprano wrote: > > The truth of the matter is, MyClass.__private is not private at all. It is > still a public attribute with a slightly unexpected name. In other words, > if you want to code defensively, you should simply assume that Python has > no private attributes, and code accordingly. > > Problem solved. Well, it isn't really solved - it's more avoided than anything else. ;-) Still, if one deconstructs the use of private data in various programming languages, one can identify the following roles (amongst others): 1. The prevention of access to data from program sections not belonging to a particular component. (The classic "keep out" mechanism.) 2. The enforcement of distinct namespaces within components. (Making sure that subclass attributes and superclass attributes can co-exist.) 3. To support stable storage layouts and binary compatibility. Most Python adherents don't care too much about #1, and Python isn't driven by the need for #3, mostly due to the way structures (modules, classes, objects) are accessed by the virtual machine. However, one thing which does worry some people is #2, and in a way it's the forgotten but more significant benefit of private data. Before I became completely aware of the significance of #2, I remember using various standard library classes which are meant to be subclassed and built upon, thinking that if I accidentally re-used an attribute name then the operation of such classes would be likely to fail in fairly bizarre ways. Of course, a quick browse of the source code for sgmllib.SGMLParser informed me of the pitfalls, and I'm sure that various tools could also be informative without the need to load sgmllib.py into a text editor, but if I had been fully aware of the benefits of private attributes and could have been sure that such attributes had been used (again, a tool might have given such assurances) then I wouldn't have needed to worry. So I suppose that to "code accordingly" in the context of your advice involves a manual inspection of the source code of superclasses or the usage of additional tools. Yet I suppose that this isn't necessarily unusual behaviour when working with large systems. Paul From gagsl-py at yahoo.com.ar Sat Jan 20 16:41:42 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Jan 2007 18:41:42 -0300 Subject: python packages and __name__ query. References: Message-ID: "krishnakant Mane" escribi? en el mensaje news:f81479dd0701201112i7f443c17w588ea3f6f7fc7d42 at mail.gmail.com... > I use cx freze for creating a python executable. cx_freeze is almost irrelevant here; all the following considerations are about your application structure, it doesnt matter if you use cx_freeze later (or any other tool). > my software is > essentially a package containing a few modules and one file where I > created the main() function. > if needed and suggested by experts I may as well put it in my > __init__.py file of the package. No, usually the main function is outside the package. The package is a library, and main() *uses* that library, as a client. > coming back to the point. where do I put the following code > if __name__ == "__main__": > main() I would say, "In the main script, obviously :)" But since you're asking it may not be so obvious... It appears that your main script is exec.py - so there should be it. I suppose you run your application this way: exec.py -some -options file.ext (perhaps a bare exec.py is enough) so using the idiom above, inside exec.py you can detect when someone is running it as a script. > I have 5 modules in my package each doing a specific task. > and a file that contains the main() function. the 5 modules and the > exec.py file all are in the same package. if it is a wrong practice > please correct me. exec.py is not a good name, since this is the "public" entry point to your application, and should be more meaningful. Usually it is not inside the package, just uses it. I suggest you look into other Python applications, to see how they are layered. -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 26 03:50:14 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 26 Jan 2007 09:50:14 +0100 Subject: stop script w/o exiting interpreter In-Reply-To: References: Message-ID: <45b9c0bc$0$29540$426a74cc@news.free.fr> Alan Isaac a ?crit : > I'm fairly new to Python and I've lately been running a script at > the interpreter while working on it. Sometimes I only want to > run the first quarter or half etc. What is the "good" way to do this? If the point is to debug your script, then import pdb; pdb.set_trace() > Possible ugly hacks include: > > - stick an undefined name at the desired stop point > - comment out the last half > > I do not like these and assume that I have overlooked the obvious. If you have much of your code in functions/classes etc, and the bare minimum[1] at the top level, then you can launch a Python shell, import your module, and test functions as you wish... [1]: import XXX import YYY # lots of functions/classes etc def main(argv): # what would have been at the top level if __name__ == __main__: import sys sys.exit(main(sys.argv)) From tsuraan at gmail.com Mon Jan 8 11:55:24 2007 From: tsuraan at gmail.com (tsuraan) Date: Mon, 8 Jan 2007 10:55:24 -0600 Subject: Suitability for long-running text processing? In-Reply-To: References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> Message-ID: <84fb38e30701080855x4cc809ddh7c0cf2d2e0e83520@mail.gmail.com> > $ python > Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> # Python is using 2.7 MiB > ... a = ['1234' for i in xrange(10 << 20)] > >>> # Python is using 42.9 MiB > ... del a > >>> # Python is using 2.9 MiB > > With 10,485,760 strings of 4 chars, it still works as expected. Have you tried running the code I posted? Is there any explanation as to why the code I posted fails to ever be cleaned up? In your specific example, you have a huge array of pointers to a single string. Try doing "a[0] is a[10000]". You'll get True. Try "a[0] is '1'+'2'+'3'+'4'". You'll get False. Every element of a is a pointer to the exact same string. When you delete a, you're getting rid of a huge array of pointers, but probably not actually losing the four-byte (plus gc overhead) string '1234'. So, does anybody know how to get python to free up _all_ of its allocated strings? -------------- next part -------------- An HTML attachment was scrubbed... URL: From will at willmcgugan.com Wed Jan 17 07:41:02 2007 From: will at willmcgugan.com (Will McGugan) Date: 17 Jan 2007 04:41:02 -0800 Subject: generate tuples from sequence Message-ID: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Hi, I'd like a generator that takes a sequence and yields tuples containing n items of the sqeuence, but ignoring the 'odd' items. For example take_group(range(9), 3) -> (0,1,2) (3,4,5) (6,7,8) This is what I came up with.. def take_group(gen, count): i=iter(gen) while True: yield tuple([i.next() for _ in xrange(count)]) Is this the most efficient solution? Regards, Will McGugan -- http://www.willmcgugan.com From jm.suresh at gmail.com Thu Jan 11 09:06:39 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: 11 Jan 2007 06:06:39 -0800 Subject: dot operations In-Reply-To: <1168522658.128216.199310@77g2000hsv.googlegroups.com> References: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> <1168522658.128216.199310@77g2000hsv.googlegroups.com> Message-ID: <1168524399.307074.192080@i56g2000hsf.googlegroups.com> Paddy wrote: > jm.suresh at no.spam.gmail.com wrote: > > Hi, > > Frequently I get to do like this: > > a = (1, 2, 3, 4) # some dummy values > > b = (4, 3, 2, 1) > > import operator > > c = map(operator.add, a, b) > > > > I am finding the last line not very readable especially when I combine > > couple of such operations into one line. Is it possible to overload > > operators, so that, I can use .+ for element wise addition, as, > > c = a .+ b > > which is much more readable. > > > > Similarly, I want to use .- , .*, ./ . Is it possible to do? > > > > thanks. > > > > - > > Suresh > > List comprehensions? > > >>> a = (1, 2, 3, 4) > >>> b = (4, 3, 2, 1) > >>> import operator > >>> c = map(operator.add, a, b) > >>> c > [5, 5, 5, 5] > >>> c1 = [a1+b1 for a1,b1 in zip(a,b)] > >>> c1 > [5, 5, 5, 5] > >>> > I just found this from : http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122 class Infix(object): def __init__(self, function): self.function = function def __ror__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __or__(self, other): return self.function(other) def __rlshift__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __rshift__(self, other): return self.function(other) def __call__(self, value1, value2): return self.function(value1, value2) import operator dotplus = Infix(lambda x,y: map(operator.add, x, y)) a = range(4) b = range(4) c = a |dotplus| b > > - Paddy. From gagsl-py at yahoo.com.ar Mon Jan 8 19:46:06 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 08 Jan 2007 21:46:06 -0300 Subject: Network failure when using urllib2 In-Reply-To: <1168302603.565442.113760@v33g2000cwv.googlegroups.com> References: <1168292352.349983.139260@i15g2000cwa.googlegroups.com> <1168301738.984509.3030@38g2000cwa.googlegroups.com> <1168302603.565442.113760@v33g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070108214407.03288130@yahoo.com.ar> At Monday 8/1/2007 21:30, jdvolz at gmail.com wrote: >I am fetching different web pages (never the same one) from a web >server. Does that make a difference with them trying to block me? >Also, if it was only that site blocking me, then why does the internet >not work in other programs when this happens in the script. It is >almost like something is seeing a lot of traffic from my computer, and >cutting it off thinking it is some kind of virus or worm. I am >starting to suspect my firewall. Anyone else have this happen? Perhaps you're not closing connections once finished? Try netstat -an from the command line and see how many open connections you have. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fsckedagain at gmail.com Thu Jan 4 12:14:29 2007 From: fsckedagain at gmail.com (fscked) Date: 4 Jan 2007 09:14:29 -0800 Subject: minidom utf-8 encoding In-Reply-To: <459D2DEF.2060508@v.loewis.de> References: <1167868380.481121.154880@42g2000cwt.googlegroups.com> <459cbbce$0$15834$9b622d9e@news.freenet.de> <1167927887.745869.18260@q40g2000cwq.googlegroups.com> <459D2DEF.2060508@v.loewis.de> Message-ID: <1167930869.836046.86840@42g2000cwt.googlegroups.com> Martin v. L?wis wrote: <...snip...> > I find that hard to believe. There is no code in Python that does > removal of characters, and I can't see any other reason why it gets > removed. > > OTOH, what I do get when writing to a file is a UnicodeError, when > it tries to convert the Unicode string that toxml gives to a byte > string. > > So I recommend you pass encoding="utf-8" to the toprettyxml invocation > also. > > Regards, > Martin OK, now I am really confused. After trying all variations of opening and writing and encoding and all the other voodoo I can find on the web for hours, I decide to put the script back to how it was when it did everything but remove the unicode characters. And now it just works... I hate it when that happens. In case you are wondering here is the code that caused me all this (seemingly odd) pain: import csv import codecs from xml.dom.minidom import Document out = open("test.xml", "w") # Create the minidom document doc = Document() # Create the base element boxes = doc.createElement("boxes") myfile = open('ClientsXMLUpdate.txt') csvreader = csv.reader(myfile) for row in csvreader: mainbox = doc.createElement("box") doc.appendChild(boxes) r2 = csv.reader(myfile) b = r2.next() mainbox.setAttribute("city", b[10]) mainbox.setAttribute("country", b[9]) mainbox.setAttribute("phone", b[8]) mainbox.setAttribute("address", b[7]) mainbox.setAttribute("name", b[6]) mainbox.setAttribute("pl_heartbeat", b[5]) mainbox.setAttribute("sw_ver", b[4]) mainbox.setAttribute("hw_ver", b[3]) mainbox.setAttribute("date_activated", b[2]) mainbox.setAttribute("mac_address", b[1]) mainbox.setAttribute("boxid", b[0]) boxes.appendChild(mainbox) # Print our newly created XML out.write( doc.toprettyxml ()) And it just works... From michele.petrazzoDELETE at DELETEunipex.it Tue Jan 23 03:58:57 2007 From: michele.petrazzoDELETE at DELETEunipex.it (Michele Petrazzo) Date: Tue, 23 Jan 2007 08:58:57 GMT Subject: beep or sound playing under linux In-Reply-To: References: Message-ID: hg wrote: > Hi, > > Is there a way to do that ? I can do it, into my debian, with a: michele:~$ echo -e "\007" >/dev/tty It's very simple to reproduce it with python and os.system or subprocess. Michele From nick at craig-wood.com Mon Jan 22 04:30:09 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 22 Jan 2007 03:30:09 -0600 Subject: mmap caching References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <1169415139.515834.233700@a75g2000cwd.googlegroups.com> Message-ID: George Sakkis wrote: > The file is written once and then opened as read-only, there's no > flushing. So if caching is completely up to the OS, I take it that my > options are either (1) modify my algorithms so that they work in > fixed-size batches instead of arbitrarily long sequences or (2) > implement my own memory-mapping scheme to fit my algorithms. I guess > (1) would be the less trouble overall, or is there a way to give a hint > to the OS on how large cache can it use ? The above behaviour isn't as expected. So either there is something going on in your program that we don't know about or there is a bug somewhere, either in the OS or in python. Can you make a short program to replicate the problem? That will help narrow down the problem. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From greg at cosc.canterbury.ac.nz Fri Jan 26 22:26:48 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 27 Jan 2007 16:26:48 +1300 Subject: ANN: Plex 1.1.5 Message-ID: I have released a small update to Plex to fix the problem of assignment to None causing syntax warnings or errors in Python 2.3 and later. What is Plex? Plex is a Python module for lexical analysis that provides similar functionality to Lex and Flex. -- Greg From steve at REMOVE.THIS.cybersource.com.au Wed Jan 24 16:31:29 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 25 Jan 2007 08:31:29 +1100 Subject: Static variables References: Message-ID: On Wed, 24 Jan 2007 21:48:38 +0100, Florian Lindner wrote: > Hello, > does python have static variables? I mean function-local variables that keep > their state between invocations of the function. There are two ways of doing that (that I know of). The simplest method is by having a mutable default argument. Here's an example: def foo(x, _history=[]): print _history, x _history.append(x) >>> foo(2) [] 2 >>> foo(3) [2] 3 >>> foo(5) [2, 3] 5 Another method is to add an attribute to the function after you've created it: def foo(x): print foo.last, x foo.last = x foo.last = None >>> foo(3) None 3 >>> foo(6) 3 6 >>> foo(2) 6 2 But the most powerful method is using generators, which remember their entire internal state between calls. Here's a simple example, one that returns the integers 0, 1, 3, 6, 10, ... def number_series(): increment = 1 n = 0 while True: yield n # instead of return n += increment increment += 1 Notice that in this case there is no exit to the function: it loops forever because the series goes on for ever. If you want to exit the generator, just use a plain return statement (don't return anything), or just exit the loop and fall off the end of the function. This is how we might use it: Create an iterator object from the generator function, and print the first six values: >>> gen = number_series() >>> for i in range(6): print gen.next() ... 0 1 3 6 10 15 Sum the values from the current point up to 100: >>> s = 0 >>> n = gen.next() >>> n 21 >>> for x in gen: ... if x >= 100: ... break ... n += x ... >>> n 420 Reset the iterator to the start: >>> gen = number_series() For generators that terminate, you can get all the values in one go with this: everything = list(gen) # or everything = list(number_series()) but don't try this on my example, because it doesn't terminate! -- Steven. From carsten at uniqsys.com Fri Jan 12 15:22:01 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 12 Jan 2007 15:22:01 -0500 Subject: dynamic argument name for functions In-Reply-To: References: Message-ID: <1168633321.3382.92.camel@dot.uniqsys.com> On Fri, 2007-01-12 at 12:17 -0800, mark wrote: > I want to pass a value to an argument of a function. The argument name > is dynamic and is stored in a > variable. How do I call the function using with arg_name and value as > the parameters. > thanks > mark > > For ex: > def function(arg1='None', arg2='None', arg3='None'): > print arg1 > print arg2 > print arg3 > > > arg_name = 'arg1' > arg_value = 'i am passing a value to argument 1' > function(???????) function(**{arg_name: arg_value}) -Carsten From bdesth.quelquechose at free.quelquepart.fr Fri Jan 12 18:00:20 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Jan 2007 00:00:20 +0100 Subject: Tools Designing large/complicated applications In-Reply-To: References: Message-ID: <45a80c9e$0$308$426a74cc@news.free.fr> Carl J. Van Arsdall a ?crit : > For those of you that work on larger applications but still code in > python... do your development teams use any tools to facilitate the > design? Yes : coffee, beer, pizzas, cigarettes, paper napkins, pen, and a good wiki. > (i'm not asking about editors here, i'm really asking about > software design tools) > Thanks! HTH From ktenney at gmail.com Sun Jan 28 09:28:00 2007 From: ktenney at gmail.com (Kent Tenney) Date: 28 Jan 2007 06:28:00 -0800 Subject: Problems with ElementTree and ProcessingInstruction Message-ID: <1169994480.424321.51600@m58g2000cwm.googlegroups.com> Howdy, I want to generate the following file; stuff How should I be doing this? As far as I can tell, ElementTree() requires everything to be inside the root element (leo_file) Thanks, Kent From bthom at cs.hmc.edu Fri Jan 5 03:40:44 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Fri, 05 Jan 2007 00:40:44 -0800 Subject: checking one's type Message-ID: Hi, I've been using the following hack to determine if a type is acceptable and I suspect there is a better way to do it: e.g. if type(s) == type("") : print "okay, i'm happy you're a string" If anyone knows a better way, I'm all ears. Thanks, --b From fdelente at mail.cpod.fr Sat Jan 27 03:59:03 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 27 Jan 2007 08:59:03 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> <12rl5mq4nnqoea0@corp.supernews.com> <45bafda7$0$2417$426a74cc@news.free.fr> <45bb02bf$0$26684$426a34cc@news.free.fr> Message-ID: <45bb1457$0$25908$426a34cc@news.free.fr> > Try "export LINES COLUMNS" to set them as environment variables. Thanks, it works. Didn't know that. -- Fabrice DELENTE From cyberco at gmail.com Thu Jan 11 03:59:31 2007 From: cyberco at gmail.com (cyberco) Date: 11 Jan 2007 00:59:31 -0800 Subject: The Python Papers: Submit your Quotes In-Reply-To: <1168492949.830615.131350@o58g2000hsb.googlegroups.com> References: <1168492949.830615.131350@o58g2000hsb.googlegroups.com> Message-ID: <1168505970.905216.38400@77g2000hsv.googlegroups.com> "Like silence in music, whitespace is where Python Power shows" "The odd thing is that Python results in what I call YoYo-code. After writing some code I always discover a shorter, more elegant and more readable way of doing the same thing in Python. The same happens after adding more functionality. This goes on indefinitely, resulting in a piece of code whose length YoYo's over time" "Python's power is that it is fitted for both simple and complex tasks. You're not bothered with the restrictions that are only relevant when building complex systems if you just want to do something simple" - Berco Beute "Jack of all trades, master as well" - Berco Beute From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 12 20:00:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 13 Jan 2007 02:00:49 +0100 Subject: modules...n methods References: <1168620496.520506.296330@q2g2000cwa.googlegroups.com> <50pst9F1h5hj5U1@mid.individual.net> Message-ID: <50qpa1F1h80tbU1@mid.individual.net> belinda thom wrote: > This becomes a lot easier if you use IPython (which embellishes > the python shell in many useful ways). For instance, I did a "dir > (__builtins__)" to find out what some of the builtin functions > were. Sure. > HTH I'm sorry, it doesn't help me. And *please* don't send mail copies to me. Regards, Bj?rn -- BOFH excuse #14: sounds like a Windows problem, try calling Microsoft support From http Wed Jan 24 22:11:59 2007 From: http (Paul Rubin) Date: 24 Jan 2007 19:11:59 -0800 Subject: My Tkinter Threading nightmare References: <1169693266.209082.323310@a75g2000cwd.googlegroups.com> Message-ID: <7x1wljajgg.fsf@ruckus.brouhaha.com> half.italian at gmail.com writes: > and setup the callback to kill the operation and then the window when > the user clicks on the X of the progress window. I've implemented this > in my code, but clicking on the X does nothing until I kill the main > thread (i think), and then my callback is run. I've also had problems > in the past of the gui not refreshing properly, which leads me to > believe that both of these are thread related. Any help would be > immensely appreciated. That was more code than I was willing to sit and read, but basically the tkinter thread blocks unless there's tkinter events. The usual trick for what you're trying to do is to set up a tk.after event to run every 20 msec or so. That can check for commands on a queue to launch operations, kill windows, or whatever. In your Window class you'd have something like (this is pseudocode, I don't remember the exact params and args off the top of my head so you'll have to check them): def __init__(self, ...): ... self.after(20, self.idle) def idle(self): # read and execute any commands waiting on the queue while True: try: func, args, kw = self.cmd_queue.get(block=False) except QueueEmpty: return func (*args, **kw) cmd_queue is a queue that you set up ahead of time, and you use it to send commands into your gui thread from other threads, such as window kill. Don't call gui functions directly as tkinter is not thread-safe. From pwatson at redlinepy.com Wed Jan 3 14:24:17 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 03 Jan 2007 13:24:17 -0600 Subject: Cannot build 2.5 on FC6 x86 Message-ID: <502e72F1eh7ngU1@mid.individual.net> ./configure make make test The result appears to hang after the test_tkl... line. I had to kill the 'make test' process which terminated it. Any suggestions? 280 tests OK. 4 tests failed: test_optparse test_socket test_socket_ssl test_urllib2 35 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_bsddb3 test_cd test_cl test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_curses test_gl test_imgfile test_linuxaudiodev test_logging test_macfs test_macostools test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_scriptpackages test_socketserver test_startfile test_sunaudiodev test_tcl test_timeout test_urllib2net test_urllibnet test_winreg test_winsound test_zipfile64 2 skips unexpected on linux2: test_tcl test_logging make: *** [test] Terminated Terminated From Thomas.Ploch at gmx.net Fri Jan 12 15:00:41 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 12 Jan 2007 21:00:41 +0100 Subject: Rational Numbers In-Reply-To: <8c7f10c60701121134q35bf7c27h7c4b5cf1dcfe44ca@mail.gmail.com> References: <8c7f10c60701121134q35bf7c27h7c4b5cf1dcfe44ca@mail.gmail.com> Message-ID: <45A7E8E9.8060105@gmx.net> Simon Brunning schrieb: > On 12 Jan 2007 15:55:39 GMT, Nick Maclaren wrote: >> In article , >> Carsten Haese writes: >> |> but there are more use >> |> cases for Decimal than for Rational. >> >> That is dubious, but let's not start that one again. > > Decimals are good for holding financial values. There's a whole lot of > software out there that deals with money. > Do not forget: - Time - Personal Data (like birthdays, age) Thomas From fsckedagain at gmail.com Thu Jan 4 11:24:49 2007 From: fsckedagain at gmail.com (fscked) Date: 4 Jan 2007 08:24:49 -0800 Subject: minidom utf-8 encoding In-Reply-To: <459cbbce$0$15834$9b622d9e@news.freenet.de> References: <1167868380.481121.154880@42g2000cwt.googlegroups.com> <459cbbce$0$15834$9b622d9e@news.freenet.de> Message-ID: <1167927887.745869.18260@q40g2000cwq.googlegroups.com> Martin v. L?wis wrote: > fscked schrieb: > > Hi guys/gals. > > > > I am trying to write and xml file from data parsed from a csv. > > > > I can get everything to work except that I cannot get minidom to do --> > > ? which needless to say is driving me nuts. > > > > Any suggestions? > > Works fine for me: > > py> d = minidom.Document() > py> r = d.createElement("root") > py> r.appendChild(d.createTextNode(u"\xf6")) > > py> d.appendChild(r) > > py> d.toxml() > u'\n\xf6' > py> print d.toxml() > > ? > > Regards, > Martin Well, let me clarify. If I just print it to the screen/console it works fine, but when I do: out.write( doc.toprettyxml()) it just removes the character that would be the "?". I can post the code if anyone wants to see it, but it is fairly straightforward. From mail at microcorp.co.za Wed Jan 10 00:31:36 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 10 Jan 2007 07:31:36 +0200 Subject: Colons, indentation and reformatting. (2) References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com><45a33a24$0$7658$4c368faf@roadrunner.com><1168329449.577659.214890@s34g2000cwa.googlegroups.com> Message-ID: <019c01c7348c$1b90f8e0$03000080@hendrik> "Jorgen Grahn" wrote: > On 8 Jan 2007 23:57:29 -0800, Paddy wrote: > > > > OK, whilst colons are not sufficient to re-format a completely > > mis-indented file. I'm thinking that they are sufficient for > > reformatting most pasted code blocks when refactoring say? > > Let's put it this way: if the formatter can assume the original code is > valid (i.e. has the intended indentation) then it can do all kinds of nifty > things to it. This is true - and I think it will only fail if the "entry" point in the pasted code is "further to the right" than where it has to fit in to the original code - i.e. if you "run out of space" to the left. - but in that case you really are hacking, and you are in urgent need of some slashing... - Hendrik From nocl123 at gmail.com Thu Jan 11 12:09:30 2007 From: nocl123 at gmail.com (nic) Date: 11 Jan 2007 09:09:30 -0800 Subject: os.popen() not executing command on windows xp References: <1168508553.151827.261420@k58g2000hse.googlegroups.com> <1168509560.119819.78470@o58g2000hsb.googlegroups.com> Message-ID: <1168535370.211599.265250@p59g2000hsd.googlegroups.com> Justin Ezequiel wrote: > > import os > > a = os.popen('"c:\Program Files\Grisoft\AVG Free\avgscan.exe" > > "c:\program files\temp1\test1.txt"') > > print a.read() > > > > use raw strings > > e.g., instead of '"c:...\avgscan...' > use r'"c:...\avgscan...' > > http://www.ferg.org/projects/python_gotchas.html#contents_item_2 Sorry I initally had retyped the code to replace some variables to make it more clear, I already had them as raw strings: import os pstr = r'"c:\Program Files\Grisoft\AVG Free\avgscan.exe" "c:\program files\temp1\test1.txt"' a = os.popen(pstr) print a.read() I've confirmed the string I'm inputting to os.popen is EXACTLY the same as the one I can successfully execute manually in command prompt, so when I go: print pstr, it yields: "c:\Program Files\Grisoft\AVG Free\avgscan.exe" "c:\program files\temp1\test1.txt" The problem remains popen won't execute this line as it does when inputted manually to command prompt. From laurent.pointal at limsi.fr Tue Jan 23 03:53:55 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 23 Jan 2007 09:53:55 +0100 Subject: Removing outdated files In-Reply-To: <45b59949@griseus.its.uu.se> References: <45b59949@griseus.its.uu.se> Message-ID: Jan Danielsson a ?crit : > Hello all, > > I have a backup system which produces files using the following pattern: ... > > Obviously, I have little need for *all* those files. What I want to > do is to delete old files according to this pattern: > > - Keep all backup files which are two weeks, or less, old > - If backups are more than two weeks old, then keep only the latest > one for each week. > - If backups are more than two months old, then keep only the latest > one for each month. > - If backups are more than two years old, then keep only the latest > one for each year. You should take a look at snapy, AFAIR it does things like this to manage snapshot backups (with cp [+rsync] [+ssh]). http://www.flibuste.net/libre/snapy/ From yinglcs at gmail.com Mon Jan 22 17:05:16 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 22 Jan 2007 14:05:16 -0800 Subject: How to use time.clock() function in python Message-ID: <1169503516.425217.218790@q2g2000cwa.googlegroups.com> Hi, I am following this python example trying to time how long does an operation takes, like this: My question is why the content of the file (dataFile) is just '0.0'? I have tried "print >>dataFile, timeTaken" or "print >>dataFile,str( timeTaken)", but gives me 0.0. Please tell me what am I missing? t1 = time.clock() os.system(cmd) outputFile = str(i) + ".png" t2 = time.clock() timeTaken = t2 - t1 allTimeTaken += timeTaken print >>dataFile, timeTaken From paul at boddie.org.uk Fri Jan 12 07:13:33 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Jan 2007 04:13:33 -0800 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: <1168604013.854051.61940@51g2000cwl.googlegroups.com> robert wrote: > Paul Boddie wrote: > > > > [1] http://www.python.org/pypi/parallel > > I'd be interested in an overview. I think we've briefly discussed the above solution before, and I don't think you're too enthusiastic about anything using interprocess communication, which is what the above solution uses. Moreover, it's intended as a threading replacement for SMP/multicore architectures where one actually gets parallel execution (since it uses processes). > For ease of use a major criterion for me would be a pure python > solution, which also does the job of starting and controlling the > other process(es) automatically right (by default) on common > platforms. > Which of the existing (RPC) solutions are that nice? Many people have nice things to say about Pyro, and there seem to be various modules attempting parallel processing, or at least some kind of job control, using that technology. See Konrad Hinsen's ScientificPython solution for an example of this - I'm sure I've seen others, too. Paul From mhellwig at xs4all.nl Fri Jan 19 16:31:27 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Fri, 19 Jan 2007 22:31:27 +0100 Subject: How to comment code? Message-ID: <45b13876$0$323$e4fe514c@news.xs4all.nl> Hi all, I've been toying with python for about two years now. Not every day, just when I encounter something in my job (sysadmin) repetitively dull. The amazing thing is that like any other language (natural or not) learning it more gives you power to express your thoughts better and create something from nothing, for me this is something I can only compare to freedom. However since I'm learning more of python I've struggled with commenting, how should I've comment my code? I'm not talking about the style but more on the concept itself, things that where a couple of month ago a bunch of monkey poop is now as easy as reading a comic. I always give a brief description on what the code is supposed to do and I suppose that any serious coder knows way more then me about programming so I don't bother to comment that much since it mostly (in my eyes) just clutters up the code and makes it actually harder to read. Though this makes me uncomfortably, commenting so little, I was thinking that perhaps something like doctest (I'm not so much into unit testing or the equivalents at this moment) has the side affect to make my code more understandable and readable. Any practical experience you'd like to share with me, any other comments are welcome too of course :-) Thanks. -- mph From danb_83 at yahoo.com Mon Jan 8 19:19:05 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 8 Jan 2007 16:19:05 -0800 Subject: Maths error In-Reply-To: References: Message-ID: <1168301945.854331.95920@s80g2000cwa.googlegroups.com> On Jan 8, 3:30 pm, Rory Campbell-Lange wrote: > >>> (1.0/10.0) + (2.0/10.0) + (3.0/10.0) > 0.60000000000000009 > >>> 6.0/10.0 > 0.59999999999999998 > > Is using the decimal module the best way around this? (I'm expecting the first > sum to match the second). Probably not. Decimal arithmetic is NOT a cure-all for floating-point arithmetic errors. >>> Decimal(1) / Decimal(3) * Decimal(3) Decimal("0.9999999999999999999999999999") >>> Decimal(2).sqrt() ** 2 Decimal("1.999999999999999999999999999") > It seem anachronistic that decimal takes strings as > input, though. How else would you distinguish Decimal('0.1') from Decimal('0.1000000000000000055511151231257827021181583404541015625')? From kmsmgill at gmail.com Fri Jan 19 08:48:33 2007 From: kmsmgill at gmail.com (kmsmgill at gmail.com) Date: 19 Jan 2007 05:48:33 -0800 Subject: how to mimik a main() function to start a program with entry point? References: Message-ID: <1169214513.910651.29280@l53g2000cwa.googlegroups.com> def main(): print "Hello" if __name__ == "__main__": main() Simply verify __name__ and run any function from there. This will cause main() to be run if the script is run directly. I haven't used py2exe, so I'm not sure if it still applies. --Kevin krishnakant Mane wrote: > hello all. > I have one simple query and may be that's to stupid to answer but I am > not finding the answer any ways. > I have a set of modules in my package and out if which one is my > actual starting point to my entire program. say for example I have an > entire database application ready and I want a main (as in java or c) > to initiate the program and may be bring up a login screen and then > pass the control on to the main window. > if I am giving raw source code that is easy because I will tell user > to run the command ./xyz.py which has that function. > but if I freze it into an executable with py2exe for example , how do > I solve this problem? > thanks. > Krishnakant. From no-spam at no-spam-no-spam.invalid Thu Jan 11 05:41:33 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Thu, 11 Jan 2007 11:41:33 +0100 Subject: dot operations In-Reply-To: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> References: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> Message-ID: jm.suresh at no.spam.gmail.com wrote: > Hi, > Frequently I get to do like this: > a = (1, 2, 3, 4) # some dummy values > b = (4, 3, 2, 1) > import operator > c = map(operator.add, a, b) > > I am finding the last line not very readable especially when I combine > couple of such operations into one line. Is it possible to overload > operators, so that, I can use .+ for element wise addition, as, > c = a .+ b > which is much more readable. > > Similarly, I want to use .- , .*, ./ . Is it possible to do? import numpy You'll not even need dots From news at grauer-online.de Fri Jan 5 09:30:10 2007 From: news at grauer-online.de (Uwe Grauer) Date: Fri, 05 Jan 2007 15:30:10 +0100 Subject: C/C++, Perl, etc. to Python converter In-Reply-To: References: Message-ID: <459E60F2.4000600@grauer-online.de> mm wrote: > > Is there a Perl to Python converter? > Or in general: a XY to Python converter? > > Is see, that Python is much better then Perl anyway. > But for beginners, they whant to konw how is this done with Python etc. > > Sure, there are some docus out there in the internet. But a converter? Maybe this can help in converting from prel to python: http://www.crazy-compilers.com/bridgekeeper/ Uwe From bj_666 at gmx.net Wed Jan 10 02:55:30 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 10 Jan 2007 08:55:30 +0100 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) References: <2BBAEE949D384D40A2B851287ADB6A4304595A6D@eugsrv400.psc.pscnet.com> <7.0.1.0.0.20070109203637.0422acb8@yahoo.com.ar> Message-ID: In , Julio Biason wrote: > If I use a file() in a for, how to I explicitely close the file? > > > for line in file('contents'): > print line > > > Would this work like the new 'with' statement or it will only be closed > when the GC finds it? Only when the GC destroys it. Ciao, Marc 'BlackJack' Rintsch From frank at chagford.com Sun Jan 7 04:33:32 2007 From: frank at chagford.com (Frank Millman) Date: 7 Jan 2007 01:33:32 -0800 Subject: How to invoke parent's method? In-Reply-To: <1168138626.574514.102060@i15g2000cwa.googlegroups.com> References: <1168138626.574514.102060@i15g2000cwa.googlegroups.com> Message-ID: <1168162412.253449.296520@38g2000cwa.googlegroups.com> many_years_after wrote: > Hi, pythoners: > > My wxPython program includes a panel whose parent is a frame. The > panel has a button. When I click the button , I want to let the frame > destroy. How to implement it? Could the panel invoke the frame's > method? > Thanks. Have a look at the following program - ---------------------------------------------------------------------- class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) MyPanel(self) class MyPanel(wx.Panel): def __init__(self,frame): wx.Panel.__init__(self,frame,-1) self.frame = frame b = wx.Button(self,-1,'Close') b.Bind(wx.EVT_BUTTON,self.onClose,id=b.GetId()) def onClose(self,evt): self.frame.Close() evt.Skip() class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, "Test") frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) # Create an instance of the application class app.MainLoop() # Tell it to start processing events ---------------------------------------------------------------------- The essential point is that you save a reference to the frame when you create the panel. Then when the button is clicked you can use the reference to call the frame's Close method. HTH Frank Millman From codecraig at gmail.com Tue Jan 9 10:01:31 2007 From: codecraig at gmail.com (abcd) Date: 9 Jan 2007 07:01:31 -0800 Subject: Determine an object is a subclass of another In-Reply-To: <1168353975.285391.212350@m30g2000cwm.googlegroups.com> References: <1168353205.066357.39530@42g2000cwt.googlegroups.com> <1168353975.285391.212350@m30g2000cwm.googlegroups.com> Message-ID: <1168354891.334807.58940@s80g2000cwa.googlegroups.com> yea i meant to have animal extend thing and dog extend animal....my mistake. anyways, is there a way to check without having an instance of the class? such as, isinstance(Dog, (Animal, Thing)) ?? thanks From heikki at osafoundation.org Fri Jan 12 20:01:04 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 12 Jan 2007 17:01:04 -0800 Subject: More M2Crypto issues. Not big ones, though. In-Reply-To: References: Message-ID: <3JGdnb2VxN7PsjXYnZ2dnUVZ_hydnZ2d@comcast.com> John Nagle wrote: > A list of small problems and bugs in the current M2Crypto: > I need to look at SSL certificates in some detail, so this > is all about the access functions for certificates. Thanks, got the reports, will check them out. > 3. /M2Crypto/SSL/Connection.py:147: > DeprecationWarning: Old style callback, use cb_func(ok, store) > instead return m2.ssl_connect(self.ssl) > (Also reported, in Polish, here: > http://www.mail-archive.com/pld-devel-pl at lists.pld-linux.org/msg12433.html) > Entered into Bugzilla as #7718. This is actually intended. Once I figure out how to implement all the functionality in the new way I'd like to remove the old way. > > 4. "close()" on an SSL socket that's just finished certificate > negotiation hangs, at least on Windows. "del" does not hang, > but I don't know if there's a leak problem. > Not enough info yet to file a bug report. I might be doing > something wrong there. Any known "close" issues? No known issues, but the ending of an SSL connection is a little grey area to me so I wouldn't be surprised if there are some cases where we shut down prematurely or too late. But I don't know why we'd hang. > 1. X509.X509_name.__getattr__: > Field retrieval from X.509 name items with x509_name_by_nid > retrieves only first instance of field, not all instances. Yes, I've been battling with this myself as well. OpenSSL provides objects to get things as a list, but they are so weird I haven't yet figured out a way to wrap them in Python so that you would actually be able to get some values out. > 2. Unclear if M2Crypto's X.509 interface is UTF-8 compatible. > OpenSSL will return info in UTF-8 if you use the > ASN1_STRFLGS_UTF8_CONVERT flag on as_text, but unclear if the > M2 glue code handles this correctly. Haven't found a UTF8 cert > to test it on yet. Yeah, I am not convinced everything works as it should. Any UTF8 (and other encoding) samples would be welcome. > Other than that, I'm having relatively good results with M2Crypto. Glad to hear. -- Heikki Toivonen From fredrik at pythonware.com Wed Jan 10 09:48:16 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Jan 2007 15:48:16 +0100 Subject: An iterator with look-ahead References: Message-ID: Neil Cerutti wrote: > For use in a hand-coded parser I wrote the following simple > iterator with look-ahead. I haven't thought too deeply about what > peek ought to return when the iterator is exhausted. Suggestions > are respectfully requested. As it is, you can't be sure what a > peek() => None signifies until the next iteration unless you > don't expect None in your sequence. if you're doing simple parsing on an iterable, it's easier and more efficient to pass around the current token and the iterator's next method: http://online.effbot.org/2005_11_01_archive.htm#simple-parser-1 From gavcomedy at gmail.com Fri Jan 12 01:42:47 2007 From: gavcomedy at gmail.com (gavino) Date: 11 Jan 2007 22:42:47 -0800 Subject: FUCK YOU Jerub on #python, you desynced me for no good reason Message-ID: <1168584166.949097.233620@11g2000cwr.googlegroups.com> I can't fucking believe this guy. The chat was jsut getting interesting about epoll on linux and twisted moduel for it and he desyncs me. FUCK JERUB complete fucking asshole!! From horpner at yahoo.com Wed Jan 10 13:06:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Jan 2007 19:06:39 +0100 Subject: An iterator with look-ahead References: Message-ID: On 2007-01-10, Steven Bethard wrote: > Neil Cerutti wrote: >> For use in a hand-coded parser I wrote the following simple >> iterator with look-ahead. > > There's a recipe for this: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 > > Note that the recipe efficiently supports an arbitrary > look-ahead, not just a single item. > >> I haven't thought too deeply about what peek ought to return >> when the iterator is exhausted. Suggestions are respectfully >> requested. > > In the recipe, StopIteration is still raised on a peek() > operation that tries to look past the end of the iterator. That was all I could think of as an alternative, but that makes it fairly inconvenient to use. I guess another idea might be to allow user to provide a "no peek" return value in the constructor, if they so wish. -- Neil Cerutti From deets at nospam.web.de Fri Jan 26 03:55:09 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 26 Jan 2007 09:55:09 +0100 Subject: Prefered install method? In-Reply-To: References: Message-ID: <51tu02F1lqdjbU1@mid.uni-berlin.de> Tina I schrieb: > Another noob question: > I have written my first linux application that might actually be of > interest to others. Just for fun I also wrote an install script that put > the files in the common directories for my distro (Debian). That is in > /usr/local/. (This particular program can be run directly from the > user's /home but as a learning experience I want to do it the 'coorect' > way) > > Now, I don't know if that is the way to do it with python applications. > I also don't know if a custom install script is the norm. I have seen > some use of makefiles and tried to find something about it but the > manual for GNUMake really assume you are familiar with/ using C which > I'm not. I have googled a lot for this but can't really find anything > aimed for someone just learning programming with Python. > > So my question is; What is the preferred/ common way to install a python > application so it's not really distro specific? And are there any good > resources on this on the web? These days, it's setuptools. Google for it. It will let you distribute your application in a convenient way as so-called EGG (basically a ZIP-file), additionally you will get support for installing scripts in /usr/bin or wherever you like, and you have versioning support. If you plan to release the app publically, it will also handle the upload to the PyPI, the python package index - also known(?) as cheeseshop. Diez From deacon.sweeney at gmail.com Fri Jan 26 16:35:20 2007 From: deacon.sweeney at gmail.com (deacon.sweeney at gmail.com) Date: 26 Jan 2007 13:35:20 -0800 Subject: Resizing widgets in text windows Message-ID: <1169847315.631951.295830@a75g2000cwd.googlegroups.com> Hi, I've been searching for a .resize()-like function to overload much like can be done for the delete window protocol as follows: toplevel.protocol("WM_DELETE_WINDOW", callback) I realize that the pack manager usually handles all of the resize stuff, but I've found an arrangement that the pack manager fails for. That is, if one embeds a canvas into a window created inside a text widget, then resize the text widget (via its container), the canvas and its container windows do not resize. So I need to resize the window that the canvas is embedded in. The most obvious way of doing this would be as above, but there does not seem to be an equivalent to the "WM_DELETE_WINDOW" protocol for resizing. Any help would be greatly appreciated. Deacon Sweeney From bearophileHUGS at lycos.com Mon Jan 1 20:01:18 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Jan 2007 17:01:18 -0800 Subject: Writing more efficient code In-Reply-To: <459989ec$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> References: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> <1167687229.430930.197720@v33g2000cwv.googlegroups.com> <459989ec$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1167699678.310643.140480@n51g2000cwc.googlegroups.com> Jon Harrop: > I think most people could pick up the core ideas in a day and start writing > working programs. Probably I am not that intelligent, I probably need some months :-) But that language has many good sides, and one day I'll probably try to learn it a bit. > Mathematica is expensive but learning to use pattern matching is much easier > than learning how to write a pattern matcher and much less tedious than > reimplementing it yourself all the time (which is exactly what the OP will > end up doing). I see. This is a very old post of mine, at the bottom there are few notes about the Mathematica pattern matching syntax: http://groups.google.com/group/comp.lang.python/msg/93ce3e9a08f5e4c7 To avoid reimplementing it yourself all the time then maybe someone (you?) can try to write a good pattern matcher for sequences for CPython. With such system it may become less important to switch to a different language ;-) Bye, bearophile From tiedon_jano at hotmail.com Sat Jan 6 17:01:12 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Sat, 06 Jan 2007 22:01:12 GMT Subject: still struggling, howto use a list-element as a name ? In-Reply-To: <45a01981$0$296$426a74cc@news.free.fr> References: <45a01981$0$296$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers kirjoitti: > Stef Mientki a ?crit : >> In the example below, "pin" is an object with a number of properties. >> Now I want >> 1- an easy way to create objects that contains a number of these "pin" >> 2- an multiple way to access these "pin", i.e. >> device.pin[some_index] >> device.some_logical_name >> ad 1: >> a dictionary (as "pinlist" in the example) seems a very convenient >> way (from a viewpoint of the device creator). >> As you can see in the "__init__" section this dictionary can easily be >> transported to the pin-objects. >> >> ad 2: >> THAT's the problem: how do automate these lines "self.GND = self.pin[0]" >> >> I'm also in for other solutions. > > I'm afraid I don't understand your design (nor the domain FWIW). ditto > > > But the whole thing still looks awfully convulted and kludgy to me, and > I suspect serious design flaws... Why don't you try and explain your > real problem, instead of asking how to implement what you *think* is the > solution ? ditto Cheers, Jussi From fdelente at mail.cpod.fr Sat Jan 27 02:36:13 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 27 Jan 2007 07:36:13 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> <12rl5mq4nnqoea0@corp.supernews.com> <45bafda7$0$2417$426a74cc@news.free.fr> Message-ID: <45bb00ec$0$30487$426a34cc@news.free.fr> To really be sure that the problem is when I use python, I tried in C: #include #include int main(void) { initscr(); /* Start curses mode */ // printw("???o?"); /* Print Hello World */ addstr("???o?"); /* Print Hello World */ refresh(); /* Print it on to the real screen */ getch(); /* Wait for user input */ endwin(); /* End curses mode */ return(0); } and both my tries (with printw, or with addstr) showed the 8-bot chars correctly. -- Fabrice DELENTE From robert.kern at gmail.com Tue Jan 9 21:32:57 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 20:32:57 -0600 Subject: Read CSV file into an array In-Reply-To: <1168396138.395017.299530@o58g2000hsb.googlegroups.com> References: <1168396138.395017.299530@o58g2000hsb.googlegroups.com> Message-ID: oyekomova wrote: > I would like to know how to read a CSV file with a header ( n columns > of float data) into an array without the header row. Did you read our responses from the last time you asked this question? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bj_666 at gmx.net Tue Jan 9 15:36:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 09 Jan 2007 21:36:18 +0100 Subject: Newbie - converting csv files to arrays in NumPy References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> Message-ID: In <1168373279.943232.228160 at o58g2000hsb.googlegroups.com>, oyekomova wrote: > I would like to know how to convert a csv file with a header row into a > floating point array without the header row. Take a look at the `csv` module in the standard library. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Fri Jan 5 10:34:31 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 05 Jan 2007 16:34:31 +0100 Subject: Encoding / decoding strings References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> <1168010144.000928.131920@42g2000cwt.googlegroups.com> Message-ID: In <1168010144.000928.131920 at 42g2000cwt.googlegroups.com>, oliver at obeattie.com wrote: > Basically, I want to encode an email address so that it looks something > like 8d2e23c0a835598510c88a758c6b215a - this way the user does not know > the email address they are looking at. They are public-facing views and > they are to get info about other users, therefore anonymity is > important. > > Any suggestions? Don't deliver encoded e-mail addresses to other users. They might decode them and the anonymity is gone. What exactly are you trying to do? Why should users see encrypted e-mail addresses of others? Ciao, Marc 'BlackJack' Rintsch From gnewsg at gmail.com Thu Jan 11 05:52:41 2007 From: gnewsg at gmail.com (billie) Date: 11 Jan 2007 02:52:41 -0800 Subject: sleep in asyncore Message-ID: <1168512761.621361.258180@o58g2000hsb.googlegroups.com> Hi all. I'm writing an authentication server by using asyncore / asynchat modules. I'd like to implement a basic brute-force protection by "freezing / sleeping" the current client session for a period of time (e.g. 2 seconds) when the user sends a wrong password. Does someone knows a "trick" to do that with asyncore? Thanks in advance for your helping. From paddy3118 at netscape.net Tue Jan 9 02:57:29 2007 From: paddy3118 at netscape.net (Paddy) Date: 8 Jan 2007 23:57:29 -0800 Subject: Colons, indentation and reformatting. (2) In-Reply-To: <45a33a24$0$7658$4c368faf@roadrunner.com> References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> <45a33a24$0$7658$4c368faf@roadrunner.com> Message-ID: <1168329449.577659.214890@s34g2000cwa.googlegroups.com> OK, whilst colons are not sufficient to re-format a completely mis-indented file. I'm thinking that they are sufficient for reformatting most pasted code blocks when refactoring say? - Paddy. From harvey.thomas at informa.com Fri Jan 19 05:45:54 2007 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 19 Jan 2007 02:45:54 -0800 Subject: Match 2 words in a line of file References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> <1169172954.107365.133950@51g2000cwl.googlegroups.com> <1169175299.490994.244700@51g2000cwl.googlegroups.com> Message-ID: <1169203554.455579.243560@11g2000cwr.googlegroups.com> Rickard Lindberg wrote: > I see two potential problems with the non regex solutions. > > 1) Consider a line: "foo (bar)". When you split it you will only get > two strings, as split by default only splits the string on white space > characters. Thus "'bar' in words" will return false, even though bar is > a word in that line. > > 2) If you have a line something like this: "foobar hello" then "'foo' > in line" will return true, even though foo is not a word (it is part of > a word). Here's a solution using re.split: import re import StringIO wordsplit = re.compile('\W+').split def matchlines(fh, w1, w2): w1 = w1.lower() w2 = w2.lower() for line in fh: words = [x.lower() for x in wordsplit(line)] if w1 in words and w2 in words: print line.rstrip() test = """1st line of text (not matched) 2nd line of words (not matched) 3rd line (Word test) should match (case insensitivity) 4th line simple test of word's (matches) 5th line simple test of words not found (plural words) 6th line tests produce strange words (no match - plural) 7th line "word test" should find this """ matchlines(StringIO.StringIO(test), 'test', 'word') From exarkun at divmod.com Tue Jan 16 09:11:38 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 16 Jan 2007 09:11:38 -0500 Subject: Debugging SocketServer.ThreadingTCPServer In-Reply-To: Message-ID: <20070116141138.11447.663310173.divmod.quotient.18554@ohm> On Tue, 16 Jan 2007 00:23:35 -0500, "Stuart D. Gathman" wrote: >I have a ThreadingTCPServer application (pygossip, part of >http://sourceforge.net/projects/pymilter). It mostly runs well, but >occasionally goes into a loop. How can I get a stack trace of running >threads to figure out where the loop is? Is there some equivalent of >sending SIGQUIT to Java to get a thread dump? If needed, I can import pdb >and set options at startup, but there needs to be some external way of >triggering the dump since I can't reproduce it at will. Grab the gdbinit out of Python SVN Misc/ directory. Apply this patch: http://jcalderone.livejournal.com/28224.html Attach to the process using gdb. Make sure you have debugging symbols in your build of Python. Run 'thread apply all pystack'. Jean-Paul From seandavi at gmail.com Wed Jan 10 17:37:29 2007 From: seandavi at gmail.com (Sean Davis) Date: 10 Jan 2007 14:37:29 -0800 Subject: Read from database, write to another database, simultaneously Message-ID: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> I am working on a simple script to read from one database (oracle) and write to another (postgresql). I retrieve the data from oracle in chunks and drop the data to postgresql continuously. The author of one of the python database clients mentioned that using one thread to retrieve the data from the oracle database and another to insert the data into postgresql with something like a pipe between the two threads might make sense, keeping both IO streams busy. Any hints on how to get started? Thanks, Sean From bearophileHUGS at lycos.com Tue Jan 30 05:53:49 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 30 Jan 2007 02:53:49 -0800 Subject: Executing Javascript, then reading value In-Reply-To: References: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> Message-ID: <1170154429.566551.150810@p10g2000cwp.googlegroups.com> Jean-Paul Calderone: > You might look into the > stand-alone Spidermonkey runtime. However, it lacks the DOM APIs, so > it may not be able to run the JavaScript you are interested in running. > There are a couple other JavaScript runtimes available, at least. This may be okay too: http://www.digitalmars.com/dscript/ Bye, bearophile From duncan.booth at invalid.invalid Sat Jan 6 16:24:15 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Jan 2007 21:24:15 GMT Subject: Recommended way to force a thread context switch? References: <1168103258.602286.146100@42g2000cwt.googlegroups.com> <1168104008.910681.46800@38g2000cwa.googlegroups.com> Message-ID: Lloyd Zusman wrote: > I have a python (2.5) program with number of worker threads, and I want > to make sure that each of these does a context switch at appropriate > times, to avoid starvation. I know that I can do a time.sleep(0.001) to > force such a switch, but I'm wondering if this is the recommended > method. The recommended method is to start a new thread rather than following up on an existing thread with an unrelated question. Why do you think that just letting the threads run won't have the effect you desire? Leave it to the system to schedule the threads. From gagsl-py at yahoo.com.ar Tue Jan 16 21:56:55 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 23:56:55 -0300 Subject: Help: asyncore/asynchat and terminator string In-Reply-To: <45AD5A2F.7060701@ilm.com> References: <45AD5A2F.7060701@ilm.com> Message-ID: <7.0.1.0.0.20070116233534.04676110@yahoo.com.ar> At Tuesday 16/1/2007 20:05, David Hirschfield wrote: >I'm implementing a relatively simple inter-application communication >system that uses asyncore/asynchat to send messages back and forth. > >The messages are prefixed by a length value and terminator string, to >signal that a message is incoming, and an integer value specifying the >size of the message, followed by the message data. > >My question is: how can I produce a short terminator string that won't >show up (or has an extremely small chance of showing up) in the binary >data that I send as messages? If you send previously the size of data to follow, there is no need for a terminator. On the receiving side, just read so many bytes; it's a lot easier. Anyway you can add a terminator, and check for it after the data arrives, just a small consistency test. If you can't do that for whatever reason, usually it's done backwards: ensure the chosen (fixed) terminator never happens inside the message. Example: encoding using || as terminator, % as quote character: - any | inside the message is prefixed by the quote character: | -> %| - any % inside the message is doubled: % -> %% This way, any terminator inside the message would be converted to %|%| and could never be confused. At the receiving side, decode as follows: - search for any % character; when found, delete it and keep the following character; keep searching until no more % are found. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From michele.petrazzoDELETE at DELETEunipex.it Fri Jan 5 12:51:38 2007 From: michele.petrazzoDELETE at DELETEunipex.it (Michele Petrazzo) Date: Fri, 05 Jan 2007 17:51:38 GMT Subject: wxWindows off-screen? In-Reply-To: References: Message-ID: Ivan Voras wrote: > Is it possible to draw a widget or a window in an off-screen buffer? (Assuming that you are on linux.) wxWigets (wxWindows is the old name) or better, since if you are on a python ng, wxPython :), can't be used if you are on a not-X machine: michele:~$ env | grep DIS DISPLAY=:0.0 michele:~$ export DISPLAY= michele:~$ env | grep DIS DISPLAY= michele:~$ python Python 2.4.4 (#2, Oct 20 2006, 00:23:25) [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import wx a = wx.PySimpleApp() Unable to access the X Display, is $DISPLAY set properly? michele:~$ echo $? 1 michele:~$ > What I'm trying to do is capture rendered HTML to a bitmap (in other > words, something like html2bitmap) by using wxWindows' HTML widget. > If anyone has a different way of doing it, I'd be glad to hear it... For me you have some solutions: - open an X server (only X, you don't need gdm, kdm other), set the right DISPLAY env variable and use wx. Ok, you need (a lot of) memory, that in my tests are about 16 M for Xorg and 24 for python with wx, a wxFrame, wxPanel and some controls. Can be a good/the right solution for me. - If I remember correctly, there are a project that "emulate" an X server (so the same that the X solution, but with less memory), but I don't know its name... Try to search on internet. - Always with an X server, use a browser and with its api (pyxpcom for mozilla based, or dcop and pykde for konqueror and so on...), using the "print on a file" feature, so print a ps and convert it on an image. Good try :), and not forgot to tell us your results! Hope this help, Michele From mccredie at gmail.com Thu Jan 18 13:08:35 2007 From: mccredie at gmail.com (Matimus) Date: 18 Jan 2007 10:08:35 -0800 Subject: closing a "forever" Server Socket References: <1169123381.930403.24170@38g2000cwa.googlegroups.com> Message-ID: <1169143715.222186.30530@51g2000cwl.googlegroups.com> > I want to ask if someone knows a better way for closing a "forever > server" or if there is a lack in my design. Generally you don't create a 'forever server'. You create an 'until I say stop' server. I would do this by looking at the 'serve_forever' method, and implementing my own 'serve_until_?' method that is similar, but will stop if a flag is set. Then you have to create a method for setting that flag. It could be as simple as a keypress, or you could add a quit method to your dispatcher that sets the flag when a certain address is visited. That second method probably needs some added security, otherwise anybody can just visit 'your.server.com/quit' and shut it down. From ask.me at mail.com Mon Jan 29 01:09:07 2007 From: ask.me at mail.com (Jammer) Date: Mon, 29 Jan 2007 01:09:07 -0500 Subject: decode overwrite variable? Message-ID: <21235$45bd8f83$d8a87c2a$18298@NEXICOM.NET> Will a failed decode overwrite the variable? message = message.decode('iso-8859-1') or do I need to do msg = message.decode('iso-8859-1') From klappnase at web.de Tue Jan 16 14:03:57 2007 From: klappnase at web.de (klappnase) Date: 16 Jan 2007 11:03:57 -0800 Subject: Segfault with tktreectrl on python-2.5 on linux In-Reply-To: References: <1168884154.116074.308720@s34g2000cwa.googlegroups.com> <1168941826.062298.229080@51g2000cwl.googlegroups.com> Message-ID: <1168974236.965840.193310@s34g2000cwa.googlegroups.com> Anton Hartl schrieb: > The bug report should go to both; I actually contacted Jeremy Hylton > as a main contributor of the new AST code two weeks ago but didn't > get any response. > Ok, I submitted bug reports on both the tktreectrl and the python sourceforge pages. Now I'll have a nice cup of tea and see what happens :) Regards Michael From duncan.booth at invalid.invalid Thu Jan 18 07:06:19 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Jan 2007 12:06:19 GMT Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: Peter Otten <__peter__ at web.de> wrote: > But still, to help my lack of fantasy -- what would a sane zip() > implementation look like that does not guarantee the above output? > Hypothetically? The code in zip which builds the result tuples looks (ignoring error handling) like: // inside a loop building each result element... PyObject *next = PyTuple_New(itemsize); for (j = 0; j < itemsize; j++) { PyObject *it = PyTuple_GET_ITEM(itlist, j); PyObject *item = PyIter_Next(it); PyTuple_SET_ITEM(next, j, item); } For fixed size tuples you can create them using PyTuple_Pack. So imagine some world where the following code works faster for small tuples: // Outside the loop building the result list: PyObject *a, *b, *c; if (itemsize >= 1 && itemsize <= 3) a = PyTuple_GET_ITEM(...); if (itemsize >= 2 && itemsize <= 3) b = PyTuple_GET_ITEM(...); if (itemsize == 3) c = PyTuple_GET_ITEM(...); ... // inside the result list loop: PyObject *next; if (itemsize==1) { next = PyTuple_Pack(1, PyIter_Next(a)); } else if (itemsize==2) { next = PyTuple_Pack(2, PyIter_Next(a), PyIter_Next(b)); } else if (itemsize==2) { next = PyTuple_Pack(3, PyIter_Next(a), PyIter_Next(b), PyIter_Next(c)); } else { next = PyTuple_New(itemsize); for (j = 0; j < itemsize; j++) { PyObject *it = PyTuple_GET_ITEM(itlist, j); PyObject *item = PyIter_Next(it); PyTuple_SET_ITEM(next, j, item); } } If compiled on a system where the stack grows downwards (as it often does) the C compiler is very likely to evaluate function arguments in reverse order. (BTW, this also assumes that it's an implementation which uses exceptions or something for error handling otherwise you probably can't get it right, but maybe something like IronPython could end up with code like this.) Or maybe if someone added PyTuple_Pack1, PyTuple_Pack2, PyTuple_Pack3 functions which grab their memory off a separate free list for each tuple length. That might speed up the time to create the tuples as you might be able to just reset the content not rebuild the object each time. Again that could make code like the above run more quickly. From gibo at gentlemail.com Tue Jan 23 06:09:08 2007 From: gibo at gentlemail.com (GiBo) Date: Wed, 24 Jan 2007 00:09:08 +1300 Subject: How to instantiate a different class in a constructor? Message-ID: <45B5ECD4.3040207@gentlemail.com> Hi all, I have a class URI and a bunch of derived sub-classes for example HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is module urllib & friends, however my actual problem however maps very well to this example). Now I want to pass a string to constructor of URI() and get an instance of one of the subclasses back. For example uri=URI('http://abcd/...') will make 'uri' an instance of HttpURI class, not instance of URI. To achieve this I have a list of all subclasses of URI and try to instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI to HttpURI constructor it raises ValueError exception and I want to test HttpsURI, FtpURI, etc. For now I have this code: ===== class URI(object): def __new__(self, arg): for subclass in subclasses: try: instance = object.__new__(subclass, arg) return instance except ValueError, e: print "Ignoring: %s" % e raise ValueError("URI format not recognized" % arg) class HttpURI(URI): def __init__(self, arg): if not arg.startswith("http://"): raise ValueError("%s: not a HTTP URI" % arg) self._uri = arg class FtpURI(URI): def __init__(self, arg): if not arg.startswith("ftp://"): raise ValueError("%s: not a FTP URI") self._uri = arg subclasses = [HttpURI, FtpURI] if __name__ == "__main__": print "Testing HTTP URI" uri = URI("http://server/path") print uri print "Testing FTP URI" uri = URI("ftp://server/path") print uri ===== The problem is that ValueError exception raised in HttpURI.__init__() is not handled in URI.__new__(): ----- ~$ ./tst.py Testing HTTP URI <__main__.HttpURI object at 0x808572c> # this is good Testing FTP URI Traceback (most recent call last): File "./tst.py", line 35, in uri = URI("ftp://server/path") File "./tst.py", line 18, in __init__ raise ValueError("%s: not a HTTP URI" % arg) ValueError: ftp://server/path: not a HTTP URI # this is bad ----- When I change the __init__ methods of subclasses to __new__ I instead get: ----- ./tst.py Testing HTTP URI Traceback (most recent call last): File "./tst.py", line 29, in uri = URI("http://server/path") File "./tst.py", line 7, in __new__ instance = object.__new__(subclass, arg) TypeError: default __new__ takes no parameters ----- Does anyone have any hints on how to solve this problem? (other than using urllib or other standard modules - as I said this is just to demonstrate the nature of my problem). Thanks! GiBo From robert.kern at gmail.com Fri Jan 5 19:58:37 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 05 Jan 2007 18:58:37 -0600 Subject: PyType_IsSubtype () In-Reply-To: <1167996955.467665.286170@42g2000cwt.googlegroups.com> References: <1167986947.735415.99970@s34g2000cwa.googlegroups.com> <459E1988.8060807@v.loewis.de> <1167996955.467665.286170@42g2000cwt.googlegroups.com> Message-ID: Sheldon wrote: > I ran the program in GDB and it crashed giving the following backtrace: > > #0 0x4008376e in PyType_IsSubtype () from /usr/lib/libpython2.3.so.1.0 > #1 0x4047730c in ?? () from > /usr/lib/python2.3/site-packages/Numeric/_numpy.so > #2 0x000000f2 in ?? () > #3 0x08d9dd34 in ?? () > #4 0x4046c780 in PyArray_Return () from > /usr/lib/python2.3/site-packages/Numeric/_numpy.so > #5 0x08d9dd44 in ?? () > #6 0x40100300 in PyBaseString_Type () from > /usr/lib/libpython2.3.so.1.0 > #7 0x08105718 in ?? () > #8 0x4007490d in PyObject_Init () from /usr/lib/libpython2.3.so.1.0 > #9 0x08105ae0 in ?? () > > Can you make head or tail of this? No, we still need more information. Can you tell us what version of Numeric you are using? The latest is 24.2, so you might want to try that if you are not already. Also, please try to come up with the smallest self-contained snippet of code that demonstrates the bug so that the rest of us can try to replicate it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Thomas.Ploch at gmx.net Thu Jan 4 23:28:41 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 05:28:41 +0100 Subject: What is proper way to require a method to be overridden? In-Reply-To: <12prkb29em82cac@corp.supernews.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> <12prkb29em82cac@corp.supernews.com> Message-ID: <459DD3F9.5040603@gmx.net> Grant Edwards schrieb: > On 2007-01-05, Thomas Ploch wrote: > >>>> I am writing a class that is intended to be subclassed. What >>>> is the proper way to indicate that a sub class must override a >>>> method? >>> If any subclass *must* override a method, raise >>> NotImplementedError in the base class (apart from documenting >>> how your class is supposed to be used). >> I learn so much from this list. I didn't even know this error existed. > > And remember: even if it didn't, you could have created your > own: Erm, it wasn't me who asked. I just wanted to say that I didn't know that there is a NotImplementedError. Havn't seen it before. :-) Thomas From Norbert.Klamann at projecthome.de Fri Jan 12 08:36:18 2007 From: Norbert.Klamann at projecthome.de (Norbert) Date: 12 Jan 2007 05:36:18 -0800 Subject: Hint :Easy_Install Documentation Message-ID: <1168608975.981916.200080@s34g2000cwa.googlegroups.com> Hello list, just in the moment I wanted to write about then lacking documentation about Easy_Install, but then I found this one : http://www-128.ibm.com/developerworks/library/l-cppeak3.html. Just for google. HTH Norbert From skip at pobox.com Sat Jan 13 15:53:29 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Jan 2007 14:53:29 -0600 Subject: Threaded for loop In-Reply-To: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> Message-ID: <17833.18121.441468.699493@montanaro.dyndns.org> John> I want to do something like this: John> for i = 1 in range(0,N): John> for j = 1 in range(0,N): John> D[i][j] = calculate(i,j) John> I would like to now do this using a fixed number of threads, say John> 10 threads. What is the easiest way to do the "parfor" in python? I'd create a queue containing 10 tokens. Pull a token off the queue, invoke the thread with the parameters for its chunk, have it compute its bit, lock D, update it, unlock it, then return the token to the token queue. Sketching (and completely untested): # Calculate one row of D def calcrow(i, N, token, Tqueue, Dqueue): d = [0.0] * N for j in range(N): d[j] = calculate(i, j) D = Dqueue.get() D[i][:] = d Dqueue.put(D) Tqueue.put(token) # This queue limits the number of simultaneous threads Tqueue = Queue.Queue() for i in range(10): Tqueue.put(i) # This queue guards the shared matrix, D Dqueue = Queue.Queue() D = [] for i in range(N): D.append([0.0] * N) Dqueue.put(D) for i in range(N): token = Tqueue.get() t = threading.Thread(target=calcrow, args=(i, N, token, Tqueue, Dqueue)) t.start() Skip From martin at v.loewis.de Wed Jan 31 02:48:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 31 Jan 2007 08:48:58 +0100 Subject: Unicode error handler In-Reply-To: References: Message-ID: <45C049EA.60009@v.loewis.de> Walter D?rwald schrieb: > You might try the following: > > # -*- coding: iso-8859-1 -*- > > import unicodedata, codecs > > def transliterate(exc): > if not isinstance(exc, UnicodeEncodeError): > raise TypeError("don'ty know how to handle %r" % r) > return (unicodedata.normalize("NFD", exc.object[exc.start])[:1], > exc.start+1) I think a number of special cases need to be studied here. I would expect that this is "semantically correct" if the characters being dropped are combining characters (at least in the languages I'm familiar with, it is common to drop them for transliteration). However, if you do py> for i in range(65536): ... c = unicodedata.normalize("NFD", unichr(i)) ... for c2 in c[1:]: ... if not unicodedata.combining(c2): print hex(i),;break you'll see that there are many characters which don't decompose into a base character + sequence of combining characters. In particular, this involves all hangul syllables (U+AC00..U+D7A3), for which it is just incorrect to drop the "jungseongs" (is that proper wording?). There are also some cases which I'm completely uncertain about, e.g. ORIYA VOWEL SIGN AI decomposes to ORIYA VOWEL SIGN E + ORIYA AI LENGTH MARK. Is it correct to drop the length mark? It's not listed as a combining character. Likewise, MYANMAR LETTER UU decomposes to MYANMAR LETTER U + MYANMAR VOWEL SIGN II; same question here. Regards, Martin From rampeters at gmail.com Fri Jan 12 11:11:23 2007 From: rampeters at gmail.com (johnny) Date: 12 Jan 2007 08:11:23 -0800 Subject: Any python based "Live Web Chat Support" Message-ID: <1168618282.128710.52500@l53g2000cwa.googlegroups.com> Is there any open source "live web chat support" program or script out there? Any you can recommend? From deacon.sweeney at gmail.com Tue Jan 30 17:02:11 2007 From: deacon.sweeney at gmail.com (deacon.sweeney at gmail.com) Date: 30 Jan 2007 14:02:11 -0800 Subject: Resizing widgets in text windows In-Reply-To: References: <1169847315.631951.295830@a75g2000cwd.googlegroups.com> Message-ID: <1170194530.966547.312010@q2g2000cwa.googlegroups.com> On Jan 26, 10:52 pm, James Stroud wrote: > deacon.swee... at gmail.com wrote: > > Hi, I've been searching for a .resize()-like function to overload much > > like can be done for the delete window protocol as follows: > > > toplevel.protocol("WM_DELETE_WINDOW", callback) > > > I realize that the pack manager usually handles all of the resize > > stuff, but I've found an arrangement that the pack manager fails for. > > That is, if one embeds a canvas into a window created inside a text > > widget, > > Your meaning here is unclear. How is it possible to have "a window > created inside a text widget"? using the create_window function, as below. > > > then resize the text widget (via its container), the canvas and > > its container windows do not resize. So I need to resize the window > > that the canvas is embedded in. > > Try the Toplevel.wm_geometry() function. > > > The most obvious way of doing this > > would be as above, but there does not seem to be an equivalent to the > > "WM_DELETE_WINDOW" protocol for resizing. > > Do you want to detect when a window is resized or do you want to resize > a window programatically. > > If the former, bind the Toplevel to ''. > > E.g. > > from Tkinter import * > > def config(t): > def _r(e, t=t): > geom = e.widget.wm_geometry() > geom = geom.split('+')[0] > t.wm_geometry(geom) > print 'resized %s to %s' % (t, geom) > return _r > > tk = Tk() > tk.title('resize me') > t2 = Toplevel(tk) > t2.title('I get resized') > tk.bind('', config(t2)) > > Is that cool or what? > Yes, this is exactly what I was looking for. Thanks. > James > > > Any help would be greatly appreciated. > > >DeaconSweeney From jorge.vargas at gmail.com Fri Jan 5 15:52:15 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Fri, 5 Jan 2007 16:52:15 -0400 Subject: PDF rendering toolkit? Message-ID: <32822fe60701051252s6353f10drc101109adc376fdb@mail.gmail.com> Hi I'm looking for a tool to take an actual .pdf file and display it in a window (I'm using wxwidgets at the moment) I have found several project but none seem to do what I need. http://sourceforge.net/projects/pdfplayground seems like a nice toolkit to edit pdf files with python code, but nothing about rendering. I have find out http://poppler.freedesktop.org/ but there seems to be no python bindings for it. there is also an example at http://www.daniweb.com/code/snippet618.html using wx.lib.pdfwin but that is windows only, I need at least Linux support better if it's platform independant as python *should* be and the reportlabs BSD packages can't do this. http://www.reportlab.org/devfaq.html#2.1.5 anyone knows of a toolkit to do this? bonus points if's it is already integrated into wxpython From dfj225 at gmail.com Tue Jan 9 19:25:48 2007 From: dfj225 at gmail.com (dfj225 at gmail.com) Date: 9 Jan 2007 16:25:48 -0800 Subject: dynamic library loading, missing symbols Message-ID: <1168388748.024090.119530@i39g2000hsf.googlegroups.com> While my question doesn't pertain specifically to python programming, it is a result of developing a python module, so I'm hoping someone here might have experience with this issue. So, first a little background to how the system works right now. I am developing a module for Python. The original code is written in C++ and I am creating a wrapper using Boost.Python. The C++ code for the module makes calls into a library that in turn dynamically loads a library (using dlopen). This dynamically loaded library, in turn, expects to find a symbol in the code that loaded it (using extern it declares a variable). However, the linker fails at runtime here because it can't find this symbol. The variable in question does exist in the C++ code that in does dlopen. The reason for the complication is that I don't have control over how the library does dlopen() or how the code that calls dlopen was compiled. I am, however, able to control the build process for the Boost.Python wrapper and the original C++ code that the Boost.Python wraps. I've tried as many linker tricks as I can think of to get this to work. Both the boost wrapper and the C++ code that it wraps are built using --export-dynamic. Is there a way to set at runtime what directories or libraries the linker should search for these symbols? I have set LD_LIBRARY_PATH correctly, but that didn't seem to affect anything. For reference, I am running on Gentoo linux 2.6.11.12 with gcc 3.4.4 I'm interested in any ideas that might help, but the ideal one should work on any *nix system and not just linux. (Please don't suggest that I change the operation of the code that is doing dlopen, as it is 3rd party and not something that would be in our best interest to work on). If you think I need to provide more information, I'd be happy to try and clarify things. Thanks, ~Doug From robert.kern at gmail.com Mon Jan 15 17:52:52 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 15 Jan 2007 16:52:52 -0600 Subject: The curious behavior of integer objects In-Reply-To: References: Message-ID: Jim B. Wilson wrote: > Am I nuts? Or only profoundly confused? I expected the this little script > to print "0": > > class foo(int): > def __init__(self, value): > self = value & 0xF That statement only rebinds the local name self to something else. It does not modify the object at all or change the result of instantiating foo(). You need to override __new__ to get the behavior that you want. http://www.python.org/download/releases/2.2.3/descrintro/#__new__ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From grante at visi.com Fri Jan 5 10:14:28 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 15:14:28 -0000 Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> Message-ID: <12psqqk75ij5ta5@corp.supernews.com> On 2007-01-05, king kikapu wrote: > i am learning Python, just finished a book and i am starting > to write programs. I just want to ask, is the "correct" way to > deploy my programs to other computers, the .pyc files ?? That depends on the platform. Under Linux, one usually just provides the source. Under Windows, I ususally use py2exe+inno-setup. > I now that with the "-m compileall ." switch can compile a .py > file into bytecodes. So i suppose that if Python has to run a > .pyc file, it will load and execute it faster. A little bit, yes. > And if i have some "sensitive" data in my source, like > passwords (and the source of cource!) they will be more secure > in a compiled file. Not really. -- Grant Edwards grante Yow! I represent a at sardine!! visi.com From ptmcg at austin.rr.com Tue Jan 23 14:19:01 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jan 2007 11:19:01 -0800 Subject: Overloading assignment operator In-Reply-To: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1169579940.966652.191990@l53g2000cwa.googlegroups.com> On Jan 23, 12:24 pm, Achim Domma wrote: > Hi, > > I want to use Python to script some formulas in my application. The user > should be able to write something like > > A = B * C > > where A,B,C are instances of some wrapper classes. Overloading * is no > problem but I cannot overload the assignment of A. I understand that > this is due to the nature of Python, but is there a trick to work around > this? > All I'm interested in is a clean syntax to script my app. Any ideas are > very welcome. > > regards, > Achim Simple option: how do you feel about using '<<=' instead of '=' (by defining __ilshift__)? This gives you: A <<= B * C (looks sort of like "injecting" the result of B times C into A) More complicated option: embed an expression/assignment parser into your app. You can get a jump on this using some of the examples that come with pyparsing (can check these out online at http://pyparsing.wikispaces.com/Examples - look at fourFn.py and simpleArith.py). -- Paul From mail at microcorp.co.za Wed Jan 10 00:39:41 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 10 Jan 2007 07:39:41 +0200 Subject: Bitwise expression References: Message-ID: <019d01c7348c$1c2fa9e0$03000080@hendrik> "Gigs_" wrote: > Now is all clearer thanks to mensanator at aol.com and Hendrick van Rooyen Contrary to popular belief in the English speaking world - >>> "c" in "Hendrik" False >>> There is no "c" in "Hendrik" : - ) - Hendrik From jstroud at mbi.ucla.edu Sun Jan 28 19:38:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 28 Jan 2007 16:38:01 -0800 Subject: Function to create Tkinter PhotoImages from directory? In-Reply-To: References: Message-ID: Kevin Walzer wrote: > I am trying to create a number of Tk PhotoImages from a single > directory. Currently I am hard-coding file names and image names, like so: > > def makeImages(self): > self.imagedir = (os.getcwd() + '/images/') > self.folder_new=PhotoImage(file=self.imagedir + 'folder_new.gif') > self.save=PhotoImage(file = self.imagedir + 'save.gif') > self.folder=PhotoImage(file=self.imagedir + 'folder.gif') > self.help=PhotoImage(file=self.imagedir + 'help.gif') > self.fontsmall=PhotoImage(file=self.imagedir + 'fontsmall.gif') > self.stop=PhotoImage(file=self.imagedir + 'stop.gif') > > What I'd like to do is glob the directory and create images with the > same name as the gif file, but I can't figure out how to get that to > work. Can anyone help? > Should be (wrote setattr to fast): def makeImages(self): import glob import os self.imagedir = os.path.join(os.getcwd(), 'images') pattern = os.path.join(self.imagedir, '*.gif') image_names = glob.glob(pattern) for name in image_names: base = os.path.basename(name).split('.')[0] pathname = os.path.join(self.imagedir, n) setattr(self, base, Photoimage(file=pathname)) From stever at cruzio.com Fri Jan 26 12:30:02 2007 From: stever at cruzio.com (Steve) Date: 26 Jan 2007 09:30:02 -0800 Subject: Pyparsing - Dealing with a Blank Value In-Reply-To: <1169784435.941039.269240@k78g2000cwa.googlegroups.com> References: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> <1169784435.941039.269240@k78g2000cwa.googlegroups.com> Message-ID: <1169832602.513112.141360@a75g2000cwd.googlegroups.com> Hi Paul! Thanks for your suggestions on the default value (I didn't know you could do that!!) and the use of the makeHTMLtags module! Steve On Jan 25, 8:07 pm, "Paul McGuire" wrote: > On Jan 25, 7:13 pm, "Steve" wrote: > > > Hi All, > > > I've picked up thePyParsingmodule and am trying to figure out how to > > do a simple parsing of some HTML source code. My specific problem is > > dealing with an element that is blank. > > > > > Any assistance would be greatly appreciated! > > > SteveJust define a default value to be returned for MultiItem if the > Optional expression is not found: > > MultiItem = Optional(OneOrMore(dataItem),default="") > > Define default to be whatever string you choose. > > -- Paul From no-spam at no-spam-no-spam.invalid Wed Jan 17 13:22:36 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 17 Jan 2007 19:22:36 +0100 Subject: Distributed computation of jobs In-Reply-To: <1169046239.405261.81740@m58g2000cwm.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> <1169046239.405261.81740@m58g2000cwm.googlegroups.com> Message-ID: Paul Boddie wrote: > A.T.Hofkamp skrev: >> Let me add a few cents to the discussion with this announcement: > > [Notes about exec_proxy, batchlib and rthread] > > I've added entries for these modules, along with py.execnet, to the > parallel processing solutions page on the python.org Wiki: > > http://wiki.python.org/moin/ParallelProcessing > > Thanks for describing your work to us! > > Paul > as many libs are restriced to certain OS'es, and/or need/rely on extension modules, few tags would probably improve: OS'es, pure-python, dependeniess Robert From zaz600 at gmail.com Thu Jan 25 02:07:02 2007 From: zaz600 at gmail.com (NoName) Date: 24 Jan 2007 23:07:02 -0800 Subject: How can i do this in Python? In-Reply-To: References: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> Message-ID: <1169708822.345102.67630@s48g2000cws.googlegroups.com> Thanks;) On 25 ???., 17:47, Gabriel Genellina wrote: > At Thursday 25/1/2007 01:25, NoName wrote: > > >perl -ane "print join(qq(\t), at F[0,1,20,21,2,10,12,14,11,4,5,6]).qq(\n)"Must be done on a single line? > I'm not sure if I've got right the behavior - it's been some time > since I quit writing Perl code. The script iterates over all lines > contained on all files specified on the command line; for each line, > splits it on whitespace; then it prints a selected set of fields > (columns 0, 1, 20, 21...) using a tab character as field separator. > > === cut === > import operator,fileinput > > mapper = map(operator.itemgetter, [0,1,20,21,2,10,12,14,11,4,5,6]) > for line in fileinput.input(): > ? ? ?fields = line.split() > ? ? ?print '\t'.join(m(fields) for m in mapper) > === cut === > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya!http://www.yahoo.com.ar/respuestas From stargaming at gmail.com Sun Jan 28 12:48:04 2007 From: stargaming at gmail.com (Stargaming) Date: Sun, 28 Jan 2007 18:48:04 +0100 Subject: howto redirect and extend help content ? In-Reply-To: <1fc1a$45bcc7f4$d443bb3a$8806@news.speedlinq.nl> References: <1fc1a$45bcc7f4$d443bb3a$8806@news.speedlinq.nl> Message-ID: Stef Mientki schrieb: > I'm making special versions of existing functions, > and now I want the help-text of the newly created function to exists of > 1. an extra line from my new function > 2. all the help text from the old function > > # the old function > def triang(M,sym=1): > """The M-point triangular window. <== old help text > """ > .... > > # the new function > def chunked_triang(M): > """ Chunked version of "triang" <== the extra line > """ > > >>> help(chunked_triang) > # should give something like > > chunked_triang(M) <== the new definition > Chunked version of "triang" <== the extra line > The M-point triangular window. <== old help text > > Is that possible ? > > > thanks, > Stef Mientki Don't you think your users can follow this easy reference theirselves? From bytter at gmail.com Wed Jan 31 09:47:12 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Wed, 31 Jan 2007 14:47:12 +0000 Subject: Synchronous shutil.copyfile() In-Reply-To: <4e8efcf50701301711m1fb5a0ffi5b3080eed1517214@mail.gmail.com> References: <4e8efcf50701301711m1fb5a0ffi5b3080eed1517214@mail.gmail.com> Message-ID: <4e8efcf50701310647x3b98aa9cobaf543270dc62e84@mail.gmail.com> I'm banging my head over this one... sometimes it just works... *argh* Here's a snip of my problem: import win32com.client import shutil import time engine = win32com.client.Dispatch("DAO.DBEngine.36") table = 'STUFFTODELETE' dstFilename = 'in.mdb' workingfile = 'work.mdb' shutil.copyfile(dstFilename, workingfile) print 'Sleeping 5 after copy...' time.sleep(5) dstDb = engine.OpenDatabase(workingfile) print 'Sleeping 5 after open...' time.sleep(5) dstDb.Execute('DELETE FROM ' + table) At at *exactly* this line, I get the error: C:\Python24\lib\site-packages\win32com\gen_py\00025E01- 0000-0000-C000-000000000046x0x5x0.py 510 com_error: (-2147352567, 'Exception occurred.', (0, 'DAO.Database', 'Not a valid bookmark.', 'jeterr40.chm', 5003159, -2146825129), None) Sometimes... Yes, the database is a %"#$"# MSAccess. This script is running under windows. Any ideas? On 1/31/07, Hugo Ferreira wrote: > > Well.. Thx for the answers. > > The only way I had to make it work was to use a time.sleep(10) after the > shutil.copyfile(). Since this is a night-run script, I can waste 10 > seconds, but it still knocks me out "why" it happens... > > Cheers! > > Hugo Ferreira > > On 30 Jan 2007 18:06:15 +0000 (GMT), Matthew Woodcraft > wrote: > > > > Hugo Ferreira < bytter at gmail.com> wrote: > > > I have a problem. I'm using calling shutil.copyfile() followed by > > > open(). The thing is that most of the times open() is called before > > > the actual file is copied. I don't have this problem when doing a > > > step-by-step debug, since I give enough time for the OS to copy the > > > file, but at run-time, it throws an exception. > > > > > > Is there anyway to force a sync copy of the file (make python wait for > > > the completion)? > > > > shutil.copyfile() closes both files before it returns, so I suspect > > this is an OS-level bug. > > > > The most likely culprits are buggy network filesystems and buggy > > on-access virus scanners. > > > > -M- > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at netscape.net Mon Jan 1 01:00:58 2007 From: paddy3118 at netscape.net (Paddy) Date: 31 Dec 2006 22:00:58 -0800 Subject: OO question In-Reply-To: References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> Message-ID: <1167631258.804660.154490@n51g2000cwc.googlegroups.com> Steven D'Aprano wrote: > On Sun, 31 Dec 2006 19:47:12 -0800, fejkadress wrote: > > > I want to make an addressbook and I'm new to OO programming, so I > > wonder if this sounds reasonable. > > > > I think of making a class Address which contains all data about one > > person, that class can have UserDict as baseclass so I can access data > > like object['name'], etc.. > > If you are using Python 2.2 or greater, you can inherit from dict: > > > >>> class Address(dict): > ... pass > ... > >>> fred = Address({"address": "123 smith street"}) > >>> fred['address'] > '123 smith street' > > > But ask yourself, what benefit do you gain by subclassing dict? Why not > just use a dict? > > If this is a learning exercise, then sure, go for it, subclass away! But > if this is meant to be real code, then consider what benefits and costs > using OO will give you, compared to a function-based approach. > > (Please don't assume that this is a thinly veiled hint that OO is the > wrong approach. It isn't.) > > > > Then maybe I can have a class AddressBook which has a list that > > contains all those Address objects. > > Does that sound reasonable? > > Again, why create an AddressBook class? Why not just have a list of > Addresses? > > > > > And then the real reason that I posted here is: > > If I want to save all addresses to disk, I can have a method, say, > > save() of AddressBook. But then what? What is a good object oriented > > approach? Should each Address object take care of saving itself to the > > file, with a method like writetofile(filename), or should the class > > AddressBook take care of the saving and ask each object for its data? > > > > Here's one approach, assuming that AddressBook is merely a list of > Addresses and that the Address class knows how to write to an open file > object: > > def save(list_of_addresses, filename): > f = file(filename, "w") > for address in list_of_addresses: > address.save(f) > f.close() > > Here's a more pure OO approach to do the same thing: > > class AddressBook(object): > def __init__(self, list_of_addresses): > self.addresses = list_of_addresses > > def save(self, filename): > f = file(filename, "w") > for address in self.addresses: > address.save(f) > f.close() > > Here's a third approach: > > class AddressBook(object): > def __init__(self, list_of_addresses): > self.addresses = list_of_addresses > self.currentfile = None > > def save_one_address(self, data): > data = do_something_with(data) > self.currentfile.write(data) > > def save(self, filename): > self.currentfile = file(filename, "w") > for address in self.addresses: > self.save_one_address(address.export()) > self.currentfile.close() > self.currentfile = None > > > -- > Steven. Small addition. If a class does a save then it should also do the load of the data too. From exarkun at divmod.com Wed Jan 10 18:45:11 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 10 Jan 2007 18:45:11 -0500 Subject: what is the idiom for copy lots of params into self? In-Reply-To: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> Message-ID: <20070110234511.11447.2048857953.divmod.quotient.12511@ohm> On 10 Jan 2007 14:46:54 -0800, Emin wrote: >Dear Experts, > >When writing large classes, I sometimes find myself needing to copy a >lot of parameters from the argument of __init__ into self. Instead of >having twenty lines that all basically say something like self.x = x, I >often use __dict__ via something like: > >class example: > def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n): > for name in >['a','b','c','d','e','f','g','h','i','j','k','l','m','n']: > self.__dict__[name] = locals()[name] > >This saves a lot of code and makes it easier to see what is going on, >but it seems like there should be a better idiom for this task. Any >suggestions? I use a helper, like http://divmod.org/trac/browser/trunk/Epsilon/epsilon/structlike.py#L35 Jean-Paul From http Tue Jan 30 19:38:42 2007 From: http (Paul Rubin) Date: 30 Jan 2007 16:38:42 -0800 Subject: Sorting a List of Lists References: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> Message-ID: <7x8xfkghd9.fsf@ruckus.brouhaha.com> L?tezo writes: > > I then thought I'd just go events.sort(lambda x,y: x[2] References: Message-ID: <45AD4E8A.7040008@bullseye.andymac.org> Dejan Rodiger wrote: > Jeremy said the following on 16.1.2007 8:27: > >> I have a fat C++ extension to a Python 2.3.4 program. In all, I count >> five threads. Of these, two are started in Python using >> thread.start_new_thread(), and both of these wait on semaphores in the C++ >> extension using sem_wait(). There also are two other Python threads and one >> thread running wholly in >> the extension. >> >> I notice that when one of the Python threads calls the extension and waits >> on a semaphore, all but the C++ thread halt even when not waiting on any >> semaphore. How do we get this working right? > > Check the Global Interpreter Lock More specifically, make sure that any extension code that does not call Python API functions releases the GIL for the duration. Look into the Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS macros and the PyGILState*() API functions (these API functions appeared in Python 2.3). -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From nobody at localhost.localdomain Fri Jan 12 06:49:56 2007 From: nobody at localhost.localdomain (Steven Wayne) Date: Fri, 12 Jan 2007 05:49:56 -0600 Subject: Learning Python book, new edition? References: Message-ID: On 12 Jan 2007 11:06:29 GMT, Duncan Booth wrote: > Steven Wayne wrote: > >> Don't take this the wrong way, but this isn't an email, it's a usenet >> posting. > > It is now, but it started as an email. If you examine its headers he sent > it to the list but the list administrator had set up software up to copy > the email to a newsgroup. There's a list? > Fortunately, as you said, the email gave him > permission to do that otherwise the entire legal profession might have > collapsed under its own weight. :-) Not seeing a down side to that. But it brings up and interesting point. Is automatic email to newsgroup software now defunct? What if the disclaimer were better written and it forbade such an action? Steven -- .''`. : :' : `. `'` `- From steve at REMOVEME.cybersource.com.au Mon Jan 15 22:42:35 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 16 Jan 2007 14:42:35 +1100 Subject: assert versus print [was Re: The curious behavior of integer objects] References: <76fd5acf0701151838l1a724be5n3f1e1fda629d1464@mail.gmail.com> Message-ID: On Mon, 15 Jan 2007 21:01:35 -0600, Ron Adam wrote: > There have been times where I would like assert to be a little more assertive > than it is. :-) > > ie.. not being able to turn them off with the -0/-00 switches, and having them > generate a more verbose traceback. If you want something more verbose, you have it: >>> assert False, "verbose traceback" Traceback (most recent call last): File "", line 1, in ? AssertionError: verbose traceback If you want something that won't be turned off by -O, you maybe need to write your own: def assert_(condition, msg=""): if not condition: raise AssertionError(msg) > Maybe have an alternative 'warn' as an alternative debugging version that could > be set to ignore, soft (print to log), and hard (raise an error). Check out the warnings module. -- Steven D'Aprano From yuxi at ece.gatech.edu Mon Jan 22 09:46:57 2007 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Mon, 22 Jan 2007 09:46:57 -0500 Subject: Getting to an SSH account over a HTTP proxy In-Reply-To: <51jt71F1k884hU1@mid.uni-berlin.de> References: <51jt71F1k884hU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > BJ?rn Lindqvist wrote: > >> I want to use Python to connect to a SSH account over a HTTP proxy to >> automate some operations. I thought paramiko would be able to do that, >> but it can not (it seems). >> >> Is there some other Python module that can do what I want? > > Is there anything that can do what you want? Last time I checked there is no > such thing as SSH-over-HTTP. Are you sure that is possible? He's referring to the HTTP CONNECT method, which can tunnel arbitrary TCP connections, not just HTTP. The IETF draft for this is titled "Tunneling TCP based protocols through Web proxy servers". AFAIK, there are no Python modules which support that. The protocol itself is fairly simply though, so it shouldn't be too hard to write your own wrapper or proxy for the client side. Things get a little more complicated if you have to authenticate with the proxy first. From sjmachin at lexicon.net Wed Jan 10 07:31:34 2007 From: sjmachin at lexicon.net (John Machin) Date: 10 Jan 2007 04:31:34 -0800 Subject: pyExcelerator big integer values In-Reply-To: <1168422401.594651.278390@i39g2000hsf.googlegroups.com> References: <1168349446.381187.65810@11g2000cwr.googlegroups.com> <45a42e7c@news.eftel.com> <1168422401.594651.278390@i39g2000hsf.googlegroups.com> Message-ID: <1168432294.206654.308670@77g2000hsv.googlegroups.com> Gacha wrote: > Thank you, the repr() function helped me a lot. > > v = unicode(values[(row_idx, col_idx)]) > if v.endswith('e+12'): > v = repr(values[(row_idx, col_idx)]) That endswith() looks rather suspicious ... what if it's +11 or +13, and shouldn't it have a zero in it, like "+012" ?? Here's a possible replacement -- I say possible because you have been rather coy about what you are actually trying to do. value = values[(row_idx, col_idx)]) if isinstance(value, float): v = repr(value) else: v = unicode(value) HTH John From duncan.booth at invalid.invalid Tue Jan 16 06:51:06 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jan 2007 11:51:06 GMT Subject: html + javascript automations = [mechanize + ?? ] or something else? References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> Message-ID: "John" wrote: > Is there a way > to control a browser like firefox from python itself? How about IE? IE is easy enough to control and you have full access to the DOM: >>> import win32com >>> win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB- 0000C05BAE0B}', 0, 1, 1) >>> IE = win32com.client.DispatchEx('InternetExplorer.Application.1') >>> dir(IE) ['CLSID', 'ClientToWindow', 'ExecWB', 'GetProperty', 'GoBack', 'GoForward', 'GoHome', 'GoSearch', 'Navigate', 'Navigate2', 'PutProperty', 'QueryStatusWB', 'Quit', 'Refresh', 'Refresh2', 'ShowBrowserBar', 'Stop', '_ApplyTypes_', '__call__', '__cmp__', '__doc__', '__getattr__', '__init__', '__int__', '__module__', '__repr__', '__setattr__', '__str__', '__unicode__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', '_prop_map_get_', '_prop_map_put_', 'coclass_clsid'] >>> IE.Visible=True >>> IE.Navigate("http://plone.org") >>> while IE.Busy: pass >>> print IE.Document.getElementById("portlet-news").innerHTML
RSS News
... and so on ... See http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/int ernetexplorer.asp for the documentation. From bdesth.quelquechose at free.quelquepart.fr Wed Jan 24 16:58:42 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Jan 2007 22:58:42 +0100 Subject: Static variables In-Reply-To: References: Message-ID: <45b7cfd4$0$16160$426a74cc@news.free.fr> Neil Cerutti a ?crit : > On 2007-01-24, Florian Lindner wrote: > >>does python have static variables? I mean function-local >>variables that keep their state between invocations of the >>function. > > > Yup. Here's a nice way. I don't how recent your Python must be > to support this, though. > > >>>>def foo(x): > > ... print foo.static_n, x > ... foo.static_n += 1 > ... > >>>>foo.static_n = 0 Yup,I had forgotten this one. FWIW, it's an old trick. There's also the closure solution: def make_foo(start_at=0): static = [start_at] def foo(x): print static[0], x static[0] += 1 return foo foo = make_foo() And this let you share state between functions: def make_counter(start_at=0, step=1): count = [start_at] def inc(): count[0] += step return count[0] def reset(): count[0] = [start_at] return count[0] def peek(): return count[0] return inc, reset, peek foo, bar, baaz = make_counter(42, -1) print baaz() for x in range(5): print foo() print bar() print baaz() From citronelu at yahoo.com Mon Jan 8 14:25:00 2007 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 8 Jan 2007 11:25:00 -0800 Subject: Execute binary code Message-ID: <1168284300.638111.191440@38g2000cwa.googlegroups.com> Is it possible to execute a binary string stored within a python script as executable code ? The script is run under Windows, and the binary code (a full executable file) is stored in a variable in the script. I know I can use os.system() or os.popen() to run an external file, but these functions take as argument a string evaluated as command-line. I also know I could save the binary code as a temporary file, execute it and delete it afterwards, but this is not an alternative. Thanks. From arkanes at gmail.com Fri Jan 12 13:31:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 12 Jan 2007 12:31:54 -0600 Subject: parsing a file name In-Reply-To: <1168626221.581533.128750@s34g2000cwa.googlegroups.com> References: <1168622211.188972.179680@38g2000cwa.googlegroups.com> <1168626221.581533.128750@s34g2000cwa.googlegroups.com> Message-ID: <4866bea60701121031w479f64d2p56f2a9561b972a47@mail.gmail.com> On 12 Jan 2007 10:23:41 -0800, Paul Boddie wrote: > Chris Mellon wrote: > > > > I'm trying to think of a good reason to extract the version from the > > filename instead of using RPM to get the real version from the > > metadata and I can't come up with one. > > The inquirer doesn't have any RPM handling tools installed/available or > is dealing with a lot of versioned filenames which might be a selection > of different, arbitrary formats. > > Try harder! ;-) > > Paul Well, the answer to the first is "get some", so that's not a good reason. And the second would mean that they asked a question on c.l.p without giving all the background information on the task they were doing, and we know that never happens. From rweth at cisco.com Sun Jan 7 03:51:15 2007 From: rweth at cisco.com (rweth) Date: Sun, 07 Jan 2007 00:51:15 -0800 Subject: How to invoke parent's method? In-Reply-To: <1168138626.574514.102060@i15g2000cwa.googlegroups.com> References: <1168138626.574514.102060@i15g2000cwa.googlegroups.com> Message-ID: <1168159875.980990@sj-nntpcache-1.cisco.com> many_years_after wrote: > Hi, pythoners: > > My wxPython program includes a panel whose parent is a frame. The > panel has a button. When I click the button , I want to let the frame > destroy. How to implement it? Could the panel invoke the frame's > method? > Thanks. > I think it "could" if what I read recently in: http://www.python.org/download/releases/2.2/descrintro/#cooperation Is applicable. Look at the link "Cooperative methods and super" Write a subclass of panel where the target method of it's parent is targX (that parent method of Frame that you want to call) class myPanel (Panel): def dadsX (self): Frame.targX(self) I think you are forced to invoke this within a method of the Class itself, as opposed to doing so with an instance. Good luck! From nospam at domain.tld Thu Jan 25 01:56:35 2007 From: nospam at domain.tld (Stephan Kuhagen) Date: Thu, 25 Jan 2007 07:56:35 +0100 Subject: Python does not play well with others References: Message-ID: Dennis Lee Bieber wrote: > Uhm... Unless something has happened that I don't know about, isn't > C# a M$ specific product? Mono? Regards Stephan From sjdevnull at yahoo.com Fri Jan 5 23:57:40 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 5 Jan 2007 20:57:40 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1168041434.385029.55870@38g2000cwa.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1168041434.385029.55870@38g2000cwa.googlegroups.com> Message-ID: <1168059460.614853.193090@q40g2000cwq.googlegroups.com> Patrick Down wrote: > jeremito wrote: > > I am writing a class that is intended to be subclassed. What is the > > proper way to indicate that a sub class must override a method? > > > > Thanks, > > Jeremy > > Decorators to the rescue? > > def must_override(f): > def t(*args): > raise NotImplementedError("You must override " + f.__name__) > return t > > class Foo: > @must_override > def Bar(x,y): pass > > Foo().Bar() > > Traceback (most recent call last): > File "testit.py", line 14, in ? > Foo().Bar() > File "testit.py", line 5, in t > raise NotImplementedError("You must override " + f.__name__) > NotImplementedError: You must override Bar I'd think twice before using a decorator. This just seems less clear to read than simply raising NotImplementedError, and the traceback points into the decorator instead of the function that you really care about. From eurleif at ecritters.biz Mon Jan 29 00:40:06 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 29 Jan 2007 00:40:06 -0500 Subject: Convert from unicode chars to HTML entities In-Reply-To: References: <45bd7a82$0$17928$4d3efbfe@news.sover.net> Message-ID: <45bd8849$0$17928$4d3efbfe@news.sover.net> Steven D'Aprano wrote: > A few issues: > > (1) It doesn't seem to be reversible: > >>>> '© and many more...'.decode('latin-1') > u'© and many more...' > > What should I do instead? Unfortunately, there's nothing in the standard library that can do that, as far as I know. You'll have to write your own function. Here's one I've used before (partially stolen from code in Python patch #912410 which was written by Aaron Swartz): from htmlentitydefs import name2codepoint import re def _replace_entity(m): s = m.group(1) if s[0] == u'#': s = s[1:] try: if s[0] in u'xX': c = int(s[1:], 16) else: c = int(s) return unichr(c) except ValueError: return m.group(0) else: try: return unichr(name2codepoint[s]) except (ValueError, KeyError): return m.group(0) _entity_re = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));") def unescape(s): return _entity_re.sub(_replace_entity, s) > (2) Are XML entities guaranteed to be the same as HTML entities? XML defines one entity which doesn't exist in HTML: '. But xmlcharrefreplace only generates numeric character references, and those should be the same between XML and HTML. > (3) Is there a way to find out at runtime what encoders/decoders/error > handlers are available, and what they do? From what I remember, that's not possible because the codec system is designed so that functions taking names are registered instead of the names themselves. But all of the standard codecs are documented at , and all of the standard error handlers are documented at . From fsckedagain at gmail.com Wed Jan 17 12:18:42 2007 From: fsckedagain at gmail.com (fscked) Date: 17 Jan 2007 09:18:42 -0800 Subject: XLM prolgoue Message-ID: <1169054322.500863.313660@11g2000cwr.googlegroups.com> How do I go about creating the XML prologue like I want it to be? Specifically, I am trying to add encoding and some namespace stuff. From gdamjan at gmail.com Wed Jan 24 19:40:09 2007 From: gdamjan at gmail.com (Damjan) Date: Thu, 25 Jan 2007 01:40:09 +0100 Subject: Question about docutils Message-ID: <45b7fca1$0$49206$14726298@news.sunsite.dk> I'm using docutils 0.4. Is it possible to define special custom 'tags' (or something) that will invoke my own function? The function would then return the real content in the ReST document. -- damjan From hg at nospam.org Fri Jan 5 06:16:42 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 12:16:42 +0100 Subject: Undefined symbol __pure_virtual when importing MySQLdb References: <1167977378.425615.220350@51g2000cwl.googlegroups.com> Message-ID: <5Cwnh.47481$gl2.933@newsfe16.lga> antonyliu2002 at yahoo.com wrote: > I downloaded MySQL-python-1.2.1 from SourceForge and installed it on a > Mandrake system (Mandrake Linux 9.2 3.3.1-2mdk on linux2). > > The installation was successful. The gcc version is 3.3. > > My Python version is 2.4.2. When I import MySQLdb, I get an error > which says that __pure_virtual is an undefined symbol. > > Look: > >>>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/local/python2.4/site-packages/MySQLdb/__init__.py", line > 19, in ? > import _mysql > ImportError: /usr/local/python2.4/site-packages/_mysql.so: undefined > symbol: __pure_virtual > > By the way, mysql (5.0.27-standard)is running OK on the Mandrake > system. Look: > > [antonyliu at myhost antonyliu]$ mysql -u root -p > Enter password: > Welcome to the MySQL monitor. Commands end with ; or \g. > Your MySQL connection id is 13 to server version: 5.0.27-standard > > Type 'help;' or '\h' for help. Type '\c' to clear the buffer. > > mysql> > > I have googled hard, and did see someone asking the same question, but > haven't found a good solution to this problem. Could anyone give me a > hint? Thanks a lot! Hi, I can only say that it runs fine under Mandriva 2007 ... and that Mandriva went to gcc V4 long after 9.2 ... maybe an issue here. Regards, hg From wolf_tracks at invalid.com Wed Jan 24 16:06:35 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 24 Jan 2007 21:06:35 GMT Subject: Python Windows Editors In-Reply-To: References: Message-ID: Stef Mientki wrote: > Any text editor is only as good as the >> programmer who uses it. ;) >> > Yes but an IDE is different ;-) > > cheers, > Stef Mientki Correct. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Depend upon it, there is nothing so unnatural as the commonplace." -- Sherlock Holmes, in "A Case of Identity" -- Web Page: From laurent.pointal at limsi.fr Fri Jan 12 05:06:52 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 12 Jan 2007 11:06:52 +0100 Subject: pygame and python 2.5 In-Reply-To: References: Message-ID: siggi a ?crit : > Hi all, > > when I rtry to install pygame (pygame-1.7.1release.win32-py2.4.exe, the most > ciurrent version I found) it requires Python 2.4! Will I really have to > uninstall my Python 2.5 and install the old Python 2.4 in order to use > pygame? Note: You can have both versions installed, just be sure to use the right one when using pygame (until there is a 2.5 compatible version). From __peter__ at web.de Thu Jan 25 12:18:52 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Jan 2007 18:18:52 +0100 Subject: Two dimensional lists References: Message-ID: gonzlobo wrote: > I might get an answer since I didn't call them arrays. :^) > > Ok, I have 2 lists that I need to process individually, then merge > them into a 2x list and fill with data. > > arinc429 = ['ab', '2b', '0b', '21', 'c1', '61', '11', 'db', '9b', '5b', > 'eb', > '6b', '1b', '6e', '3e'] > iPIDs = [300, 301, 320, 321] > > merged[arinc429, iPIDs] > > # PID & a429 are defined elsewhere > > a_idx = iPIDs.index[PID] > p_idx = [arinc429.index[a429] > > # shouldn't I be able to fill the lists simply by pointing to a location? > > matrix[a_idx, p_idx] = 0x219 # and so on? The simplest approach is to go with a dictionary: >>> matrix = {} >>> arinc = ['ab', '2b', '0b'] >>> pids = [300, 321] >>> for x in arinc: ... for y in pids: ... matrix[x, y] = y + int(x, 16) # replace with your actual data ... >>> matrix {('ab', 300): 471, ('2b', 300): 343, ('ab', 321): 492, ('0b', 321): 332, ('2b', 321): 364, ('0b', 300): 311} Get one entry: >>> matrix["2b", 321] 364 Get all items along an axis: >>> [matrix[x, 300] for x in arinc] [471, 343, 311] Peter From __peter__ at web.de Thu Jan 25 07:39:08 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Jan 2007 13:39:08 +0100 Subject: While loop with "or"? Please help! References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> <45b8a31d$0$2401$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > and simplified again thanks to Python 'in' operator: > while?not?usrinp.lower()?in?"yn": But note that 'in' performs a substring search and therefore "yn" and "" would be accepted as valid answers, too. Peter From robert.kern at gmail.com Tue Jan 9 16:11:33 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 15:11:33 -0600 Subject: distutils and ctypes In-Reply-To: <45A3FF17.2070509@v.loewis.de> References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> <45A3FF17.2070509@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Not sure it's stupid, but I wonder why you want to use ctypes. What's > wrong with extension modules? What's wrong with ctypes? They're both valid, useful approaches to connect to C libraries. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sickcodemonkey at gmail.com Tue Jan 30 08:49:47 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Tue, 30 Jan 2007 08:49:47 -0500 Subject: Diff between opening files in 'r' and 'r+' mode In-Reply-To: <1170149775.253373.318960@q2g2000cwa.googlegroups.com> References: <1170149775.253373.318960@q2g2000cwa.googlegroups.com> Message-ID: <2adc542f0701300549h740dc90ar1ab1b898ff8787c6@mail.gmail.com> It was a little hard to follow your logic of your sample code (writing, reading and writing again), but (1)The difference between r and r+..... - 'r+' opens the file for both reading and writing. - 'r' should be used when the file will only be read. I am not sure on how you want to store the contents of the file, but I have provided an example below. You could do something like this: ---------------------------------------------------------------------- fileContent = open(fname, 'r') a = fileContent.readlines(); fileContent.close() print a ---------------------------------------------------------------------- (2) If you are just going to read the file, then yes I would use just the 'r' argument. On 30 Jan 2007 01:36:15 -0800, raghu wrote: > > i want to know the difference between 'r' mode and 'r+' mode > 1.i = open('c:\python25\integer.txt','w')-------->for writiing > i.write('hai')--------->written some content in text file > i = open('c:\python25\integer.txt','r')---->for reading > print i.read()---->for printing the contents in that text file > i = open('c:\python25\integer.txt','w')---------->for writing > i.write('how')-----------?Rewrite the contents > print i.read() > [MY QUESTION]:i want to read the text file contents cant it be done by > giving (print i.read())? > Before going to next question [I deleted all the contents in the text > file] > > 2.i = open('c:\python25\integer.txt','r+')-----For reading and writing > i.write('hai')--------->written some content to text file > print i.read()--------->{? ?('c:\python25\integer.txt','w') > i write('') > print i.read()how') > i = open('c:\python25\integer.txt','r') > print i.read() > i = open('c:\python25\integer.txt','w') > i.write() > i = open('c:\python25\integer.txt','r') > print i.read() } --->Thats what i saw on > interpreter(In curly braces) when i ran the script > [MY QUESTION]:1.from where the above in curly braces is printed?and i > have written only 'hai' to the text file > 2.Should i recall again the opening of the > file in 'r' mode to read the file? > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Jan 18 03:03:48 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Jan 2007 09:03:48 +0100 Subject: question about module resolution References: <1169050133.438101.90030@a75g2000cwd.googlegroups.com> <1169060571.641437.297170@51g2000cwl.googlegroups.com> Message-ID: Emin wrote: > On Jan 17, 11:20 am, Peter Otten <__pete... at web.de> wrote: >> Emin wrote: >> > I often find myself wanting to have a child module get some parameters >> > defined in a parent module. For example, imagine I have the following >> > directory structure and want something in baz.py to look at a value in >> > config.py. I end up putting in things like import sys; >> > sys.path.append('../..'). Is there a better way? >> >> > foo/ >> > __init__.py >> > config.py >> > bar/ >> > __init__.py >> > baz.py >> from __future__ import absolute_import >> from .. import config > I put the lines you suggested in baz.py, but got an error: > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import baz > Traceback (most recent call last): > File "", line 1, in > File "baz.py", line 3, in > from .. import config > ValueError: Attempted relative import in non-package If you put foo/bar in the path and then import baz how do you think that baz is to know that it's actually foo.bar.baz? Make sure that the parent directory of foo is in sys.path (e. g. by starting the interpreter in that directory) and then import baz using its official name. $ tree . `-- foo |-- __init__.py |-- bar | |-- __init__.py | `-- baz.py `-- config.py 2 directories, 4 files $ cat foo/config.py print "importing config" $ cat foo/bar/baz.py from __future__ import absolute_import from .. import config $ python2.5 Python 2.5 (r25:51908, Oct 3 2006, 08:48:09) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import foo.bar.baz importing config Peter From sickcodemonkey at gmail.com Wed Jan 24 21:05:24 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Wed, 24 Jan 2007 21:05:24 -0500 Subject: difflib qualm Message-ID: <2adc542f0701241805i79b79580y2522ec854e49621d@mail.gmail.com> I am trying to write a python script that will compare 2 files which contains names (millions of them). More specifically, I have 2 files (Files1.txt and Files2.txt). Files1.txtcontains 180 thousand names and Files2.txt contains 34 million names. I have a script which will analyze these two files and store them into 2 different lists (fileList1 and fileList2 respectivly). I have imported the diflib library and after the lists are created, matching on the following criteria " " for diflib -> (just the names that are similar between the two files). This works perfectly for hundreds of names but is taking forever for millions of them; thus not really efficient. Does anyone have any idea on how to get this more efficient? (speaking of Time and RAM) Any advice would be greatly appreciated. (NOTE: I have been trying to study multithreading, but have not really grasp the concept. So I may need some examples.) ~~~~~~~~~~~~~~ S.C.M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Mon Jan 15 11:45:20 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 15 Jan 2007 10:45:20 -0600 Subject: How naive is Python? In-Reply-To: <17835.39437.115750.617750@montanaro.dyndns.org> References: <1168848408.785931.285160@q2g2000cwa.googlegroups.com> <17835.39437.115750.617750@montanaro.dyndns.org> Message-ID: <17835.44960.196267.242474@montanaro.dyndns.org> John> Sorry, Skip, but I find that very hard to believe. The foo() John> function would take quadratic time if it were merely adding on John> pieces of constant size -- however len(str(i)) is not a constant, John> it is O(log10(i)), so the time should be super-quadratic. me> Sorry, I should have pointed out that I'm using the latest version me> of Python. I believe += for strings has been optimized to simply me> extend s when there is only a single reference to it. Actually, it isn't until I work my way back to 2.3 that I start to see quadratic behavior: % python2.6 strcopy.py 32 0.00022292137146 6.96629285812e-06 64 0.000907897949219 1.41859054565e-05 128 0.000649929046631 5.0775706768e-06 256 0.00111794471741 4.36697155237e-06 512 0.00260806083679 5.09386882186e-06 1024 0.00437998771667 4.27733175457e-06 2048 0.00921607017517 4.50003426522e-06 4096 0.0191979408264 4.68699727207e-06 8192 0.0694131851196 8.47328919917e-06 16384 0.0976829528809 5.96209429204e-06 32768 0.194766998291 5.94381708652e-06 % python2.5 strcopy.py 32 0.000439167022705 1.37239694595e-05 64 0.000303030014038 4.73484396935e-06 128 0.000631809234619 4.93600964546e-06 256 0.00112318992615 4.38746064901e-06 512 0.00279307365417 5.45522198081e-06 1024 0.00446391105652 4.35928814113e-06 2048 0.00953102111816 4.65381890535e-06 4096 0.0198018550873 4.83443727717e-06 8192 0.175454854965 2.14178289752e-05 16384 0.103327989578 6.30663998891e-06 32768 0.191411972046 5.84142981097e-06 % python2.4 strcopy.py 32 0.000230073928833 7.18981027603e-06 64 0.000307083129883 4.79817390442e-06 128 0.00114107131958 8.91461968422e-06 256 0.00116014480591 4.53181564808e-06 512 0.00231313705444 4.51784580946e-06 1024 0.00459003448486 4.48245555162e-06 2048 0.00974178314209 4.75673004985e-06 4096 0.019122838974 4.66866185889e-06 8192 0.0717267990112 8.75571276993e-06 16384 0.112125873566 6.84362021275e-06 32768 0.188065052032 5.73928991798e-06 % python2.3 strcopy.py 32 0.000223875045776 6.99609518051e-06 64 0.000385999679565 6.03124499321e-06 128 0.000766038894653 5.98467886448e-06 256 0.00154304504395 6.02751970291e-06 512 0.00309181213379 6.03869557381e-06 1024 0.0065929889679 6.43846578896e-06 2048 0.0147500038147 7.20215030015e-06 4096 0.14589214325 3.56181990355e-05 8192 0.778324127197 9.50102694333e-05 16384 3.20213103294 0.000195442567929 32768 14.7389230728 0.000449796236353 % python2.2 strcopy.py 32 0.00031590461731 9.87201929092e-06 64 0.000494003295898 7.71880149841e-06 128 0.00090217590332 7.04824924469e-06 256 0.00173211097717 6.76605850458e-06 512 0.00362610816956 7.08224251866e-06 1024 0.00711607933044 6.94929622114e-06 2048 0.0158200263977 7.7246222645e-06 4096 0.152237892151 3.71674541384e-05 8192 0.89648604393 0.000109434331534 16384 3.14483094215 0.000191945247934 32768 13.3367011547 0.000407003819419 Skip From gagsl-py at yahoo.com.ar Sun Jan 7 17:38:38 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 14:38:38 -0800 Subject: strange for loop construct In-Reply-To: <1168206762.164747.299470@42g2000cwt.googlegroups.com> References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> <12ptf5bl21f2teb@corp.supernews.com> <1168206762.164747.299470@42g2000cwt.googlegroups.com> Message-ID: <1168209518.288765.39380@s80g2000cwa.googlegroups.com> On 7 ene, 18:52, "Dustan" wrote: > Shouldn't that same page be found on the python website?http://www.python.org/doc/2.0/ > Any clue as to why it isn't? For 2.0 it's on http://www.python.org/download/releases/2.0/new-python.htm For later ones, it's on http://www.python.org/download/releases/2.5/NEWS.txt (replacing 2.5 as desired) You can use google with site:www.python.org (or the Search box in the Python web) to locate them. -- Gabriel Genellina From robin at reportlab.com Wed Jan 17 11:05:23 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 17 Jan 2007 16:05:23 +0000 Subject: 2.3-2.5 what improved? In-Reply-To: <1169038574.260669.194760@s34g2000cwa.googlegroups.com> References: <1169038574.260669.194760@s34g2000cwa.googlegroups.com> Message-ID: <45AE4943.3080700@chamonix.reportlab.co.uk> bruno.desthuilliers at gmail.com wrote: > Robin Becker a ?crit : >........ > > AFAIK, most of the speedup comes from optimization of the builtin dict > type, which is the central > data structure in Python. But anyway, as Robert pointed out, using CGI > means lauching > a new Python process for each and every HTTP request. > >> Presumably we have a lot of old >> cruft that could be improved in some way eg moving loops into comprehensions, >> using iterator methods etc. Are those sort of things what we should look at? > > Consider profiling your code before doing anything else - unless you're > planning on wasting your time. our major show stoppers(stuff like stringWidth) are already in C; the remainder are rather complex methods to do things like paragraph splitting. We're already considering fcgi to eliminate the startup time. A trial with psyco indicates another 15% could be obtained there, but I don't think we can use that on the target platform (which I think is sparc). -- Robin Becker From __peter__ at web.de Tue Jan 16 03:42:43 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 Jan 2007 09:42:43 +0100 Subject: for v in l: References: Message-ID: Gert Cuykens wrote: > is there a other way then this to loop trough a list and change the values > > i=-1 > for v in l: > i=i+1 > l[i]=v+x > > something like > > for v in l: > l[v]=l[v]+x Be generous, create a new list: items = [value + delta for value in items] That will require some extra peak memory, but is faster. Also, code relying on lists not being changed in place tends to be more robust (and better looking) than code relying on lists being changed in place :-) If you cannot rebind the list variable, use slices: items[:] = [value + delta for value in items] If the list is huge and you have to economize memory, use enumerate(): for index, value in enumerate(items): items[index] = value + delta Peter From michele.simionato at gmail.com Sat Jan 27 01:09:50 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Jan 2007 22:09:50 -0800 Subject: instancemethod In-Reply-To: References: <1169872049.261689.263820@j27g2000cwj.googlegroups.com> Message-ID: <1169878190.392229.277600@k78g2000cwa.googlegroups.com> On Jan 27, 6:39 am, Steven D'Aprano wrote: > > It seems that the description of __new__ is wrong. Since __new__ takes an > implicit first argument, the class, it is a class method, not a static > method. No: >>> class C(object): ... def __new__(cls): pass >>> C.__dict__['__new__'] Moreover, citing from http://www.python.org/download/releases/2.2.3/descrintro/#staticmethods """ * Factoid: __new__ is a static method, not a class method. I initially thought it would have to be a class method, and that's why I added the classmethod primitive. Unfortunately, with class methods, upcalls don't work right in this case, so I had to make it a static method with an explicit class as its first argument. Ironically, there are now no known uses for class methods in the Python distribution (other than in the test suite). However, class methods are still useful in other places, for example, to program inheritable alternate constructors. """ So, I stand my point. Michele Simionato From toby at tobiah.org Mon Jan 22 15:44:55 2007 From: toby at tobiah.org (Tobiah) Date: Mon, 22 Jan 2007 12:44:55 -0800 Subject: AES and Credit card number encryption Message-ID: <45b5159e$0$24377$88260bb3@free.teranews.com> I browsed this subject and thought I might use the 'AES' cypher scheme to do this. Would this be a good choice? I came across a "Python Cryptography Toolkit" http://www.amk.ca/python/code/crypto which has a nice AES implementation, but in the example, a simple string is passed as the key: obj=AES.new('abcdefgh', AES.ECB) So my real question is, how do I go about generating the best key. Isn't the length supposed to be a 2^n bits, and soforth? Thanks, Tobiah -- Posted via a free Usenet account from http://www.teranews.com From ptmcg at austin.rr.com Tue Jan 23 20:33:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jan 2007 17:33:31 -0800 Subject: Simple Matrix class In-Reply-To: References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> Message-ID: <1169602411.917985.89840@l53g2000cwa.googlegroups.com> On Jan 23, 6:59 pm, Robert Kern wrote: > Paul McGuire wrote: > > I've posted a simple Matrix class on my website as a small-footprint > > package for doing basic calculations on matrices up to about 10x10 in > > size (no theoretical limit, but performance on inverse is exponential). > > Why is that? A simple and robust LU decomposition should be no more than O(n**3). > > -- > Robert Kern Well "3" is an exponent isn't it? :) In truth, in my laziness, I didn't *actually* test the performance. But after measuring inversion times for nxn matrices for n=2 to 12, I get these results (run on Python 2.4.2, on a 2GHz CPU): n seconds ln(seconds) 2 0.000411225449045 -7.79636895604 3 0.00102247632031 -6.88552782893 4 0.00437541642862 -5.43175358002 5 0.0146999129778 -4.21991370509 6 0.0507813143849 -2.98022681913 7 0.143077961026 -1.94436561528 8 0.39962257773 -0.917234732978 9 1.14412558021 0.134640659841 10 3.01953516439 1.10510290046 11 8.76039971561 2.17024153354 12 21.8032182861 3.0820575867 Plotting n vs. ln(seconds) gives a fairly straight line of slope about 1.09, and exp(1.09) = 2.97, so your big-O estimate seems to line up nicely with the experimental data - I couldn't have fudged it any better. -- Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 26 11:25:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 26 Jan 2007 17:25:37 +0100 Subject: instancemethod In-Reply-To: References: <45b51298$0$8289$426a74cc@news.free.fr> Message-ID: <45ba2b72$0$3007$426a34cc@news.free.fr> Gert Cuykens a ?crit : > import MySQLdb > > class Db(object): > > def __enter__(self): > pass > > def __init__(self,server,user,password,database): > self._db=MySQLdb.connect(server , user , password , database) > self._db.autocommit(True) > self.cursor=self._db.cursor() > > def execute(self,cmd): > self.cursor.execute(cmd) > self.rowcount=int(self.cursor.rowcount) isn't cursor.rowcount already an int ? > def close(self): > self.cursor.close() > self._db.close() > > def __getattr__(self, name): > attr = getattr(self._cursor, name,getattr(self._db, name, None)) > if attr is None: > raise AttributeError("object %s has no attribute %s" > %(self.__class__.__name__, name)) > return attr > > def __del__(self): > try: > self.close() > finally: > pass > except: > pass The finally clause is useless here. > def __exit__(self): > pass > > if __name__ == '__main__': > gert = Db('localhost','root','*****','gert') > gert.execute('select * from person') > for row in gert.cursor: > print row > > with Db('localhost','root','*****','gert') as gert: > gert.excecute('select * from person') > for row in gert.cursor: > print row > > Desktop/svn/db/Py/db.py:45: Warning: 'with' will become a reserved > keyword in Python 2.6 > File "Desktop/svn/db/Py/db.py", line 45 > with Db('localhost','root','*****','gert') as gert: > ^ > SyntaxError: invalid syntax > > I was thinking if it would be possible to create a object that uses > it's own instance name as a atribute. class Obj(object): pass toto = tutu = tata = titi = Obj() What's an "instance name" ? From steve at REMOVEME.cybersource.com.au Mon Jan 29 00:13:05 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 29 Jan 2007 16:13:05 +1100 Subject: Convert from unicode chars to HTML entities References: <45bd7a82$0$17928$4d3efbfe@news.sover.net> Message-ID: On Sun, 28 Jan 2007 23:41:19 -0500, Leif K-Brooks wrote: > >>> s = u"? and many more..." > >>> s.encode('ascii', 'xmlcharrefreplace') > '© and many more...' Wow. That's short and to the point. I like it. A few issues: (1) It doesn't seem to be reversible: >>> '© and many more...'.decode('latin-1') u'© and many more...' What should I do instead? (2) Are XML entities guaranteed to be the same as HTML entities? (3) Is there a way to find out at runtime what encoders/decoders/error handlers are available, and what they do? Thanks, -- Steven D'Aprano From steve at REMOVE.THIS.cybersource.com.au Thu Jan 25 10:40:16 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 26 Jan 2007 02:40:16 +1100 Subject: Please have a look at this class References: <1169735908.009109.7460@a75g2000cwd.googlegroups.com> Message-ID: On Thu, 25 Jan 2007 06:38:28 -0800, antred wrote: > Hello everyone, > > While working on a program I encountered a situation where I'd > construct a largish data structure (a tree) from parsing a host of > files and would end up having to throw away parts of my newly built > tree if a file turned out to contain invalid data. Why not validate the file before you add it to the tree? > My first thought was > 'Well, you can always make a deep copy of your tree first, then add new > data to the copy and revert to the original if you need to.", but as > this tree can grow very big this is not exactly efficient. My first thought would have been to just delete the invalid node from the tree. BTW, what sort of tree are you using? A basic binary tree, or something more sophisticated? Deleting nodes from trees need not be expensive. > So my second idea was to come up with a class that offers a very > limited degree of database-like behavior, meaning you can make changes > to the object and then decide whether you want to commit those changes > or roll them back to get back to the original. I don't know whether that would be a useful tool to have in general. How do you use it? I can guess two broad strategies: (1) commit; add; validate; commit or roll-back. That seems wasteful, because if you're adding only a single node to the tree, it should be *very* easy to delete it and revert to the previous state. Alternatively: (2) commit; add multiple times; validate multiple items; commit the lot, or roll-back the lot and then re-add the ones that validated. But does it really make sense to be rolling back a whole lot of transactions, just because one of them is faulty? I don't think so. In this specific example, I think the right solution is to make adding and deleting a file an atomic operation (or at least as close to atomic as Python allows), so you don't need to think about attributes. You just add or delete nodes. Anyway, that's the solution I'd be looking at. [snip] > The basic idea behind this is that each instance of the Unrollable > class keeps an internal dictionary (which, in lieu of a better name I'm > currently calling 'sand box') Bad name! "Sand box" already has an established usage, and that's not it. A better name might be something like "provisional" or "uncommitted" or similar. [snip] > Finally, this works for 'private' attributes (i.e. names with two > leading underscores), too, as the __setattr__ implementation mangles > the name of the attribute if it detects a private name. I think it would be better NOT to mangle the names of the attribute, as that defeats the purpose of name mangling in the first place. If the user of your code wants to muck about with private variables, then he should mangle the name before passing it to your code. [snip] > class Unrollable( object ): > """Provides a very simple commit/rollback system.""" > > def __setattr__( self, attributeName, attributeValue ): > """Changes the specified attribute by setting it to the passed value. > The change is only made to the sandbox and is not committed.""" > > if attributeName.find( '__' ) == 0: > # Mangle name to make attribute private. > attributeName = '_' + self.__class__.__name__ + attributeName You use mangle twice in your code -- that should be factored out as a function or method. Or better yet, just don't do it at all. > try: > theDict = self.__dict__[ '_Unrollable__dSandBox' ] > except KeyError: > theDict = self.__dict__[ '_Unrollable__dSandBox' ] = {} Use this instead: theDict = self.__dict__.setdefault('_Unrollable__dSandBox', {}) > theDict[ attributeName ] = attributeValue > > > def __getattr__( self, attributeName ): > """This method ensures an attribute can be accessed even when it > hasn't been committed yet (since it might not exist in the object > itself yet).""" Doesn't that defeat the purpose of having a distinct commit? If something hasn't been committed, you shouldn't be able to access it! [snip] What about commits/roll-backs for deletion of attributes? > def commitChanges( self ): > """Commits the contents of the sandbox to the actual object. Clears > the sandbox.""" > while len( self.__dSandBox ) > 0: > key, value = self.__dSandBox.popitem() > self.__dict__[ key ] = value If you change the name of your class, or subclass it, your 'sandbox' will break. Here, you use a double-underscore name and let Python mangle it, but earlier you hard-coded the mangled name. Do one or the other, not both. > def unroll( self, bRecurseSandBox = True, bRecurseDict = False ): > """Ditches all changes currently in the sandbox. Recurses all objects > in the instance itself and in its sandbox and, if > they're unrollable instances themselves, invokes the unroll method on > them as well.""" But if you're ditching the objects in the 'sandbox', why would you need to unroll them? Aren't they going to disappear? > if bRecurseSandBox: > while len( self.__dSandBox ) > 0: > key, value = self.__dSandBox.popitem() > > if isinstance( value, Unrollable ): > value.unroll( bRecurseSandBox, bRecurseDict ) > else: > self.__dSandBox.clear() > > if bRecurseDict: > iterator = self.__dict__.itervalues() > > while True: > try: > nextVal = iterator.next() > except StopIteration: > break > > if isinstance( nextVal, Unrollable ): > nextVal.unroll( bRecurseSandBox, bRecurseDict ) Use this instead: for nextVal in iterator: if isinstance( ... ): > def hasUncommittedChanges( self ): > """Returns true if there are uncommitted changes, false otherwise.""" > return len( self.__dSandBox ) > 0 Which will fail if the 'sandbox' doesn't exist. In other parts of the code you test for its existence. Another thing... I notice that you seem to be inconsistently using a form of the Hungarian Notation (e.g. dSandbox, bRecurseDict, etc.). I suggest you read this for a better understanding of when you should do so: http://www.joelonsoftware.com/articles/Wrong.html Hope this was helpful, -- Steven. From gagsl-py at yahoo.com.ar Tue Jan 16 20:55:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 22:55:19 -0300 Subject: How can I create a linked list in Python? In-Reply-To: References: Message-ID: <7.0.1.0.0.20070116224531.04673008@yahoo.com.ar> At Tuesday 16/1/2007 17:07, Dongsheng Ruan wrote: >Thanks for your kindly help. >I am new CS student taking datat structure and algorithms with AHO's book >with the same title. > >The book is done in Pascal, which might be an outdated language. > >However, my instructor probably wants us to understand the list ADT better >by not using the built in list in Python. Just use the same structure as the book. Instead of nil, use None; instead of new(P) where P:^Foo, use P=Foo(); records become classes without methods... Anyway, implementing linked lists, dictionaries, and other basic structures in a language like Pascal, or C -which doesn't have them natively- may be a good learning exercise. But doing that in Python is not a good idea. Of course, using Python in a second or third algorithms course *is* a good idea, because you can forget about these implementation details and concentrate on the algorithms. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From deets at nospam.web.de Tue Jan 23 06:23:26 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 Jan 2007 12:23:26 +0100 Subject: How to instantiate a different class in a constructor? References: Message-ID: <51m9heF1kgf4kU1@mid.uni-berlin.de> > I have a class URI and a bunch of derived sub-classes for example > HttpURI, FtpURI, HttpsURI, etc. (this is an example, I know there is > module urllib & friends, however my actual problem however maps very > well to this example). > > Now I want to pass a string to constructor of URI() and get an instance > of one of the subclasses back. For example uri=URI('http://abcd/...') > will make 'uri' an instance of HttpURI class, not instance of URI. > > To achieve this I have a list of all subclasses of URI and try to > instantiate one by one in URI.__new__(). In the case I pass e.g. FTP URI > to HttpURI constructor it raises ValueError exception and I want to test > HttpsURI, FtpURI, etc. Use a factory function: class UriBase(object): REGISTRY = {} class HttpUri(UriBase): pass UriBase.REGISTRY['http'] = HttpUri def URI(arg): return UriBase.REGISTRY[get_protocol(arg)](arg) This is untested and could be enhanced by e.g. using metaclasses to perform the registration automagicall, but I think you get the idea. Diez From rw at smsnet.pl Wed Jan 31 07:59:46 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 31 Jan 2007 04:59:46 -0800 Subject: Help needed on config files In-Reply-To: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> References: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> Message-ID: <1170248385.900158.241470@v45g2000cwv.googlegroups.com> jvdb wrote: > Hi there, > > I am quite new on python programming and need some help on solving my > problem.. > > I have to make a (python) program which deletes files from > directories. I don't think deleting, etc. is the problem. The problem > is that the directories where i have to delete them are 'dynamic'/ > subject to change. So what i thought is to make a config file > containing an identifier (useful for myself) and there the directory. > something like: > [PROJECTx] > > [PROJECTy] > What about this? # proj.cfg [PROJECTx] path=/path/to/dir1 [PROJECTy] path=/path/to/dir2 # cfg.py from ConfigParser import ConfigParser cfg = ConfigParser() cfg.read("proj.cfg") for proj in cfg.sections(): path = cfg.items(proj)[0][1] print "proj: %s, path: %s" % (proj, path) Is that not enough? -- HTH, Rob From martin.witte at gmail.com Mon Jan 8 11:19:11 2007 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 8 Jan 2007 08:19:11 -0800 Subject: sys.exit versus raise SystemExit In-Reply-To: <45a26b70$0$32019$fa0fcedb@news.zen.co.uk> References: <45a26b70$0$32019$fa0fcedb@news.zen.co.uk> Message-ID: <1168273151.359419.118640@42g2000cwt.googlegroups.com> Will McGugan wrote: > Hi, > > Is there any difference between calling sys.exit() and raise SystemExit? > Should I prefer one over the other? > > Regards, > > Will McGugan > -- > blog: http://www.willmcgugan.com sys.exit() raises a SystemExit, see http://docs.python.org/lib/module-sys.html From perica.zivkovic at gmail.com Thu Jan 11 11:37:03 2007 From: perica.zivkovic at gmail.com (perica.zivkovic at gmail.com) Date: 11 Jan 2007 08:37:03 -0800 Subject: Portable Python - free portable development environment ! Message-ID: <1168533423.224355.221390@k58g2000hse.googlegroups.com> Hi there, I would like to announce the *first* beta release of the Portable Python 1.0 beta. From today Portable Python website is also online and you can find it on the location www.PortablePython.com. About: Portable Python is a Python programming language preconfigured to run directly from a portable device (USB stick, iPod etc.), enabling you to have, at any time, portable programming environment. Just download and extract to your portable device and in 10 minutes you are ready to create your next Python application. No registry modifications, installations, totally portable. Where to find it: http://www.portablepython.com regards, Perica Zivkovic P.S. did I mentioned that it is free? :-) From bearophileHUGS at lycos.com Tue Jan 2 21:37:30 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Jan 2007 18:37:30 -0800 Subject: Iterate through list two items at a time In-Reply-To: References: Message-ID: <1167791850.072999.288710@48g2000cwx.googlegroups.com> Few alternative solutions (other are possible), I usually use a variant of the first version, inside a partition function, the second variant is shorter when you don't have a handy partition() function and you don't want to import modules, and the forth one needs less memory when the data is very long: from itertools import izip, islice data = [1,2,3,4,5,6,7] for x1, x2 in (data[i:i+2] for i in xrange(0, len(data)/2*2, 2)): print x1, x2 for x1, x2 in zip(data[::2], data[1::2]): print x1, x2 for x1, x2 in izip(data[::2], data[1::2]): print x1, x2 for x1, x2 in izip(islice(data,0,None,2), islice(data,1,None,2)): print x1, x2 Bye, bearophile From bdesth.quelquechose at free.quelquepart.fr Sat Jan 6 17:25:09 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Jan 2007 23:25:09 +0100 Subject: still struggling, howto use a list-element as a name ? In-Reply-To: <182cf$45a00556$d443bb3a$17174@news.speedlinq.nl> References: <182cf$45a00556$d443bb3a$17174@news.speedlinq.nl> Message-ID: <45a01b8c$0$319$426a74cc@news.free.fr> Stef Mientki a ?crit : > rzed wrote: (snip) >> class Power_Supply(device): >> def __init__(self): >> self.pin = { >> 0:dict(Name='GND',Value=_DIG_OUT,something=_par2), >> 1:dict(Name='VCC',Value=_DIG_OUT,something=_par33), >> } > > Why so complex, I need 10 or more parameters (or empty), or empty ??? > and then this becomes completely unreadable. Named parameters are way much readables than a 10+ tuple. No one is going to remember a 10+ list of params. > As this is part of the "user interface", > (I want that completely unknown with Python people, > write these lines), From tundra at tundraware.com Mon Jan 8 04:12:54 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Mon, 08 Jan 2007 03:12:54 -0600 Subject: Walking The Right Path Message-ID: Ah yes, moral philosophy and python all come together... Er, that is to day: Imagine you have this situation on a *nix filesystem: Symlink A: /foo -> /usr/home Symlink B: /bar -> /foo/username If I do this: import os print os.path.realpath("/bar") I get this (as one would expect): /usr/home/username However, what if I want to get back the result in this form: /foo/username IOW, is there a way to return a symlink-based path which contains the symlink pointer as is was *defined* not as it expands? TIA, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From sebastien.thur at laposte.net Tue Jan 9 07:52:53 2007 From: sebastien.thur at laposte.net (seb) Date: 9 Jan 2007 04:52:53 -0800 Subject: line duplication using logging to file In-Reply-To: <45a3850d$0$16962$4c368faf@roadrunner.com> References: <1168329975.491514.282000@11g2000cwr.googlegroups.com> <45a3850d$0$16962$4c368faf@roadrunner.com> Message-ID: <1168347173.137262.287640@v33g2000cwv.googlegroups.com> Hi, Thanks for the help. Meanwhile I have written the logging function from scratch and it works without the multiple lines. This means that the multiple line copy is not due to the multiple processes (or thread) trying to access the log file but to something else. Thanks. Sebastien. the new function : import logging import time def write_log(level, message): nom_logger="main_log_file.txt" logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename=nom_logger, filemode='w') if str(level).lower() == "info" : logging.info(str(message)) elif str(level).lower() =="error": logging.error(str(message)) elif str(level).lower()=="warning" : logging.warning(str(message)) elif str(level).lower() =="critical": logging.critical(str(message)) elif str(level).lower() == "exception": logging.exception(str(message)) else : logging.INFO(str(message)) return Paul McGuire a ?crit : > "seb" wrote in message > news:1168329975.491514.282000 at 11g2000cwr.googlegroups.com... > > Hi, I am writing to a file some basic information using the logging > > module. It is working but in the log file some line are printed > > several time. I had put some print debugging messages in the logging > > function (so they appear on the consile) and they are called once only. > > Obviously there is some understantding of the logging module that I am > > missing. > > > > My simple logging program (see below) is called by several processes. > > In this way I can collect the information from various sources (and not > > use the network enabled logging module) > > > > I am using python 2.4 on WinXP SP2. > > > > Do you have any idea ? Thanks in advance. > > > > Seb. > > > > A quick tally of log messages by timestamp and comment gives this data: > > ('2007-01-08 18:26:19,578', '___init_rs232initrs232_openCOM1') : 1 > ('2007-01-08 18:26:19,578', '___run____thread lance') : 2 > ('2007-01-08 18:26:32,015', '___test1TEST 1 = OK') : 3 > ('2007-01-08 18:26:42,483', '___test1TEST 1 = OK') : 4 > ('2007-01-08 18:26:53,750', '___test1TEST 1 = OK') : 5 > ('2007-01-08 18:27:03,092', '___test1TEST 1 = OK') : 6 > ('2007-01-08 18:27:13,671', '___test1TEST 1 = OK') : 7 > ('2007-01-08 18:27:14,796', '___run___fin dans le run car continue = 0') : 8 > ('2007-01-08 18:27:14,890', "___stopthread demande d'arret") : 9 > ('2007-01-09 08:51:26,562', '___init_rs232initrs232_openCOM1') : 1 > ('2007-01-09 08:51:26,733', '___run____thread lance') : 2 > ('2007-01-09 08:51:39,453', '___test1TEST 1 = OK') : 3 > ('2007-01-09 08:51:48,280', '___test1TEST 1 = OK') : 4 > ('2007-01-09 08:51:58,750', '___test1TEST 1 = OK') : 5 > ('2007-01-09 08:52:09,812', '___test1TEST 1 = OK') : 6 > ('2007-01-09 08:52:19,078', '___test1TEST 1 = OK') : 7 > ('2007-01-09 08:52:22,078', '___run___fin dans le run car continue = 0') : 8 > ('2007-01-09 08:52:22,125', "___stopthread demande d'arret") : 8 > ('2007-01-09 08:52:22,125', "___stopthread demande d'arret ") : 1 > > Does this suggest anything to you? > > -- Paul > > > (BTW, here is the pyparsing program I used to do this analysis) > > from pyparsing import > Word,nums,Combine,alphas,oneOf,Literal,SkipTo,restOfLine > > # create pyparsing grammar definition for a log line > date = Word(nums,exact=4)+'-'+Word(nums,exact=2)+'-'+Word(nums,exact=2) > time = Word(nums,exact=2)+':'+Word(nums,exact=2)+':'+Word(nums,exact=2)+ \ > ','+Word(nums,exact=3) > timestamp = Combine(date + ' ' + time) > severity = oneOf( ["INFO","WARNING"] ) # not complete, but enough for this > data > backslash = Literal("\\") > fileref = Combine(Word(alphas,exact=1)+":" + backslash + SkipTo(".py") + > ".py") > logline = ( timestamp.setResultsName("timestamp") + "-" + > severity.setResultsName("severity") + "-" + > fileref.setResultsName("fileref") + > restOfLine.setResultsName("comment") ) > > # create list of ParseResults, with addressable log line elements by results > name > logEntries = [ logline.parseString(line) for line in logdata ] > > # tally up log lines by timestamp and comment > tallyByTimestamp = {} > for entry in logEntries: > tallyKey = (entry.timestamp, entry.comment) > tallyByTimestamp[tallyKey] = tallyByTimestamp.get(tallyKey,0) + 1 > > for ts in sorted( tallyByTimestamp.items() ): > print "%s : %d" % ts From bearophileHUGS at lycos.com Sat Jan 27 06:44:26 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 Jan 2007 03:44:26 -0800 Subject: Fixed length lists from .split()? In-Reply-To: References: <2007012611072716807-bob@passcalnmtedu> Message-ID: <1169898266.455515.268440@j27g2000cwj.googlegroups.com> Duncan Booth: > def nsplit(s, sep, n): > return (s.split(sep) + [""]*n)[:n] Another version, longer: from itertools import repeat def nsplit(text, sep, n): """ >>> nsplit("bcsn; 1000001; 1456", ";", 3) ['bcsn', ' 1000001', ' 1456'] >>> nsplit("bcsn; 1000001", ";", 3) ['bcsn', ' 1000001', ''] >>> nsplit("bcsn", ";", 3) ['bcsn', '', ''] >>> nsplit("", ".", 4) ['', '', '', ''] >>> nsplit("ab.ac.ad.ae", ".", 2) ['ab', 'ac', 'ad', 'ae'] """ result = text.split(sep) nparts = len(result) result.extend(repeat("", n-nparts)) return result if __name__ == "__main__": import doctest doctest.testmod() Bye, bearophile From mail at microcorp.co.za Thu Jan 11 00:39:27 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 11 Jan 2007 07:39:27 +0200 Subject: Is there a way to protect a piece of critical code? References: Message-ID: <004901c73542$dcabaaa0$03000080@hendrik> "robert" wrote: > Hendrik van Rooyen wrote: > > Hi, > > > > I would like to do the following as one atomic operation: > > > > 1) Append an item to a list > > 2) Set a Boolean indicator > > > I doubt you have to worry at all about this in such simple single-single queue - if there is not a much more complex condition upon the insert order. > And what should the indicator tell? that a new element is there? Yes -that is what I was using it for, and I got bitten - It would fail after five or so hours of running quite happily, because the consumer section, that tested the bool, would try to pop from an empty queue - the consumer section also cleared the boolean when the queue length was zero... A classic case of fuzzy thinking... > > The list itself tells its the length, its guaranteed to be increased _after_ .append() > And you can .pop(0) just so - catching/retring at Key/IndexError at least. I changed to testing the length of the queue to solve the problem, like I said I was just curious to see if the code could be protected. > > List .append() and .pop() will be atomic in any Python though its not mentioned explicitely - otherwise it would be time to leave Python. > > There is also Queue.Queue - though it has unneccessary overhead for most purposes. > > am aware of Queue module - the same app uses it for something else. I dont like too many try -- excepts in the code - I find they confuse me when I try to read it later - and in this case I cannot block on waiting for the queue to fill. > A function to block Python interpreter thread switching in such VHL language would be nice for reducing the need for spreading locks in some cases (huge code - little critical sections). Yet your example is by far not a trigger for this. I also requested that once. Implementation in non-C-Pythons may be difficult. > > probably true - but even here - the problem would be solved by blocking thread switching in the one thread, whereas using locks (or blocks as I would tend to call them) requires fiddling in both threads. > Generally there is also technique for optimistic unprotected execution of critical sections - basically using an atomic counter and you need to provide code for unrolling half executions. Search Google. > > ok thanks will do - Hendrik From hg at nospam.org Wed Jan 10 03:37:41 2007 From: hg at nospam.org (hg) Date: Wed, 10 Jan 2007 09:37:41 +0100 Subject: Need startup suggestions for writing a MSA viewer GUI in python References: Message-ID: Joel Hedlund wrote: > Hi! > > I've been thinking about writing a good multiple sequence alignment > (MSA) viewer in python. Sort of like ClustalX, only with better zoom and > pan tools. I've been using python in my work for a couple of years, but > this is my first shot at making a GUI so I'd very much appreciate some > ideas from you people to get me going in the right direction. Despite my > GUI n00b-ness I need to get it good and usable with an intuitive look > and feel. > > What do you think I should do? What packages should I use? > > For you non-bioinformatic guys out there, an MSA is basically a big > matrix (~1000 cols x ~100 rows) of letters, where each row represents a > biological sequence (gene, protein, etc...). Each sequence has an ID > that is usually shorter than 40 characters (typically, 8-12). Usually, > msa visualizers color the letters and their backgrouds according to > chemical properties. > > I want the look and feel to be pretty much like a modern midi sequencer > (like cubase, nuendo, reason etc...). This means the GUI should have > least three panes; one to the left to hold the IDs, one in the bottom to > hold graphs and plots (e.g: user configurable tracks), and the main one > that holds the actual MSA and occupies most of the space. The left and > bottom panes should be resizable and foldable. > > I would like to be able to zoom and pan x and y axes independently to > view different portions of the MSA, and the left and bottom panes should > follow the main pane. I would also like to be able to use drag'n'drop on > IDs for reordering sequences, and possibly also on the MSA itself to > shift sequences left and right. Furthermore, I would like to be able to > select sequences and positions (individually, in ranges or sparsely). I > would like to have a context sensitive menu on the right mouse button, > possibly with submenus. Finally, I'd like to be able to export printable > figures (eps?) of regions and whole MSAs. > > I'm thinking all three panes may have to be rendered using some sort of > scalable graphics because of the coloring and since I'd like to be able > to zoom freely. I'll also need to draw graphs and plots for the tracks. > Is pygame good for this, or is there a better way of doing it? > > I want my viewer to behave and look like any other program, so I'm > thinking maybe I should use some standard GUI toolkit instead, say PyQT > or PyGTK? Would they still allow me to render the MSA nicely? > > Does this seem like a humongous project? > > Thanks for taking the time! > /Joel Hedlund I do not know if PyGtk and PyQT have demos, but wxPython does and includes PyPlot: an easy way to look at the basic features. hg From bernard.chhun at gmail.com Fri Jan 19 15:14:52 2007 From: bernard.chhun at gmail.com (Bernard) Date: 19 Jan 2007 12:14:52 -0800 Subject: spidering script References: <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d@fdn.com> Message-ID: <1169237692.159550.198580@q2g2000cwa.googlegroups.com> 4 easy steps to get the links: 1. Download BeautifulSoup and import it in your script file. 2. Use urllib2 to download the html of the url. 3. mash the html using BeautifulSoup 4. [code] for tag in BeautifulSoupisedHTML.findAll('a'): print tag [/code] David Waizer a ?crit : > Hello.. > > I'm looking for a script (perl, python, sh...)or program (such as wget) > that will help me get a list of ALL the links on a website. > > For example ./magicscript.pl www.yahoo.com and outputs it to a file, it > would be kind of like a spidering software.. > > Any suggestions would be appreciated. > > David From eastera at gmail.com Wed Jan 3 01:24:01 2007 From: eastera at gmail.com (JTree) Date: 2 Jan 2007 22:24:01 -0800 Subject: A question about unicode() function In-Reply-To: <459ADE48.4000004@redlinepy.com> References: <1167571210.084436.311610@48g2000cwx.googlegroups.com> <1167648187.190860.123680@k21g2000cwa.googlegroups.com> <459ADE48.4000004@redlinepy.com> Message-ID: <1167805441.675586.163280@i12g2000cwa.googlegroups.com> hi, I just removed the unicode() method from my codes. As John Machin said, I had an wrong understanding of unicode and ascii. Paul Watson wrote: > JTree wrote: > > Thanks everyone! > > > > Sorry for my ambiguous question. > > I changed the codes and now it works fine. > > > > > > > > JTree wrote: > >> Hi,all > >> I encountered a problem when using unicode() function to fetch a > >> webpage, I don't know why this happenned. > >> My codes and error messages are: > >> > >> > >> Code: > >> #!/usr/bin/python > >> #Filename: test.py > >> #Modified: 2006-12-31 > >> > >> import cPickle as p > >> import urllib > >> import htmllib > >> import re > >> import sys > >> > >> def funUrlFetch(url): > >> lambda url:urllib.urlopen(url).read() > >> > >> objUrl = raw_input('Enter the Url:') > >> content = funUrlFetch(objUrl) > >> content = unicode(content,"gbk") > >> print content > >> content.close() > >> > >> > >> error message: > >> > >> C:\WINDOWS\system32\cmd.exe /c python test.py > >> Enter the Url:http://www.msn.com > >> Traceback (most recent call last): > >> File "test.py", line 16, in ? > >> content = unicode(content,"gbk") > >> TypeError: coercing to Unicode: need string or buffer, NoneType found > >> shell returned 1 > >> Hit any key to close this window... > >> > >> Any suggestions would be appreciated! > >> > >> Thanks! > > So... How about posting the brief working code? From martin at v.loewis.de Sun Jan 7 15:33:33 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 07 Jan 2007 21:33:33 +0100 Subject: OpenBSD, Apache and Python In-Reply-To: <1168197644.544400.72180@v33g2000cwv.googlegroups.com> References: <1168197644.544400.72180@v33g2000cwv.googlegroups.com> Message-ID: <45a1591d$0$304$9b622d9e@news.freenet.de> Geoff schrieb: > I'm now looking at using fastcgi to run my python. This looks like it's > going to work fine, though I will be using a fcgi interface such as > http://jonpy.sourceforge.net/. There does not seem to be any official > fastcgi module for python. > > Should I be worried about the stability and security of the python fcgi > interfaces? Is there something better (more mature / battle tested)? Certainly: CGI. Performance does not seem to be an issue, so CGI should work just fine. Regards, Martin From martin at v.loewis.de Sun Jan 21 16:38:21 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Jan 2007 22:38:21 +0100 Subject: mmap caching In-Reply-To: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> Message-ID: <45B3DD4D.3010009@v.loewis.de> George Sakkis schrieb: > I've been trying to track down a memory leak (which I initially > attributed erroneously to numpy) and it turns out to be caused by a > memory mapped file. It seems that mmap caches without limit the chunks > it reads, as the memory usage grows to several hundreds MBs according > to the Windows task manager before it dies with a MemoryError. You must be misinterpreting what you are seeing. It's the operating system that decides what part of a memory-mapped file are held in memory, and that is certainly not without limits. Notice that there are several values that can be called "memory usage" (such as the size of the committed address space, the working set size, etc); you don't mention which of these values grows several hundreds MB. Regards, Martin From kbk at shore.net Fri Jan 26 23:24:22 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 26 Jan 2007 23:24:22 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200701270424.l0R4OM59020656@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 421 open ( -2) / 3549 closed (+10) / 3970 total ( +8) Bugs : 943 open (-17) / 6471 closed (+25) / 7414 total ( +8) RFE : 260 open ( +2) / 250 closed ( +1) / 510 total ( +3) New / Reopened Patches ______________________ rlcompleter tab completion in pdb (2007-01-22) http://python.org/sf/1641544 opened by Stephen Emslie logging leaks loggers (2007-01-22) CLOSED http://python.org/sf/1641790 opened by TH Fix error/crash in AST: syntaxerror in complex ifs (2007-01-23) http://python.org/sf/1642547 opened by Thomas Wouters comments to clarify complexobject.c (2007-01-23) http://python.org/sf/1642844 opened by Jim Jewett Fix Bug 1362475 Text.edit_modified() doesn't work (2007-01-24) http://python.org/sf/1643641 opened by Matthias Kievernagel ctypes leaks memory (2007-01-24) CLOSED http://python.org/sf/1643874 opened by Thomas Heller file -> open in stdlib (2007-01-25) http://python.org/sf/1644218 opened by Daniel Nogradi Allow importing built-in submodules (2007-01-25) http://python.org/sf/1644818 opened by Miguel Lobo Patches Closed ______________ Fix for #1601399 (urllib2 does not close sockets properly) (2007-01-03) http://python.org/sf/1627441 closed by gbrandl C99 _Bool support for struct (2006-12-07) http://python.org/sf/1610575 closed by loewis logging leaks loggers (2007-01-22) http://python.org/sf/1641790 closed by vsajip Patch for #1586414 to avoid fragmentation on Windows (2006-10-31) http://python.org/sf/1587674 closed by gustaebel smtplib email renames (2007-01-16) http://python.org/sf/1637162 closed by gbrandl urllib2: email.Utils->email.utils (2007-01-16) http://python.org/sf/1637159 closed by gbrandl urllib: change email.Utils -> email.utils (2007-01-16) http://python.org/sf/1637157 closed by gbrandl tarfile extraction does not honor umask (2006-06-16) http://python.org/sf/1507247 closed by gustaebel Fix crash when replacing sys.stdout in sitecustomize (2007-01-08) http://python.org/sf/1630975 closed by twouters ctypes leaks memory (2007-01-24) http://python.org/sf/1643874 closed by theller New / Reopened Bugs ___________________ 2.3.6.4 Error in append and extend descriptions (2007-01-21) CLOSED http://python.org/sf/1641109 opened by ilalopoulos Python 2.5 gets curses.h warning on HPUX (2007-01-22) http://python.org/sf/1642054 opened by Roy Smith Grammatical Error (2007-01-23) CLOSED http://python.org/sf/1643150 opened by Steve Miller function breakpoints in pdb (2007-01-24) http://python.org/sf/1643369 opened by decitre Emphasize buffering issues when sys.stdin is used (2007-01-24) http://python.org/sf/1643712 opened by Raghuram Devarakonda Problem with signals in a single-threaded application (2007-01-24) http://python.org/sf/1643738 opened by Ulisses Furquim strptime %U broken (2007-01-24) CLOSED http://python.org/sf/1643943 opened by Brian Nahas Error arrow offset wrong (2007-01-25) CLOSED http://python.org/sf/1644239 opened by Cees Timmerman ./configure --prefix=/ breaks, won't build C modules (2007-01-25) http://python.org/sf/1644987 opened by Jim Shankland MIME renderer: wrong header line break with long subject? (2007-01-26) http://python.org/sf/1645148 opened by kxroberto Bugs Closed ___________ Newline skipped in "for line in file" (2007-01-16) http://python.org/sf/1636950 closed by bcannon Over-zealous keyword-arguments check for built-in set class (2006-05-11) http://python.org/sf/1486663 closed by gbrandl urllib2 does not close sockets properly (2006-11-22) http://python.org/sf/1601399 closed by gbrandl subprocess: error redirecting i/o from non-console process (2006-11-27) http://python.org/sf/1603907 closed by astrand Problem running a subprocess (2007-01-13) http://python.org/sf/1634739 closed by astrand subprocess.py: O(N**2) bottleneck (2006-11-17) http://python.org/sf/1598181 closed by astrand 2.3.6.4 Error in append and extend descriptions (2007-01-21) http://python.org/sf/1641109 closed by gbrandl asyncore.py and "handle_expt" (2002-12-16) http://python.org/sf/654766 closed by sf-robot Segfault provoked by generators and exceptions (2006-10-18) http://python.org/sf/1579370 closed by loewis gen_iternext: Assertion `f->f_back != ((void *)0)' failed (2006-05-06) http://python.org/sf/1483133 closed by nnorwitz Python polls unnecessarily every 0.1 second when interactive (2006-09-05) http://python.org/sf/1552726 closed by akuchling subprocess interpreted double quotation wrong on windows (2006-03-09) http://python.org/sf/1446119 closed by astrand tarfile.extract() may cause file fragmentation on Windows XP (2006-10-28) http://python.org/sf/1586414 closed by gustaebel subprocess.py Errors with IDLE (2005-02-17) http://python.org/sf/1126208 closed by astrand subprocess.Popen fails inside a Windows service (2005-07-15) http://python.org/sf/1238747 closed by astrand mailbox.py uses old email names (2007-01-16) http://python.org/sf/1637167 closed by gbrandl subprocess.py fails on Windows when there is no console (2005-11-16) http://python.org/sf/1358527 closed by astrand mailbox.py _fromlinepattern regexp does not support positive (2007-01-11) http://python.org/sf/1633678 closed by akuchling rfc822 module, bug in parsedate_tz (2005-08-01) http://python.org/sf/1249573 closed by gbrandl an extra comma in condition command crashes pdb (2007-01-03) http://python.org/sf/1627316 closed by gbrandl Use of "except:" in logging module (2001-03-28) http://python.org/sf/411881 closed by sf-robot segfaults when using __del__ and weakrefs (2005-12-10) http://python.org/sf/1377858 closed by bcannon Grammatical Error (2007-01-24) http://python.org/sf/1643150 closed by quiver modulefinder is not documented (2004-03-11) http://python.org/sf/914375 closed by theller strptime %U broken (2007-01-24) http://python.org/sf/1643943 closed by bcannon Error arrow offset wrong (2007-01-25) http://python.org/sf/1644239 closed by gbrandl ctypes: Pointer-to-pointer unchanged in callback (2006-10-10) http://python.org/sf/1574588 closed by theller New / Reopened RFE __________________ recursive urlparse (2007-01-24) http://python.org/sf/1643370 opened by anatoly techtonik RFE Closed __________ Add registry functions to windows postinstall (2007-01-14) http://python.org/sf/1635335 closed by loewis From tew24 at spam.ac.uk Fri Jan 19 06:19:16 2007 From: tew24 at spam.ac.uk (Tom Wright) Date: Fri, 19 Jan 2007 11:19:16 +0000 Subject: How to find out if another process is using a file References: Message-ID: Jean-Paul Calderone wrote: > A better solution is to name or place files which are begin written in a > which is recognizable and only rename or move them to their final location > when they have been completely written. > > For example, name files ".new" as they are being written. When they are > fully written, drop the ".new" suffix. On the reader side, ignore any > file with a name ending in ".new". Yes, that would work very neatly but I don't have any control over the writing process. I think the modification time route might be the best option, but thanks to all for their replies. -- I'm at CAMbridge, not SPAMbridge From rzantow at gmail.com Sat Jan 6 22:56:43 2007 From: rzantow at gmail.com (rzed) Date: Sat, 06 Jan 2007 22:56:43 -0500 Subject: still struggling, howto use a list-element as a name ? References: <45a01c05$0$319$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote in news:45a01c05$0$319$426a74cc at news.free.fr: > rzed a ?crit : > (snip) >> for k in self.pin.keys(): >> self.__dict__[self.pin[k]['Name']] = self.pin[k] > > for pin self.pin.values(): > self.__dict__[pin['name']] = pin > D'oh! Of course! Thank you. -- rzed From py at th.on Tue Jan 23 19:55:19 2007 From: py at th.on (py) Date: Wed, 24 Jan 2007 00:55:19 GMT Subject: smtplib starttls gmail example - comments? Message-ID: I would love for anybody to comment on this code with regard to redundancy/efficiency/wordiness or whatever else. for instance, do i understand correctly that i cant have a try: else: without an intervening except:? -dave stdout.write("calling smtp server...") try: server = SMTP(msgsmtp) except: stdout.write("FAIL.") #using .write to avoid the implied \n with print else: server.set_debuglevel(msgdebug) stdout.write("starting tls...") server.ehlo(msgfrom) try: server.starttls() except: stdout.write("FAIL.") else: server.ehlo(msgfrom) #neessary duplication (?) stdout.write("logging in...") try: server.login(msgfrom, msgpass) except: stdout.write("FAIL.") else: stdout.write("sending...") try: server.sendmail(msgfrom, msgto, msgtxt + "\n.\n") except: stdout.write("FAIL.") else: try: server.quit() except sslerror: # a known and largely ignored issue with early EOF in ssl protocol stdout.write("success.") else: stdout.write("success.") From erinhouston at gmail.com Tue Jan 16 11:45:08 2007 From: erinhouston at gmail.com (ina) Date: 16 Jan 2007 08:45:08 -0800 Subject: html + javascript automations = [mechanize + ?? ] or something else? In-Reply-To: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> Message-ID: <1168965900.409623.53970@a75g2000cwd.googlegroups.com> John wrote: > I have to write a spyder for a webpage that uses html + javascript. I > had it written using mechanize > but the authors of the webpage now use a lot of javascript. Mechanize > can no longer do the job. > Does anyone know how I could automate my spyder to understand > javascript? Is there a way > to control a browser like firefox from python itself? How about IE? > That way, we do not have > to go thru something like mechanize? > > Thanks in advance for your help/comments, > --j You want pamie, iec or ishybrowser. Pamie is probably the best choice since it gets patches and updates on a regular basis. http://pamie.sourceforge.net/ From bdesth.quelquechose at free.quelquepart.fr Tue Jan 2 18:14:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Jan 2007 00:14:46 +0100 Subject: list/dictionary as case statement ? In-Reply-To: References: Message-ID: <459ae149$0$20905$426a74cc@news.free.fr> Stef Mientki a ?crit : > > If I'm not mistaken, I read somewhere that you can use > function-names/references in lists and/or dictionaries, Python's functions are objects too - instances of the (builtin) class 'function'. So yes, you can use them like any other object (store them in containers, pass them as arguments, return them from functions etc). > but now I can't > find it anymore. > > The idea is to build a simulator for some kind of micro controller (just > as a general practise, I expect it too be very slow ;-). > > opcodes ={ > 1: ('MOV', function1, ...), > 2: ('ADD', function2, ), > 3: ('MUL', class3.function3, ) > } > > def function1 > # do something complex > > > Is this possible ? Why don't you just try ? def mov(what, where): print "mov() called with %s : %s" % (what, where) def add(what, towhat): print "add() called with %s : %s" % (what, towhat) opcodes = { 1: ('MOV', mov), 2: ('ADD', add), } opcodes[1][1](42, 'somewhere') opcodes[2][1](11, 38) The third example is a bit less straightforward. Unless class3.function3 is a classmethod or staticmethod, you'll need an instance of class3, either before constructing the 'opcodes' dict or when actually doing the call. class SomeClass(object): def some_method(self): print "some_method called, self : %s" % self some_obj = SomeClass() opcodes[3] = ('MUL', some_obj.some_method) opcodes[3][1]() FWIW, using a dict of callables is a common Python idiom to replace the switch statement. HTH From tjgolden at gmail.com Sat Jan 13 05:01:11 2007 From: tjgolden at gmail.com (Tim Golden) Date: 13 Jan 2007 02:01:11 -0800 Subject: WMI Python, writing remotely and retrieving env variables values In-Reply-To: <1168637924.982266.214250@s34g2000cwa.googlegroups.com> References: <1168637924.982266.214250@s34g2000cwa.googlegroups.com> Message-ID: <1168682469.492320.246700@q2g2000cwa.googlegroups.com> Thierry Lam wrote: > I'm using the WMI library for python and I was able to connect to > another computer on the network with the following line: > > c = wmi.WMI(computer="the-network-computer", user="hello", > password="hello") > > Is there a way to write information to a file on that computer? > > How do I read environment variables, for example SystemDrive? Questions of this sort are really Win32 questions rather than Python questions. That's not to say we can't help, but rather that you can probably find an answer by going to a search engine of your choice and typing in, say, "WMI SystemDrive". I did that, and the first hit (from Google) was: http://msdn2.microsoft.com/en-us/library/aa394239.aspx which indicates that it's available from the Win32_OperatingSystem WMI class. So, in Python: import wmi c = wmi.WMI () # optionally on another computer for os in c.Win32_OperatingSystem (): print os # show the whole thing print os.SystemDrive # get only what you want If you were after Environment Variables, then search again, this time for "WMI Environment Variables". Third hit: http://msdn2.microsoft.com/en-us/library/aa394143.aspx pointing to the Win32_Environment class. And so on. Your first question: can I write into a file? is a little more tricky. As far as I know, there's no way even to *create* a file with WMI, let alone write information into it. It's not really a file-manipulation technology. You can get hold of the name of a remote file and other of its properties via the CIM_DataFile class, but you'd have to translate that into an accessible UNC to be able to access it. TJG From gagsl-py at yahoo.com.ar Mon Jan 29 23:54:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 01:54:51 -0300 Subject: interactive prompt in IDLE References: Message-ID: En Mon, 29 Jan 2007 10:16:32 -0300, Jan Kanis escribi?: > Hello everyone, > > I'm trying to change the interactive python prompt. According to the docs > this is done by changing sys.ps1 and sys.ps2 . That works fine when > running python interactively from a command line, but when running in > IDLE > the .ps1 and .ps2 don't seem to exist. > > I suppose this has something to do with Idle and the python shell in it > both running in different processes, with the prompts generated by the > Idle process? > > Does anyone know if and how to change the prompts in IDLE's interactive > python? I'm using Python 2.5 on Windows XP. I change ps1 and ps2 in sitecustomize.py, and both pythonwin and python.exe work fine. I don't usually open IDLE, but ps1 was changed, altough it does not appear to use ps2 (it was replaced by " ") -- Gabriel Genellina From tim.one at comcast.net Sat Jan 13 21:53:59 2007 From: tim.one at comcast.net (Tim Peters) Date: Sat, 13 Jan 2007 20:53:59 -0600 Subject: Maths error References: Message-ID: [Nick Maclaren] >> ... >> Yes, but that wasn't their point. It was that in (say) iterative >> algorithms, the error builds up by a factor of the base at every >> step. If it wasn't for the fact that errors build up, almost all >> programs could ignore numerical analysis and still get reliable >> answers! >> >> Actually, my (limited) investigations indicated that such an error >> build-up was extremely rare - I could achieve it only in VERY >> artificial programs. But I did find that the errors built up faster >> for higher bases, so that a reasonable rule of thumb is that 28 >> digits with a decimal base was comparable to (say) 80 bits with a >> binary base. [Hendrik van Rooyen] > I would have thought that this sort of thing was a natural consequence > of rounding errors - if I round (or worse truncate) a binary, I can be > off by at most one, with an expectation of a half of a least > significant digit, while if I use hex digits, my expectation is around > eight, and for decimal around five... Which, in all cases, is a half ULP at worst (when rounding -- as everyone does now). > So it would seem natural that errors would propagate > faster on big base systems, AOTBE, but this may be > a naive view.. I don't know of any current support for this view. It the bad old days, such things were often confused by architectures that mixed non-binary bases with "creative" rounding rules (like truncation indeed), and it could be hard to know where to "pin the blame". What you will still see stated is variations on Kahan's telegraphic "binary is better than any other radix for error analysis (but not very much)", listed as one of two techincal advantages for binary fp in: http://www.cs.berkeley.edu/~wkahan/MktgMath.pdf It's important to note that he says "error analysis", not "error propagation" -- regardless of base in use, rounding is good to <= 1/2 ULP. A fuller elementary explanation of this can be found in David Goldberg's widely available "What Every Computer Scientist Should Know About Floating-Point", in its "Relative Error and Ulps" section. The short course is that rigorous forward error analysis of fp algorithms is usually framed in terms of relative error: given a computed approximation x' to the mathematically exact result x, what's the largest possible absolute value of the mathematical r = (x'-x)/x (the relative error of x')? This framework gets used because it's more- or-less tractable, starting by assuming inputs are exact (or not, in which case you start by bounding the inputs' relative errors), then successively computing relative errors for each step of the algorithm. Goldberg's paper, and Knuth volume 2, contain many introductory examples of rigorous analysis using this approach. Analysis of relative error generally goes along independent of FP base. It's at the end, when you want to transform a statement about relative error into a statement about error as measured by ULPs (units in the last place), where the base comes in strongly. As Goldberg explains, the larger the fp base the sloppier the relative-error-converted-to-ULPs bound is -- but this is by a constant factor independent of the algorithm being analyzed, hence Kahan's "... better ... but not very much". In more words from Goldberg: Since epsilon [a measure of relative error] can overestimate the effect of rounding to the nearest floating-point number by the wobble factor of B [the FP base, like 2 for binary or 10 for decimal], error estimates of formulas will be tighter on machines with a small B. When only the order of magnitude of rounding error is of interest, ulps and epsilon may be used interchangeably, since they differ by at most a factor of B. So that factor of B is irrelevant to most apps most of the time. For a combination of an fp algorithm + set of inputs near the edge of giving gibberish results, of course it can be important. Someone using Python's decimal implementation has an often very effective workaround then, short of writing a more robust fp algorithm: just boost the precision. From gagsl-py at yahoo.com.ar Thu Jan 11 23:27:18 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Jan 2007 01:27:18 -0300 Subject: How to modify object attribute by python C API In-Reply-To: <1168551428.114028.278940@77g2000hsv.googlegroups.com> References: <1168551428.114028.278940@77g2000hsv.googlegroups.com> Message-ID: <7.0.1.0.0.20070112011259.059a2bf0@yahoo.com.ar> At Thursday 11/1/2007 18:37, Huayang Xia wrote: >I get a python object by running a class' constructor. Then I need to >modify the instance's attribute just like obj.attr1.attr2 = 'a' if in >python's term. > > PyObject* py_obj_attr1 = PyObject_GetAttrString(obj, "attr1"); > PyObject_SetAttrString(py_obj_attr1, "attr2", >PyString_FromString("a")); > Py_DECREF(py_obj_attr1); > >The object py_obj_attr1 is said to be a "New reference". It's >confusing, does it refer to the same object as "obj.attr1" in python's >term? So that the above code equals: obj.attr1.attr2 = 'a' in python's >term. Read the Introduction in the "Python/C API Reference Manual". If you plan to use Python from C code, better learn carefully how reference counting works, or your progam won't work at all (or crash, in unrelated places, at a later time...) Going back to the example, yes, it's like obj.attr1.attr2 = 'a'. But you should check that py_obj_attr1 is not NULL, and the same for PyString_FromString. There are examples in the doc cited and in "Extending and Embedding". -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From michael at mustun.ch Sun Jan 7 17:18:56 2007 From: michael at mustun.ch (Michael M.) Date: Sun, 07 Jan 2007 23:18:56 +0100 Subject: how to find the longst element list of lists In-Reply-To: <45a169f0$0$309$426a34cc@news.free.fr> References: <45a169f0$0$309$426a34cc@news.free.fr> Message-ID: <%keoh.230$L06.209@nntpserver.swip.net> > > Err... this makes three distinct lists, not a list of lists. > Sure. Logically spoken. Not in Python code. Or a number of lists. Sure not [[ bla... ] [bla.]] etc. From gagsl-py at yahoo.com.ar Mon Jan 22 00:58:04 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Jan 2007 02:58:04 -0300 Subject: html + javascript automations = [mechanize + ?? ] or somethingelse? References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> <1169441279.556814.16770@38g2000cwa.googlegroups.com> Message-ID: "John" escribi? en el mensaje news:1169441279.556814.16770 at 38g2000cwa.googlegroups.com... > My python2.5 installation on windows did not come with "win32com". > How do I install/get this module for windows? Look for the pywin32 package at sourceforge.net -- Gabriel Genellina From steve at REMOVEME.cybersource.com.au Mon Jan 15 21:07:40 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 16 Jan 2007 13:07:40 +1100 Subject: assert versus print [was Re: The curious behavior of integer objects] References: Message-ID: On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote: > assert foo(0x10) == 0 # Assertions are much better tests than prints :-) I dispute that assertion (pun intended). Firstly, print statements work even if you pass the -O (optimize) flag to Python. Your asserts don't. Secondly, a bare assertion like that gives you very little information: it just tells you that it failed: >>> x = 1 >>> assert x == 0 Traceback (most recent call last): File "", line 1, in ? AssertionError To provide the same information that print provides, you need something like this: assert x == 0, "x == %s not 0" % x Thirdly, and most importantly, assert and print aren't alternatives, but complementary tools. Assertions are good for automated testing and simple data validation, where you already know what values you should have. Printing is good for interactively exploring your data when you're uncertain about the values you might get: sometimes it is hard to know what you should be asserting until you've seen what results your function returns. -- Steven D'Aprano From python.leojay at gmail.com Tue Jan 16 21:52:36 2007 From: python.leojay at gmail.com (Leo Jay) Date: Wed, 17 Jan 2007 10:52:36 +0800 Subject: how to use xmlrpc properly in windows xp Message-ID: <4e307e0f0701161852r382c20eayad652cc50d8c04a1@mail.gmail.com> i just wrote a server and client for xmlrpc test. if server and client run in the same machine, everything is fine. but if server and client run in different machine, the speed is unbearably slow. i tried several times, and the approx time is about 18.5 sec to invoke server.test() 5 times. i had turned off the firewall in windows before running those tests. but what interesting is, if i run the server in a FreeBSD machine, the speed boosts up to less than 1 sec to invoke server.test() 5 times. approx 20 times faster. any suggestions? thanks in advance. here is my source code. ############# server.py ############# from SimpleXMLRPCServer import SimpleXMLRPCServer import SocketServer port = 31281 a = 1 def test(): global a a += 1 print a return a def main(): # Create server print 'listening at port', port server = SimpleXMLRPCServer(("", port)) server.register_introspection_functions() server.register_function(test) server.serve_forever() if __name__ == '__main__': main() ############# client.py ############# import xmlrpclib from datetime import datetime server = xmlrpclib.Server("http://%s:%d" % ('192.168.0.92', 31281)) start = datetime.now() print server.test() print server.test() print server.test() print server.test() print 'total: ', datetime.now() - start -- Best Regards, Leo Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: From toby at tobiah.org Wed Jan 10 15:09:43 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 10 Jan 2007 12:09:43 -0800 Subject: Read CSV file into an array In-Reply-To: <1168396138.395017.299530@o58g2000hsb.googlegroups.com> References: <1168396138.395017.299530@o58g2000hsb.googlegroups.com> Message-ID: <45a53b54$0$4819$88260bb3@free.teranews.com> oyekomova wrote: > I would like to know how to read a CSV file with a header ( n columns > of float data) into an array without the header row. > import csv l = [] for line in csv.reader(open("my.csv").readlines()[1:]): l.append(line) Which really gets you a list of lists. -- Posted via a free Usenet account from http://www.teranews.com From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 22:35:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 14:35:55 +1100 Subject: **argv can't work References: Message-ID: On Sat, 20 Jan 2007 11:20:29 +0800, Jm lists wrote: > hello members, > > See my script piece below: > > def testB(shift,**argv): > print "first argument is %s" %shift > print "all other arguments are:",argv > > testB('mails','Jen','Jen at att.com','Joe','Joe at aol.com') > > It can't work at all.please help tell me the reasons.thanks. Its because of an evil terrorist plot. I suggest you invade Belgium, that should fix it. Or, you could explain what you are trying to do. Posting the exception you get will also help. Hint: **args accumulates KEYWORD arguments. Do you have any keyword arguments in your argument list? How many NON-KEYWORD arguments do you have? How many does your function accept? Here's another hint: some_function("this is a non-keyword argument", \ key="this is a keyword argument") -- Steven. From klaus at seistrup.dk Sun Jan 28 06:37:39 2007 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sun, 28 Jan 2007 11:37:39 +0000 (UTC) Subject: IP address References: Message-ID: Scripter47 wrote: >> python -c 'import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' > > Hmm then you need Internet connecting. That's what IP adresses are for... > can i do it without that? Perhaps you could use the method mentioned in http://mail.python.org/pipermail/python-list/1999-August/009153.html > and it doesn't work either :( Works for me: #v+ klaus at home:~ $ python -c 'import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' 217.157.1.202 klaus at home:~ $ #v- Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ From krypto.wizard at gmail.com Wed Jan 31 22:13:14 2007 From: krypto.wizard at gmail.com (krypto.wizard at gmail.com) Date: 31 Jan 2007 19:13:14 -0800 Subject: division by 7 efficiently ??? In-Reply-To: References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: <1170299594.491478.310430@a34g2000cwb.googlegroups.com> Its not an homework. I appeared for EA sports interview last month. I was asked this question and I got it wrong. I have already fidlled around with the answer but I don't know the correct reasoning behind it. Thanks, On Jan 31, 10:01 pm, Ben Finney wrote: > krypto.wiz... at gmail.com writes: > > How to divide a number by 7 efficiently without using - or / > > operator. We can use the bit operators. I was thinking about bit > > shift operator but I don't know the correct answer. > > I think you are asking for help on a homework assignment in violation > of collusion and plagiarism rules of your educational institution, and > I claim my ten zorkmids. > > Please use the resources made available to you in your course of > study; this almost certainly does not include having people on > discussion forums answer the homework for you. > > -- > \ "I like to go to art museums and name the untitled paintings. | > `\ 'Boy With Pail'. 'Kitten On Fire'." -- Steven Wright | > _o__) | > Ben Finney From James.w.Howard at gmail.com Fri Jan 19 18:48:12 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: 19 Jan 2007 15:48:12 -0800 Subject: Asyncore select statement problem In-Reply-To: References: <1169075120.491855.103200@q2g2000cwa.googlegroups.com> <1169228524.810461.51160@a75g2000cwd.googlegroups.com> Message-ID: <1169250492.375778.296580@11g2000cwr.googlegroups.com> Again, thank you for your help. With digging through the Asyncore.py source, I was able to find the poll2 function which is called when the function asyncore.loop(use_poll = True) is enabled. This function does not use a select call, but a poll call to do its looping. It works well for the problem of threads closing devices at unknown times. The reason for this is that the select statement is called on a series of file descriptors that should not be changed. If the file descriptors become invalid, select throws and exception and the asyncore loop haults. The use_poll flag sets the asyncore module to use a poll instead of a select statement. Within the poll method, there are better ways of dealing with file descriptors and they seem to be able to discern if a file descriptor becomes disconnected with the POLLHUP flag. I am still unsure as to why the select function is used instead of the poll function, but using poll appears to have solved my problem. Thanks for all the help, Jim Howard From beliavsky at aol.com Sun Jan 21 20:36:49 2007 From: beliavsky at aol.com (Beliavsky) Date: 21 Jan 2007 17:36:49 -0800 Subject: Reading Fortran Data In-Reply-To: <1169424273.929396.133880@m58g2000cwm.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> <1169424273.929396.133880@m58g2000cwm.googlegroups.com> Message-ID: <1169429808.910298.10240@11g2000cwr.googlegroups.com> Carl Banks wrote: > > WRITE(90,*) nfault,npoint > > Fortran writes this as two arbitrary integers separated by a space. I wrote a paragraph in my reply explaining why this is wrong. A Fortran list-directed write can print results in an almost arbitrary format, depending on the compiler. Many compilers will separate integers by several spaces, not just one, and they could use commas instead of spaces if they wanted. The number of items printed before a new line is started is also compiler-dependent. For more control, one uses a formatted write, for example write (90,"(2(1x,i0))") nfault,npoint From bthom at cs.hmc.edu Tue Jan 9 00:47:21 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Mon, 08 Jan 2007 21:47:21 -0800 Subject: private variables Message-ID: <74E534EE-D260-409D-8E91-0182BB897B94@cs.hmc.edu> Hello, In what version of python were private variables added? Thanks, --b From cvanarsdall at mvista.com Wed Jan 24 13:43:11 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 24 Jan 2007 10:43:11 -0800 Subject: The reliability of python threads In-Reply-To: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> Message-ID: <45B7A8BF.1090106@mvista.com> Chris Mellon wrote: > On 24 Jan 2007 18:21:38 GMT, Nick Maclaren wrote: > >> [snip] >> >> > > I'm aware of the issues with the POSIX threading model. I still stand > by my statement - bringing up the problems with the provability of > correctness in the POSIX model amounts to FUD in a discussion of > actual problems with actual code. > > Logic and programming errors in user code are far more likely to be > the cause of random errors in a threaded program than theoretical > (I've never come across a case in practice) issues with the POSIX > standard. > Yea, typically I would think that. The problem I am seeing is incredibly intermittent. Like a simple pyro server that gives me a problem maybe every three or four months. Just something funky will happen to the state of the whole thing, some bad data, i'm having an issue tracking it down and some more experienced programmers mentioned that its most likely a race condition. THe thing is, I'm really not doing anything too crazy, so i'm having difficult tracking it down. I had heard in the past that there may be issues with threads, so I thought to investigate this side of things. It still proves difficult, but reassurance of the threading model helps me focus my efforts. > Emphasizing this means that people will tend to ignore bugs as being > "the fault of POSIX" rather than either auditing their code more > carefully, or avoiding threads entirely (the second being what I > suspect your goal is). > > As a last case, I should point out that while the POSIX memory model > can't be proven safe, concrete implementations do not necessarily > suffer from this problem. > Would you consider the Linux implementation of threads to be concrete? -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From "trades\" at (none) Sun Jan 14 14:32:28 2007 From: "trades\" at (none) (none) Date: Sun, 14 Jan 2007 13:32:28 -0600 Subject: help with recursion on GP project Message-ID: <45aa8784$0$5803$4c368faf@roadrunner.com> I'm trying to create a recursive function to evaluate the expressions within a list. The function uses eval() to evaluate the list. Like a lisp interpreter but very limited. What I'm looking for is a function to recursively traverse the list and provide answers in place of lists, so that ... Example = ['add', ['sub', 5, 4], ['mul', 3, 2]] Becomes: Example = ['add', 1, 6] Becomes: Example = 7 *Functions are defined in the script The code I currently have, which isn't pretty (bottom), doesn't work because it doesn't return the value of the evaluated list. But I can't figure out how to do that. Any help would be greatly appreciated. Jack Trades def recursive(tree): if type(tree[1]) != type([]) and type(tree[2]) != type([]): eval(a[0]+'('+str(tree[1])+','+str(tree[2])+')') if type(tree[2]) == type([]): recursive(tree[2]) if type(tree[1]) == type([]): recursive(tree[1]) From piet at cs.uu.nl Sat Jan 6 10:37:53 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 06 Jan 2007 16:37:53 +0100 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: >>>>> Lawrence D'Oliveiro (LD) wrote: >LD> No it wouldn't. This security hole was fixed years ago. How? -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From gandalf at designaproduct.biz Mon Jan 8 04:36:29 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 08 Jan 2007 10:36:29 +0100 Subject: Parallel Python In-Reply-To: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: <45A2109D.5050501@designaproduct.biz> parallelpython at gmail.com wrote: > Has anybody tried to run parallel python applications? > It appears that if your application is computation-bound using 'thread' > or 'threading' modules will not get you any speedup. That is because > python interpreter uses GIL(Global Interpreter Lock) for internal > bookkeeping. The later allows only one python byte-code instruction to > be executed at a time even if you have a multiprocessor computer. > To overcome this limitation, I've created ppsmp module: > http://www.parallelpython.com > It provides an easy way to run parallel python applications on smp > computers. > I would appreciate any comments/suggestions regarding it. > I always thought that if you use multiple processes (e.g. os.fork) then Python can take advantage of multiple processors. I think the GIL locks one processor only. The problem is that one interpreted can be run on one processor only. Am I not right? Is your ppm module runs the same interpreter on multiple processors? That would be very interesting, and something new. Or does it start multiple interpreters? Another way to do this is to start multiple processes and let them communicate through IPC or a local network. Laszlo From rvernica at gmail.com Fri Jan 26 14:54:53 2007 From: rvernica at gmail.com (Rares Vernica) Date: Fri, 26 Jan 2007 11:54:53 -0800 Subject: Unicode error handler Message-ID: Hi, Does anyone know of any Unicode encode/decode error handler that does a better replace job than the default replace error handler? For example I have an iso-8859-1 string that has an 'e' with an accent (you know, the French 'e's). When I use s.encode('ascii', 'replace') the 'e' will be replaced with '?'. I would prefer to be replaced with an 'e' even if I know it is not 100% correct. If only this letter would be the problem I would do it manually, but there is an entire set of letters that need to be replaced with their closest ascii letter. Is there an encode/decode error handler that can replace all the not-ascii letters from iso-8859-1 with their closest ascii letter? Thanks a lot, Ray From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 17:23:40 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 23:23:40 +0100 Subject: Execute binary code References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> Message-ID: <50fujcF1g1nplU2@mid.individual.net> Larry Bates wrote: > What you are asking is a virus/trojan "like" program. Why? For being a trojan horse it must fake something. For being a virus it must replicate itself. Writing an executable doesn't imply the will to replicate itself. But you could technically achieve this with standard python too (just write python source and spawn a python process executing it). Regards, Bj?rn -- BOFH excuse #28: CPU radiator broken From vsalesa at gmail.com Wed Jan 10 05:40:45 2007 From: vsalesa at gmail.com (odlfox) Date: 10 Jan 2007 02:40:45 -0800 Subject: add re module to a embeded device phyton interpreter Message-ID: <1168425645.340291.42720@p59g2000hsd.googlegroups.com> I hav to add the re (regular expressions) functionality to an Embeded device that I'm using. I read the re.py file and it says I need several dependencies, one of them is the pcre module but I found no pcre.py or pcre.pyc file. Someone knows where to find something to solve my problem. Thanks a lot From hg at nospam.org Mon Jan 15 05:23:16 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 11:23:16 +0100 Subject: catching signals in an object Message-ID: <7MOqh.18678$sE7.16830@newsfe21.lga> Hi, I need to catch a signal "SIGUSR1" in an object ... and I need the signal def that traps is to access the object context ... is that possible ? (*nix and windows) ex: class test: def __init__(self): self.Set_Signal() def Set_Signal(self): import signal signal.signal(..., Func) def Func(.....): #I need to get access to self or can signal.signal take a method as param ? Thanks hg From mail at microcorp.co.za Fri Jan 12 00:16:25 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Jan 2007 07:16:25 +0200 Subject: maximum number of threads References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> <200701100743.45547.kosh@aesaeion.com> Message-ID: <007201c73608$cf18dd60$03000080@hendrik> "William Heymann" wrote: > So you know I tried this on ubuntu edgy 64bit edition on a dual 2218 opteron > system with 8G of ram and I got > > > Exception raised: can't start new thread > Biggest number of threads: 32274 > This almost looks as if the number of threads is a sixteen bit signed int... - Hendrik From emin.shopper at gmail.com Fri Jan 5 09:01:56 2007 From: emin.shopper at gmail.com (Emin) Date: 5 Jan 2007 06:01:56 -0800 Subject: bug in copy.deepcopy or in getattr or in my understanding? In-Reply-To: References: <1167942359.246311.80700@s34g2000cwa.googlegroups.com> Message-ID: <1168005716.195293.121490@38g2000cwa.googlegroups.com> Dear Gabriel, Thank you for your reply. As you guessed, I want to be able to select the method at runtime as in your final example, but when I tried your suggestion I got the same error (see below). I think the problem is that getattr is donig something different than in my example where I explicitly get it from the dict (see the very end of the transcript below): --------------------------- Transcript Follows ---------------------------------------------------------- Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> # The following shows that using getattr to grab a method is >>> # incompatible with copy.deepcopy >>> class a: ... def foo(self): pass ... >>> class b(a): ... def __init__(self): ... self.x = getattr(a,'foo') ... >>> import copy >>> c=b() >>> copy.deepcopy(c) Traceback (most recent call last): File "", line 1, in File "c:\Python25\lib\copy.py", line 162, in deepcopy y = copier(x, memo) File "c:\Python25\lib\copy.py", line 291, in _deepcopy_inst state = deepcopy(state, memo) File "c:\Python25\lib\copy.py", line 162, in deepcopy y = copier(x, memo) File "c:\Python25\lib\copy.py", line 254, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "c:\Python25\lib\copy.py", line 189, in deepcopy y = _reconstruct(x, rv, 1, memo) File "c:\Python25\lib\copy.py", line 322, in _reconstruct y = callable(*args) File "c:\Python25\lib\copy_reg.py", line 92, in __newobj__ return cls.__new__(cls, *args) TypeError: instancemethod expected at least 2 arguments, got 0 >>> >>> # The following shows that getattr is doing something different >>> # than looking in the __dict__ of base classes >>> b.__bases__[0].__dict__['foo'] >>> getattr(a,'foo') >>> On Jan 4, 10:08 pm, Gabriel Genellina wrote: > At Thursday 4/1/2007 17:26, Emin wrote: > > >I got some unexpected behavior in getattr and copy.deepcopy (see > >transcript below). I'm not sure if this is actually a bug in > >copy.deepcopy or if I'm doing something too magical with getattr. > >Comments would be appreciated.Both examples are different. #1 stores a *bound* method into an > instance attribute. Bound methods carry a reference to "self", this > creates a cyclic reference that may cause problems to the garbage > collector (and confuses deepcopy, apparently). > #2 uses and *unbound* method and it's the usual way. > > > >>> class a: > >... def foo(self): > >... print 'hi' > >... > > >>> class b(a): #1 > >... def __init__(self): > >... self.y = getattr(self,'foo') > > > >>> class b(a): #2 > >... def __init__(self): > >... self.x = self.__class__.__bases__[0].__dict__['foo']For #2 you can simply say: > > class b(a): > x = a.foo > > If you have to choose at runtime (a simplified version of your own code): > > class b(a): > def __init__(self): > name = select_method_to_use(..., default="foo") > self.x = getattr(a, name) > > You *know* your bases because you wrote them in the class statement > (or use super() instead of playing with __bases__); and getattr works > fine here so you don't need to mess with the __dict__ details. > > (Note that #1 was *almost* right, you had to replace self by the base class) > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya!http://www.yahoo.com.ar/respuestas From simon at brunningonline.net Fri Jan 12 14:34:36 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 12 Jan 2007 19:34:36 +0000 Subject: Rational Numbers In-Reply-To: References: Message-ID: <8c7f10c60701121134q35bf7c27h7c4b5cf1dcfe44ca@mail.gmail.com> On 12 Jan 2007 15:55:39 GMT, Nick Maclaren wrote: > > In article , > Carsten Haese writes: > |> but there are more use > |> cases for Decimal than for Rational. > > That is dubious, but let's not start that one again. Decimals are good for holding financial values. There's a whole lot of software out there that deals with money. -- Cheers, Simon B simon at brunningonline.net From GatlingGun at gmail.com Wed Jan 31 10:32:27 2007 From: GatlingGun at gmail.com (TOXiC) Date: 31 Jan 2007 07:32:27 -0800 Subject: Regex with ASCII and non-ASCII chars In-Reply-To: References: <1170243969.504255.134100@v33g2000cwv.googlegroups.com> Message-ID: <1170257547.041535.20770@a75g2000cwd.googlegroups.com> Thx it work perfectly. If I want to query a file stream? file = open(fileName, "r") text = file.read() file.close() regex = re.compile(u"(???????)", re.IGNORECASE) match = regex.search(text) if (match): result = match.group() print result WritePatch(fileName,text,result) else: result = "No match found" print result It return "no match found" (the file contain the string "???????" but...). Thanks in advance for the help! From no-spam at no-spam-no-spam.invalid Sun Jan 7 07:41:35 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Sun, 07 Jan 2007 13:41:35 +0100 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: time.swift at gmail.com wrote: > Coming from a C++ / C# background, the lack of emphasis on private data > seems weird to me. I've often found wrapping private data useful to > prevent bugs and enforce error checking.. What is the use of private declarations, if the names themselves are not verbose about it? => You'll always search the class definition/doc to check if the member is below "private" or you wait for compiler errors. If you still want to override, you have to declare 'friends' and all that school boy stuff. => Its not useful and efficient for programmers but probably more fulfilled teachers lust itching disciples, when those languages where invented. Moreover, in those languages there is more or less a clash of namespaces: All globals, module globals, members, local variables and possibly 'with'-variables. This confusion mixed with private declarations will soon provide a situation where one looses overview, what variable exactly was meant. The syntax in Python with _'s and 'self.' and true modularization and minimal magic namespace behavior, but with explicit self-similiar access to objects, modules, functions and everything is overall most clear und effective. After all I don't know another language which behaves so well in this regard. Even Ruby (little positive: it has not even the 'global' variable declaration) is much more ill below the line in that modules,classes, methods/functions.. are not objects but namespaces, messages etc. - thus self-similarity is so broken, that this which will actually limit the power and scalability of this language. Robert > It appears to me (perhaps wrongly) that Python prefers to leave class > data public. What is the logic behind that choice? > > Thanks any insight. From fredrik at pythonware.com Wed Jan 3 10:20:03 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 Jan 2007 16:20:03 +0100 Subject: Unsubscribing from the list References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> Message-ID: Dotan Cohen wrote: > > Go to the bottom of the page. Next to the button "Unsubscribe or edit options", > > enter your email address. Click the button. On the next page, click > > "Unsubscribe". Follow the instructions in the email that is sent to you. > Thanks. I read that page, got as far as this: > > (The subscribers list is only available to the list administrator.) > > and decided that there was no futher interest on the page for me. if you're unable to follow written instructions, how on earth did you manage to subscribe to this list ? From hg at nospam.org Tue Jan 16 09:22:37 2007 From: hg at nospam.org (hg) Date: Tue, 16 Jan 2007 15:22:37 +0100 Subject: Queue and signals Message-ID: Hi, Is it legal to use Queue.put in a signal handle and Queue.get in the main process (no thread) Thanks, hg From bdesth.quelquechose at free.quelquepart.fr Tue Jan 2 10:32:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Jan 2007 16:32:12 +0100 Subject: OO question In-Reply-To: <1167700159.792649.61210@a3g2000cwd.googlegroups.com> References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> <1167639280.181587.242490@s34g2000cwa.googlegroups.com> <1167700159.792649.61210@a3g2000cwd.googlegroups.com> Message-ID: <459a74e2$0$315$426a74cc@news.free.fr> fejkadress at hushmail.com a ?crit : > First I want to say thanks everyone for helping me! > > John Machin wrote: > > >>fejkadress at hushmail.com wrote: >> >>>I want to make an addressbook and I'm new to OO programming, so I >>>wonder if this sounds reasonable. >>> >>>I think of making a class Address which contains all data about one >>>person, that class can have UserDict as baseclass so I can access data >>>like object['name'], etc.. >> >>Stop right there. Class Address contains all data about one *person*? >>Please consider renaming that class Person, and having a separate class >>Address. >> >>Interruption for a reality check: A person may be related to zero, one >>or many addresses. An address may be related to zero, one or many >>persons. The relationship may take many forms e.g. "lives at", "once >>lived at", "has been noticed loitering outside", ... > > > Lets say I have those two classes, Person and Address. How would one > implement the relationship between them? First, a Person can have one > or more addresses (or none), that could be represented as a list of > Addresses, right? But then, if I have an Address I want to see which > persons who live there, then I would have a list of Persons in each > Address. > > Is this doubly-linked way of doing it a good way of doing it, or is > there a better "OO way" I haven't learned yet? > The most common solution so far for this kind of problems is to forget about "domain model" OO modeling and switch to relational modeling (usually using an SQL dbms). Else you end up rewriting an half-backed buggy ad-hoc relational system... FWIW, using OO does not imply using an OO domain model. You can restrict OO features to "technical" objects... Now the good news is that there are Python packages like SQLAlchemy that gives you kind of "best of both world" solutions (OO domain model + relational support). My 2 cents... From vithi99 at hotmail.com Mon Jan 15 00:11:35 2007 From: vithi99 at hotmail.com (vithi) Date: 14 Jan 2007 21:11:35 -0800 Subject: How to write code to get focuse the application which is open from server In-Reply-To: <45a0dae2$0$8948$4c368faf@roadrunner.com> References: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> <45a0dae2$0$8948$4c368faf@roadrunner.com> Message-ID: <1168837895.073936.270330@11g2000cwr.googlegroups.com> Hi Paul, Since your reply I try to use pywinauto. I was able to get the control of a window that is a good news but it is not working for sub window this main window create.(popup windows) eg) File -> print will open print window but the code is not clicking print button. I try several combination app,Print.OK.CloseClick() or app,Print.OK.Click() is not working my code goes like that app=application.Application() qi = app.window_(title_re = ".*arcMap.*") qi.TypeKeys("%FP") app,Print.OK.Click() the last line of code is not working same thing with file open to qi.TypeKeys("%FO") create popup window "open" but app,Open.Filename.SetEditText("test1,txt") is not working any help to overcome to this problem (Here the "Print" , "Open" are windows title I am using without any undestanding why I am using. Any help? Paul McGuire wrote: > "vinthan" wrote in message > news:1168143871.536432.252010 at v33g2000cwv.googlegroups.com... > > hi, > > I am new to python. I have to write test cases in python. An > > application is open in the desk top ( application writen in .Net) I > > have to write code to get focuse the application and click on the link > > which in the one side and it will load the map on the other and I have > > to check map is loaded. Any one tell me how do I use Dispatch or any > > other method to write a code. > > > If you are running on Windows, look into pywinauto > (http://www.openqa.org/pywinauto/). > > I have successfully used it to interact with a Flash animation running > within an IE browser. > > I also had to inspect the graphics displayed by the Flash animation, for > this I used PIL (http://www.pythonware.com/products/pil/). > > Good luck, > -- Paul From felipe.lessa at gmail.com Thu Jan 4 10:40:21 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Thu, 4 Jan 2007 13:40:21 -0200 Subject: Packaging up a Python/Twisted Matrix application... In-Reply-To: References: Message-ID: On 1/4/07, Chaz Ginger wrote: > I have a rather large Python/Twisted Matrix application that will be run > on Windows, Linux and perhaps Macs. I was wondering if there are any > tools that can be used to create an installer that will bring in Python, > Twisted Matrix, my application libraries and anything else I need? I haven't tried with Twisted, but I had success in using py2exe + Inno Setup on a program dependent on Python + ReportLab + pygtk. As both ReportLab and pygtk got even C extensions, I don't see why this setup wouldn't work with Twisted. -- Felipe. From frank at chagford.com Mon Jan 8 03:11:15 2007 From: frank at chagford.com (Frank Millman) Date: 8 Jan 2007 00:11:15 -0800 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <45A1F1D9.8070206@v.loewis.de> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <45A1F1D9.8070206@v.loewis.de> Message-ID: <1168243875.143604.269720@q40g2000cwq.googlegroups.com> Martin v. L?wis wrote: > vizcayno schrieb: > > Need your help in the "correct" definition of the next function. If > > necessary, I would like to know about a web site or documentation that > > tells me about best practices in defining functions, especially for > > those that consider the error exceptions management. > > I agree with George Sakkis' remarks. The best way to define this function is > > def ExecuteSQL(cmdSQL, cursor): > return cursor.execute(cmdSQL) > > If this raises an exception, it likely means there is something > wrong with the SQL statement. The program should abort, and the > developer should correct it. > > Regards, > Martin With respect, I can offer a counter-argument. I have a multi-user server program, with a connection to a database, servicing multiple requests from connected clients. The clients are 'thin' - the business logic resides on the server - so when a client selects an option, the server imports the appropriate module and executes it. If that includes a SQL command, the server connects to the database, executes the command, and returns the result to the client. If there is something wrong with the SQL statement, I do not want to crash the server, I want to notify the client that there was something wrong, so that the offending module can be corrected and reloaded. Frank Millman From steve at holdenweb.com Thu Jan 11 16:29:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Jan 2007 21:29:05 +0000 Subject: Portable Python - free portable development environment ! In-Reply-To: <1168533423.224355.221390@k58g2000hse.googlegroups.com> References: <1168533423.224355.221390@k58g2000hse.googlegroups.com> Message-ID: perica.zivkovic at gmail.com wrote: > Hi there, > > I would like to announce the *first* beta release of the Portable > Python 1.0 beta. From today Portable Python website is also online and > you can find it on the location www.PortablePython.com. > > About: > Portable Python is a Python programming language preconfigured to run > directly from a portable device (USB stick, iPod etc.), enabling you to > have, at any time, portable programming environment. Just download and > extract to your portable device and in 10 minutes you are ready to > create your next Python application. No registry modifications, > installations, totally portable. > > Where to find it: > http://www.portablepython.com > > regards, > > Perica Zivkovic > > P.S. did I mentioned that it is free? :-) > And what, besides is freeness, differentiates it from Movable Python? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From mail at microcorp.co.za Fri Jan 19 09:09:41 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 19 Jan 2007 16:09:41 +0200 Subject: How can I create a linked list in Python? References: <1168983652.192715.235580@a75g2000cwd.googlegroups.com> Message-ID: <010201c73bd4$75ac9a60$03000080@hendrik> "Jorgen Grahn" wrote: > > FWIW, I oppose the idea (paraphrased from further up the thread) that linked > lists and other data structures are obsolete and dying concepts, obsoleted > by Python and other modern languages. > > 99% of the time. a Python list is the right tool for the job, but that's > only because we have CPU cycles to spare and the 'n' in our 'O(n)' is > limited. You cannot call yourself a computer scientist without understanding > things like linked lists. No other data structure has the same > characteristics (good and bad) as that one. Or those two, really. +1 The concept of storing a pointer that points to the "next thing" is so basic that it will never go away. One meets it all time in chained buffer blocks, in tag sorts, etc... And if you add a pointer to the "previous thing" too, then adding or taking something out of what could become a ring is a constant effort. Until you run out of memory. Ye Olde Universal Controlle Blocke: - pointer to the start of data block - length of allocated data block - pointer to next control block - pointer to previous control block - next in pointer into data block - next out pointer into data block - optional length of data - optional here starts or ends the lesson indicator errrm... thats about it, unless you want a fast index too: - pointer to first control block - pointer to second control block - pointer to third control block ... Isn't it nice of python to hide all this stuff? - Hendrik From tpawley at gmail.com Sat Jan 13 06:17:15 2007 From: tpawley at gmail.com (Torabisu) Date: 13 Jan 2007 03:17:15 -0800 Subject: General Question About Python In-Reply-To: References: <1168254451.098796.144790@42g2000cwt.googlegroups.com> <1168586849.047301.301680@s34g2000cwa.googlegroups.com> Message-ID: <1168687033.258472.16090@v45g2000cwv.googlegroups.com> Hendrik van Rooyen wrote: > "Torabisu" wrote: > > > > > > billie wrote: > > > Torabisu wrote: > > > > > > > Its quite weird, we're looking for Python skills but are battling to > > > > find at the moment... Normally Python on its own will probably not > > > > land you a job, but the last two companies I've worked for are doing > > > > indepth Python development, so hopefully the tables are turning a bit. > > > > > > I can tell the same for Italy. > > > Where are you from? > > > > Cape Town, South Africa. There is a strong Unix following here, but > > more on the System Administration side, not really the software > > development side with regards to Python. Python more being used for > > task automation and shell scripting. > > What do you want done? - I am only a thousand miles away... > > - Hendrik If I can just get my Python teleporter sorted out, distance will be no problem... A little buggy at the moment though... Poor John, I told him not to test it but oh well. From could.net at gmail.com Wed Jan 31 11:23:57 2007 From: could.net at gmail.com (Frank Potter) Date: 31 Jan 2007 08:23:57 -0800 Subject: Any python scripts to do parallel downloading? Message-ID: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> I want to find a multithreaded downloading lib in python, can someone recommend one for me, please? Thanks~ From bdesth.quelquechose at free.quelquepart.fr Wed Jan 17 16:05:02 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 Jan 2007 22:05:02 +0100 Subject: How can I create a linked list in Python? In-Reply-To: <1169009882.408482.43360@q2g2000cwa.googlegroups.com> References: <45ad5104$0$393$426a74cc@news.free.fr> <1169009882.408482.43360@q2g2000cwa.googlegroups.com> Message-ID: <45ae8950$0$31033$426a74cc@news.free.fr> sturlamolden a ?crit : > Bruno Desthuilliers wrote: > > >>Implementing linked lists in Python is not a great deal - it just >>doesn't make much sens. > > > It does make sence, Oh Yec ?-) sorry... > as there are memory constraints related to it. > Python lists are arrays under the hood. This is deliberately. Dynamic > arrays grows faster than lists for the common "short list" case, and > because indexing an array is O(1) instead of O(N) as it is for linked > lists. You can easily break the performance of Python lists by adding > objects in the middle of a list or appending objects to the end of long > lists. At some point the list can not grow larger by a simple realloc, > as it would crash with other objects on the heap, and the whole list > must be replaced by a brand new memory segment. That's certainly true - from a technical POV -, but I never had such a problem in now 7 years of Python programming. > Also linked lists are an interesting theoretical concept in computer > science. Understanding how dynamic datastructures work and their > limitations are a key to understanding algorithms and how computers > work in general. Indeed. Did I say otherwise ? > The simplest way of implementing a linked list in Python is nesting > Python lists. Have you considered using tuples ? If you go the FP way, why not use an immutable type ? (snip) > Those who know Lisp should be familiar with the concept of creating > dynamic data structures form nesting lists; it may be more unfamiliar > to C and Pascal programmers, as these languages do not support such > constructs. But how are Lisp lists implemented then ?-) I do totally agree that Lispish lists are something one should learn, but starting with a low-level procedural language with 'manual' memory management is certainly a Good Thing(tm). Well, IMHO at least (FWIW, having first learned to implement linked lists in C and Pascal, I had no problem understanding Lisp's list). > In Python one may also use a more explicit solution > involving classes for expressing linked lists, which would be more > familiar to C and Pascal programmers. In any case, making linked lists > are trivial in Python. > Yes again. Hence my remark... From apardon at forel.vub.ac.be Mon Jan 15 04:55:59 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 15 Jan 2007 09:55:59 GMT Subject: Boilerplate in rich comparison methods References: Message-ID: On 2007-01-13, Steven D'Aprano wrote: > I'm writing a class that implements rich comparisons, and I find myself > writing a lot of very similar code. If the calculation is short and > simple, I do something like this: > > > class Parrot: > def __eq__(self, other): > return self.plumage() == other.plumage() > def __ne__(self, other): > return self.plumage() != other.plumage() > def __lt__(self, other): > return self.plumage() < other.plumage() > def __gt__(self, other): > return self.plumage() > other.plumage() > def __le__(self, other): > return self.plumage() <= other.plumage() > def __ge__(self, other): > return self.plumage() >= other.plumage() Well one thing you could do is write the following class: Comparators = SomeEnumWith("eq, ne, lt, gt, ge, le, ge") class GeneralComparator: def __eq__(self, other): return Comparators.eq in self.__compare__(self, other) def __ne__(self, other): return Comparators.ne in self.__compare__(self, other) def __lt__(self, other): return Comparators.lt in self.__compare__(self, other) def __le__(self, other): return Comparators.le in self.__compare__(self, other) def __gt__(self, other): return Comparators.gt in self.__compare__(self, other) def __ge__(self, other): return Comparators.ge in self.__compare__(self, other) Then write your Parrot class as follows: class Parrot (GeneralComparator): def __compare__(self, other): return a set which defines which comparisons should return true. -- Antoon Pardon From wehbrink at web.de Sat Jan 20 04:46:46 2007 From: wehbrink at web.de (Mario Wehbrink) Date: Sat, 20 Jan 2007 10:46:46 +0100 Subject: Code reformater? References: Message-ID: <615984-ot3.ln1@pluto.fqdn.th-h.de> Vincent Delporte schrieb in comp.lang.python: Hi > When I copy/paste Python code from the web, every so often, > the TABs are wrong, which means that the code won't work and I have to > manually reformat the code. > > Is there a code reformater that can parse the code to make it right? It may help to look at the settings of your editor. I think Vim (and surely emacs) can help you with that. (look at :help retab, paste, expandtab in (g)Vim) Mario -- Mario Wehbrink From casevh at comcast.net Thu Jan 4 03:03:40 2007 From: casevh at comcast.net (casevh at comcast.net) Date: 4 Jan 2007 00:03:40 -0800 Subject: code optimization (calc PI) / Full Code of PI calc in Python and C. In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> <1167872076.937415.250340@11g2000cwr.googlegroups.com> Message-ID: <1167897820.603957.239850@51g2000cwl.googlegroups.com> > Here is my attempt to convert the C code, not written with speed in mind > and I was too lazy too time it. :-) > > from itertools import izip > > def pi(): > result = list() > d = 0 > e = 0 > f = [2000] * 2801 > for c in xrange(2800, 0, -14): > for b, g in izip(xrange(c, 1, -1), xrange((c * 2) - 1, 0, -2)): > d += f[b] * 10000 > h, f[b] = divmod(d, g) > d = h * b > h, i = divmod(d, 10000) > result.append('%.4d' % (e + h)) > e = i > return ''.join(result) > Your version: .36 seconds It's ugly, but unrolling the divmod into two separate statements is faster for small operands. The following takes .28 seconds: from time import clock from itertools import izip def pi(): result = list() d = 0 e = 0 f = [2000] * 2801 for c in xrange(2800, 0, -14): for b, g in izip(xrange(c, 1, -1), xrange((c * 2) - 1, 0, -2)): d += f[b] * 10000 f[b] = d % g h = d // g d = h * b h, i = divmod(d, 10000) result.append('%.4d' % (e + h)) e = i return ''.join(result) start_time = clock() pi = pi() print pi print "Total time elapsed:", round(clock() - start_time, 2), "s" print len(pi) casevh From spammers-die at spam.microsoft.com Wed Jan 31 07:07:49 2007 From: spammers-die at spam.microsoft.com (John McCallum) Date: Wed, 31 Jan 2007 12:07:49 +0000 Subject: BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job References: <1170200864.492655.11850@s48g2000cws.googlegroups.com> <45bff548$0$97249$892e7fe2@authen.yellow.readfreenews.net> Message-ID: On Tue, 30 Jan 2007 19:48:45 -0600, soutjhyDin wrote: > wrote in message > news:1170200864.492655.11850 at s48g2000cws.googlegroups.com... >> http://portland.indymedia.org/en/2006/06/341238.shtml >> >> BYU Physics Prof Finds Thermate in WTC Physical Samples, Building >> Collapses an Inside Job > > [...] > > The Iron Oxide(s), dummy. This is way off topic in most of the groups it has been posted to. Please restrict replies to the only one that seems remotely relevant: soc.culture.usa We can just plonk the original author, and I'm sure most have, but when others reply we need to plonk them too. It's just more effort. ;) Cheers, John McCallum Edinburgh From ptmcg at austin.rr.com Wed Jan 24 13:49:00 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Jan 2007 10:49:00 -0800 Subject: Simple Matrix class In-Reply-To: References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> Message-ID: <1169664540.120687.211350@s48g2000cws.googlegroups.com> On Jan 24, 11:21 am, Gabriel Genellina wrote: > At Wednesday 24/1/2007 02:40, Paul McGuire wrote: > > > > The points should be aligned on a log-log plot to be a power function. > > > As Robert Kern stated before, this problem should be not worse than > > > O(n**3) - how have you implemented it? > > >Sure enough, the complete equation is t = 5e-05exp(1.1n), or t = 5e-05 > >X 3**n. > > So either reimplement it better, or place a notice in BIG letters to > your users about the terrible time and memory penalties of using inverse() > Well, really, the "terrible time and memory penalties" aren't all that terrible for matrices up to, oh, 10x10 or so, but you wouldn't want to use this on anything much larger than that. Hey, guess what?! That's exactly what I said in my original post! And the purpose/motivation for "reimplementing it better" would be what, exactly? So I can charge double for it? As it was, I felt a little guilty for posting a solution to such a likely homework assignment, but now there's room for a student to implement a kickass inverter routine in place of the crappy-but-useful-for-small-matrices brute force one I've written. Cubs win! -- Paul From redefined.horizons at gmail.com Mon Jan 22 14:07:49 2007 From: redefined.horizons at gmail.com (Scott Huey) Date: 22 Jan 2007 11:07:49 -0800 Subject: Best way to document Python code... Message-ID: <1169492869.101706.253620@38g2000cwa.googlegroups.com> I am working on a Python module and I would like to prepare some API documentaiton. I managed to find epydoc after some searching online. Is there a standard way to document the API for Python modules? Is epydoc the best way to go if there is no standard? Are there other ways to document a Python API? Thanks, Scott Huey From bdesth.quelquechose at free.quelquepart.fr Mon Jan 22 15:06:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Jan 2007 21:06:29 +0100 Subject: instancemethod In-Reply-To: References: Message-ID: <45b51298$0$8289$426a74cc@news.free.fr> Gert Cuykens a ?crit : > import MySQLdb > > class Db: (snip) > def excecute(self,cmd): > self._cursor.execute(cmd) > self._db.commit() > What about autocommit and automagic delegation ? import MySQLdb class Db(object): def __init__(self,server, user, password, database): self._db = MySQLdb.connect(server , user , password , database) self._db.autocommit(True) self._cursor = self._db.cursor() def close(self): self._cursor.close() self._db.close() def __del__(self): try: self.close() except: pass def __getattr__(self, name): attr = getattr( self._cursor, name, getattr(self._db, name, None) ) if attr is None: raise AttributeError( "object %s has no attribute %s" \ % (self.__class__.__name__, name) ) return attr (NB :not tested...) From bearophileHUGS at lycos.com Fri Jan 26 22:04:08 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Jan 2007 19:04:08 -0800 Subject: dict.keys() ? Message-ID: <1169867048.004256.279240@v33g2000cwv.googlegroups.com> The PEP 3100: http://www.python.org/dev/peps/pep-3100/ says: Return iterators instead of lists where appropriate for atomic type methods (e.g. dict.keys(), dict.values(), dict.items(), etc.); iter* methods will be removed. Better: make keys(), etc. return views ala Java collections??? ... To be removed: dict.setdefault()? [15] dict.has_key() method [done] I may be sleepy now, but maybe the keys() method too can be removed; otherwise the following two become really the same: print list(adict) for k in adict: ... print list(adict.keys()) for k in adict.keys(): ... Bye, bearophile From http Mon Jan 8 07:33:46 2007 From: http (Paul Rubin) Date: 08 Jan 2007 04:33:46 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> <7xlkke19he.fsf@ruckus.brouhaha.com> <7xirfiyn3y.fsf@ruckus.brouhaha.com> Message-ID: <7xodp9puj9.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > I have no idea how often if ever. > > You've established that there's a name conflict when you do so, which > leads to bugs. So how often do you get bitten by that particular type of bug? I don't know. Likely zero, possibly not. I'm sure I've written many bugs that have never been detected by me or anyone else. I've probably written bugs that crashed an application for some user but they just cursed me out and never bothered to tell me about the crash. Maybe I've even written bugs that leaked a user's private data without the user noticing, but discovered by some attacker intercepting the data who is cackling about the bug while keeping it secret. There's no way for me to think I'll ever find out. I'd much prefer to be able to say of any type of bug, "the number is exactly zero as a known fact, because it's inherent in Python's design that it's impossible to have that type of bug". Language designs should aim to let programmers say things like that as often as possible. > class MySubClass(SomeSuperclass): ... > raise ValueError("Name conflict with private attribute!") > Problem solved. No good, Python allows creating classes and attributes on the fly. The superclass could create its private variable after the subclass is created. > The truth of the matter is, MyClass.__private is not private at all. It is > still a public attribute with a slightly unexpected name. In other words, > if you want to code defensively, you should simply assume that Python has > no private attributes, and code accordingly. > > Problem solved. Well, "problem moved", not "problem solved". Now you have the problem of having to know the names of every attribute any related class might use when you write your own class. That is why other languages have private variables and Python has name mangling--to solve a real problem. Except Python's solution is a leaky kludge. From martin.witte at gmail.com Mon Jan 29 14:48:05 2007 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 29 Jan 2007 11:48:05 -0800 Subject: Conversion of string to integer In-Reply-To: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> References: <1170078933.180025.229830@k78g2000cwa.googlegroups.com> Message-ID: <1170100085.505577.211470@v33g2000cwv.googlegroups.com> On Jan 29, 2:55 pm, "jupiter" wrote: > Hi guys, > > I have a problem. I have a list which contains strings and numeric. > What I want is to compare them in loop, ignore string and create > another list of numeric values. > > I tried int() and decimal() but without success. > > eq of problem is > > #hs=string.split(hs) > hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"] > > j=0 > for o in range(len(hs)): > print hs[o],o > p=Decimal(hs[o]) > if p > 200: j+=j > print "-"*5,j > print "*"*25 > > I could be the best way to solve this ......? > > @nil function isinstance can help you to determine the type/class of an object: py>hs =["popopopopop","254.25","pojdjdkjdhhjdccc","25452.25"] py> py>for i in hs: py> if isinstance(i, str): py> print str(i) py> elif isinstance(i, float): py> print float(i) py> elif isinstance(i, int): py> print int(i) py> else: py> print 'dunno type of this element: %s' % str(i) popopopopop 254.25 pojdjdkjdhhjdccc 25452.25 From rridge at csclub.uwaterloo.ca Thu Jan 18 20:57:00 2007 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 18 Jan 2007 17:57:00 -0800 Subject: Determining when a file is an Open Office Document References: Message-ID: <1169171820.851021.49200@l53g2000cwa.googlegroups.com> tubby wrote: > Silly question, but here goes... what's a good way to determine when a > file is an Open Office document? I could look at the file extension, but > it seems there would be a better way. VI shows this info in the files: > > mimetypeapplication/vnd.oasis.opendocument.textPK It's a ZIP archive. The info you've found are the file name "mimetype", the uncompressed contents of that file "application/vnd.oasis.opendocument.text", and part of the ZIP magic number "PK". You should be able to use the "zipfile" module to check to see if the file a ZIP file, if it has a member named "mimetype" and if the contents of the file match one of the OpenOffice MIME types. Ross Ridge From nospam at nospam.invalid Wed Jan 3 18:30:45 2007 From: nospam at nospam.invalid (Russell Owen) Date: Wed, 03 Jan 2007 15:30:45 -0800 Subject: static object References: <459c306c$0$314$426a74cc@news.free.fr> Message-ID: In article <459c306c$0$314$426a74cc at news.free.fr>, meelab wrote: > Dear All, > > I am looking for a way to create a "static object" or a "static class" - > terms might be inappropriate - having for instance: > > class StaticClass: > . > . > > and then > staticObject1 = StaticClass() > staticObject2 = StaticClass() > > so that staticObject1 and staticObject2 refers exactly to the same > instance of object. Personally I do the following (in its own module). There may be a better way, but this is simple and it works: _theSingleton = None def getSingleton(): global _theSingleton if not _theSingleton: _theSingleton = _Singleton() return _theSingleton class _Singleton: def __init__(self, ...): ... -- Russell From hg at nospam.org Fri Jan 5 04:45:57 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 10:45:57 +0100 Subject: importing / loading a module / class dynamically References: Message-ID: <1hvnh.22241$Dy2.9812@newsfe20.lga> hg wrote: > Hi, > > I have the following problem. > > I find in a directory hierarchy some files following a certain sets of > rules: > > .../.../../plugin/name1/name1.py > .... > .../.../../plugin/namen/namen.py > > each file will in turn have a class with the same name as the filename > (minus .py) > > > I fetch those names in a list of string and want to import the files / > instantiate the classes. > > > I block at the beginning and tried this (test.py is a real file) >>>> s = 'test.py' >>>> eval ('import ' + s) > > and get > > Traceback (most recent call last): > File "", line 1, in -toplevel- > eval ('import ' + s) > File "", line 1 > import test.py > > Any clue ? > > Thanks > > hg OK, from http://mail.python.org/pipermail/python-list/2004-July/272081.html, I need to use exec and not eval hg From boyee118 at gmail.com Tue Jan 9 05:48:41 2007 From: boyee118 at gmail.com (boyeestudio) Date: Tue, 9 Jan 2007 18:48:41 +0800 Subject: I compile the Pychm in windows,But meet a lot of errors...... Message-ID: The Error is show as below: D:\Downloads\pychm-0.8.4>python setup.py build running build running build_py running build_ext building 'chm._chmlib' extension D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:D:\Python24\libs /LIBPATH:D:\Python24\PCBuild chm.lib /EXPORT:init_chmlib build\temp.win32-2.4\Release\chm/swig_chm.obj/OUT:build\lib .win32-2.4\chm\_chmlib.pyd /IMPLIB:build\temp.win32- 2.4\Release\chm\_chmlib.lib LIBC.lib(crt0init.obj) : error LNK2005: ___xc_z ??? MSVCRT.lib(cinitexe.obj) ??? LIBC.lib(crt0init.obj) : error LNK2005: ___xc_a ??? MSVCRT.lib(cinitexe.obj) ??? LIBC.lib(crt0init.obj) : error LNK2005: ___xi_z ??? MSVCRT.lib(cinitexe.obj) ??? LIBC.lib(crt0init.obj) : error LNK2005: ___xi_a ??? MSVCRT.lib(cinitexe.obj) ??? LIBC.lib(crt0init.obj) : warning LNK4006: ___xc_z ?? MSVCRT.lib(cinitexe.obj ) ???????????? LIBC.lib(crt0init.obj) : warning LNK4006: ___xc_a ?? MSVCRT.lib(cinitexe.obj ) ???????????? LIBC.lib(crt0init.obj) : warning LNK4006: ___xi_z ?? MSVCRT.lib(cinitexe.obj ) ???????????? LIBC.lib(crt0init.obj) : warning LNK4006: ___xi_a ?? MSVCRT.lib(cinitexe.obj ) ???????????? ????? build\temp.win32-2.4\Release\chm\_chmlib.lib ??? build\temp.win 32-2.4\Release\chm\_chmlib.exp LINK : warning LNK4098: ???"MSVCRT"???????????? /NODEFAULTLIB:l ibrary LINK : warning LNK4098: ???"LIBC"???????????? /NODEFAULTLIB:lib rary build\lib.win32-2.4\chm\_chmlib.pyd : fatal error LNK1169: ?????????? ???? error: command '"D:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link .exe"' failed with exit status 1169 How to fix this problem??? PS: if someone has compile it successfully in windows,Please send me a copy!!! Thanks a lot!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com Thu Jan 25 19:49:53 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 25 Jan 2007 18:49:53 -0600 Subject: difflib qualm In-Reply-To: References: <2adc542f0701241805i79b79580y2522ec854e49621d@mail.gmail.com> Message-ID: <4-CdnZBrjaO4zSTYnZ2dnUVZ_v6tnZ2d@comcast.com> Gabriel Genellina wrote: > At Wednesday 24/1/2007 23:05, Sick Monkey wrote: > >> I am trying to write a python script that will compare 2 files which >> contains names (millions of them). >> >> More specifically, I have 2 files (Files1.txt and Files2.txt). >> Files1.txt contains 180 thousand names and Files2.txt contains 34 >> million names. >> >> I have a script which will analyze these two files and store them into >> 2 different lists (fileList1 and fileList2 respectivly). I have >> imported the diflib library and after the lists are created, matching >> on the following criteria " " for diflib -> (just the names that are >> similar between the two files). >> >> This works perfectly for hundreds of names but is taking forever for >> millions of them; thus not really efficient. >> >> Does anyone have any idea on how to get this more efficient? >> (speaking of Time and RAM) >> >> Any advice would be greatly appreciated. (NOTE: I have been trying >> to study multithreading, but have not really grasp the concept. So I >> may need some examples.) > > When you say "names" you mean people's names? So you want to match, say, > Levenshtein Vladimir to Lebenstain V.? And you only have the names to > match? > Not a good candidate for difflib. See this paper: > Record Linkage: A Machine Learning Approach, A Toolbox, and A Digital > Government Web Service (2003) > Mohamed G. Elfeky, Vassilios S. Verykios, Ahmed K. Elmagarmid, Thanaa M. > Ghanem, Ahmed R. Huwait. > http://citeseer.ist.psu.edu/elfeky03record.html > and you can get other pointers from the Levenshtein distance article in > Wikipedia and http://en.wikipedia.org/wiki/Fuzzy_string_searching > > One approach: Put the big list of names in a database and create soundex keys for the names and make the soundex keys an index so you can search quickly. Databases are really good at storing data that is searchable via an index. If you REALLY need speed you can consider an in-memory database. Create soundex keys for each name in your small list and query the database with this key into the table in the DB that is indexed on soundex keys. If you get a hit, the key is sufficiently "alike" to be a candidate. I'll leave the remainder to you. Perhaps there is other information that will help determine if there is a match? -Larry Bates From walter at livinglogic.de Wed Jan 31 04:15:25 2007 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Wed, 31 Jan 2007 10:15:25 +0100 Subject: Unicode error handler In-Reply-To: <45C049EA.60009@v.loewis.de> References: <45C049EA.60009@v.loewis.de> Message-ID: <45C05E2D.80205@livinglogic.de> Martin v. L?wis wrote: > Walter D?rwald schrieb: >> You might try the following: >> >> # -*- coding: iso-8859-1 -*- >> >> import unicodedata, codecs >> >> def transliterate(exc): >> if not isinstance(exc, UnicodeEncodeError): >> raise TypeError("don'ty know how to handle %r" % r) >> return (unicodedata.normalize("NFD", exc.object[exc.start])[:1], >> exc.start+1) > > I think a number of special cases need to be studied here. > I would expect that this is "semantically correct" if the characters > being dropped are combining characters (at least in the languages I'm > familiar with, it is common to drop them for transliteration). True, it might make sense to limit the error handler to handling latin characters. > However, if you do > > py> for i in range(65536): > ... c = unicodedata.normalize("NFD", unichr(i)) > ... for c2 in c[1:]: > ... if not unicodedata.combining(c2): print hex(i),;break > > you'll see that there are many characters which don't decompose > into a base character + sequence of combining characters. In > particular, this involves all hangul syllables (U+AC00..U+D7A3), > for which it is just incorrect to drop the "jungseongs" > (is that proper wording?). Of course the above error handler only makes sense, when the decomposed codepoints are encodable in the target encoding. For your hangul example neither u"\ac00" nor the decomposed version u"\u1100\u1161" er encodable. > There are also some cases which I'm completely uncertain about, > e.g. ORIYA VOWEL SIGN AI decomposes to ORIYA VOWEL SIGN E + > ORIYA AI LENGTH MARK. Is it correct to drop the length mark? > It's not listed as a combining character. Likewise, > MYANMAR LETTER UU decomposes to MYANMAR LETTER U + > MYANMAR VOWEL SIGN II; same question here. Servus, Walter From jerzy.zielinski at gmail.com Wed Jan 24 16:37:22 2007 From: jerzy.zielinski at gmail.com (Zielinski) Date: 24 Jan 2007 13:37:22 -0800 Subject: matplotlib button problem Message-ID: <1169674642.577269.88950@l53g2000cwa.googlegroups.com> Hi, Recently I started to use matplotlib with python. Now I would like to have interaction with my plots. Here is the problem: I have a long vector of data, to long to display it on one picture, because of, well you know to much data to big mess... so I decided to extract some data from long_vector to short_vector with 100 elements. So I have: data_position = 1 interval = 100 for i in range (0, interval): short_vector[i] = long_vector[data_position*interval + i] Then I plot it. works fine... Now I created a button "next" I would like to press it and change the data_position to +1 every time i press it, of course, and redraw the picture. It can be a key on the keyboard, I don't care. Bottom line: how to change the global variable with the button in matplotlib, and redraw a picture using this variable Thanks for help Jerzy jerzy.zielinski at gmail.com From steven.bethard at gmail.com Wed Jan 10 12:10:51 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 10 Jan 2007 10:10:51 -0700 Subject: An iterator with look-ahead In-Reply-To: References: Message-ID: Neil Cerutti wrote: > For use in a hand-coded parser I wrote the following simple > iterator with look-ahead. There's a recipe for this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 Note that the recipe efficiently supports an arbitrary look-ahead, not just a single item. > I haven't thought too deeply about what peek ought to return > when the iterator is exhausted. Suggestions are respectfully > requested. In the recipe, StopIteration is still raised on a peek() operation that tries to look past the end of the iterator. STeVe From steveo at syslang.net Thu Jan 11 11:21:32 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 11 Jan 2007 11:21:32 -0500 (EST) Subject: dot operations In-Reply-To: References: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> Message-ID: On Thursday, Jan 11th 2007 at 11:41 +0100, quoth robert: =>jm.suresh at no.spam.gmail.com wrote: =>> Hi, =>> Frequently I get to do like this: =>> a = (1, 2, 3, 4) # some dummy values =>> b = (4, 3, 2, 1) =>> import operator =>> c = map(operator.add, a, b) =>> =>> I am finding the last line not very readable especially when I combine =>> couple of such operations into one line. Is it possible to overload =>> operators, so that, I can use .+ for element wise addition, as, =>> c = a .+ b =>> which is much more readable. =>> =>> Similarly, I want to use .- , .*, ./ . Is it possible to do? => =>import numpy => =>You'll not even need dots I'm very new so my plea to be gentle is still on. I just looked at the numpy package. Seems very cool, but for the life of me I didn't understand the method by which python allows for creation of infix operators. Can someone please explain or point me to a reference? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From thn at mail.utexas.edu Sun Jan 28 15:46:07 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 28 Jan 2007 12:46:07 -0800 Subject: Trouble with max() and __cmp__() Message-ID: <1170017167.165222.325800@a34g2000cwb.googlegroups.com> My code: class Policy(list): def __cmp__(self,other): return cmp(self.fitness,other.fitness) j = Policy() j.fitness = 3 k = Policy() k.fitness = 1 l = Policy() l.fitness = 5 print max([j,k,l]).fitness prints 3, when I was expecting it to print 5. What have I done wrong? Thanks for the help, THN From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 31 07:35:39 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 31 Jan 2007 13:35:39 +0100 Subject: Sorting a List of Lists In-Reply-To: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> References: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> Message-ID: <45c08cd3$0$22805$426a74cc@news.free.fr> apotheos at gmail.com a ?crit : > I can't seem to get this nailed down and I thought I'd toss it out > there as, by gosh, its got to be something simple I'm missing. > > I have two different database tables of events that use different > schemas. I am using python to collate these records for display. I do > this by creating a list of lists that look roughly like this: > > events = [['Event URL as String', 'Event Title as String ', Event Date > as Datetime], ...] Then you should not use a list of lists, but a list of tuples. > I then thought I'd just go events.sort(lambda x,y: x[2] it a day. That didn't work. But then lamda functions like to be very > simple, maybe object subscripts aren't allowed (even though I didn't > get an error). So I wrote a comparison function that looks much as you > would expect: > > def date_compare(list1, > list2): > x = list1[2] > y = list2[2] > if > x>y: > return > 1 > elif > x==y: > return > 0 > else: # > x return -1 > > But as before sorting with this function returns None. > > What have I overlooked? Lol. I guess this is a FAQ. list.sort() performs a destructive in-place sort, and always return None. This is in the FineManual: bruno at bruno:~$ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help(list.sort) Help on method_descriptor: sort(...) L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 You may want to use sorted(iterable, cmp=None, key=None, reverse=False) if you don't want to sort in-place. Also, using comparison functions is usually not the most efficient way to do such a sort. In your case, I'd go for a good old Decorate/sort/undecorate (AKA schwarzian transform): events = [evt for date, evt in sorted([(evt[2], evt) for evt in events])] HTH From nulla.epistola at web.de Wed Jan 24 14:47:26 2007 From: nulla.epistola at web.de (Hertha Steck) Date: Wed, 24 Jan 2007 20:47:26 +0100 Subject: Python Windows Editors References: <1169415514.562496.248950@a75g2000cwd.googlegroups.com> Message-ID: Am Mon, 22 Jan 2007 00:33:12 +0000 schrieb W. Watson: > mensanator at aol.com wrote: >> W. Watson wrote: >>> I downloaded python-2.5.msi and installed it. I believe its editor is IDE. I >>> understand there's a Win editor called pythonwin. I believe it's in the >>> download pywin32-210.win32-py2.5.exe, but I'm not sure if this exe file has >>> just the editor or all of Python. Comments? If not how do I get the >>> PythonWin editor by itself? By "IDE" you mean IDLE, don't you? >> >> Print your files from Notepad, after all, they're just text files. >> But IDLE has more usefull Formatting options. > Thanks. Already did it, but used Word. I can get line numbers in that way. And you are absolutely certain you won't never, ever, detect a typo when you have your script open in Word, correct it, save the file and try to use the resulting mess as a Python script? Or does Word leave it as a text file in such a case? I never dare to open source code in Word, so I'm not really sure. Hertha From laurent.pointal at limsi.fr Tue Jan 23 03:51:09 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 23 Jan 2007 09:51:09 +0100 Subject: beep or sound playing under linux In-Reply-To: References: Message-ID: hg a ?crit : > Hi, > > Is there a way to do that ? > > Regards, > > hg > Some links: Official doc: http://docs.python.org/lib/mmedia.html ==> http://docs.python.org/lib/module-ossaudiodev.html PyAudio (binding to portaudio): ==> http://people.csail.mit.edu/hubert/pyaudio/ Maybe with pyGame (and SDL): ==> http://www.pygame.org/ From pavlovevidence at gmail.com Sun Jan 7 17:40:38 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 7 Jan 2007 14:40:38 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <1168130960.670978.111850@s34g2000cwa.googlegroups.com> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> <1168048620.409190.85870@v33g2000cwv.googlegroups.com> <1168130960.670978.111850@s34g2000cwa.googlegroups.com> Message-ID: <1168209637.965967.23790@s34g2000cwa.googlegroups.com> Martin Miller wrote: > Carl Banks wrote: > > > Martin Miller wrote: > > > ### non-redundant example ### > > > import sys > > > > > > class Pin: > > > def __init__(self, name, namespace=None): > > > self.name = name > > > if namespace == None: > > > # default to caller's globals > > > namespace = sys._getframe(1).f_globals > > > namespace[name] = self > > > > > > Pin('aap') # create a Pin object named 'aap' > > > Pin('aap2') # create a Pin object named 'aap2' > > > print aap.name > > > print aap2.name > > > > The problem with this is that it only works for global namespaces, > > while failing silently and subtly if used in a local namespace: > > Oh, contrair. It would work fine with local namespaces simply by > overriding the default value of the optional 'namepace' parameter (see > below). Did you try it? > > def fun(): > > Pin('aap') > > aap1 = aap > > fun2() > > aap2 = aap > > print aap1 is aap2 > > > > def fun2(): > > Pin('aap') > > > > If it's your deliberate intention to do it with the global namespace, > > you might as well just use globals() and do it explicitly, rather than > > mucking around with Python frame internals. (And it doesn't make the > > class unusable for more straightforward uses.) > > You could be more explicit by just passing 'globals()' as a second > parameter to the __init__ constructor (which is unnecessary, since > that's effectively the default). > > It's not clear to me how the example provided shows the technique > "failing silently and subtly if used in a local namespace" because what > happens is exactly what I would expect if the constructor is called > twice with the same string and defaulted namespace -- namely create > another object and make the existing name refer to it. If one didn't > want the call to Pin in fun2 to do this, just change fun2 to this: Because the usage deceptively suggests that it defines a name in the local namespace. Failing may be too strong a word, but I've come to expect a consistent behavior w.r.t. namespaces, which this violates, so I think it qualifies as a failure. > def fun2(): > Pin('aap', locals()) Did you actually try this? Better yet, try this function. Make sure aap isn't defined as a global: def fun3(): Pin('aap',locals()) print aap (I get NameError.) > This way the "print aap1 is aap2" statement in fun() would output > "true" since the nested call to Pin would now (explicitly) cause the > name of the new object to be put into fun2's local namespace leaving > the global one created by the call in fun() alone. Did you try it? > Obviously, this was not an objection I anticipated. An important one I > would think is the fact that the current documentation says that > f_globals is a special *read-only* attribute of a frame object implying > that it shouldn't be changed (even though doing so 'works' as my > example illustrates). That means it can't be rebound. It doesn't mean you can't modify the object. Nevertheless, frame objects are an internal feature of Python, not guaranteed to work for other incarnations of Python (it doesn't even exist in IronPython, for example), and subject to change. And what you want to do is easily done in a platform generic way without using sys._getframe. > I think other valid arguments against this practice might include > whether it's an example of good OOP, or a good programming practice at > all, since it involves possibly subtle side-effects, the use of global > variables, and/or is 'unpythonic'. I think programmatically creating variables is fine; I just recommend you not use sys._getframe, nor the automagical namespace self-insertion class, to do it. > Certainly the approach is not without caveats. Despite them, I believe > it can be useful in some contexts, as long as what is going on is > clearly understood. The point of my reply to the OP was mainly just to > illustrate the power and flexibility of Python to the newbie. I guess > to that I should have also added that it gives you "enough rope to > shoot yourself" as Allen Holub said regarding C++. > Cheers, > -Martin Carl Banks From entengk at gmail.com Mon Jan 8 06:07:31 2007 From: entengk at gmail.com (Enteng) Date: 8 Jan 2007 03:07:31 -0800 Subject: General Question About Python Message-ID: <1168254451.098796.144790@42g2000cwt.googlegroups.com> To those who program in python, what programs do you do? Also what community projects are you involved in(OSS probably)? Will mastering the language land me a job? I'm thinking about learning the language as a hobby. Just curious :) From jorge.vargas at gmail.com Fri Jan 5 16:08:19 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Fri, 5 Jan 2007 17:08:19 -0400 Subject: MySQLdb windows binaries for Python 2.5?? Yes, but from a World of Warcraft guild. In-Reply-To: <4866bea60701051151v4f7942bj2921b2143a18a092@mail.gmail.com> References: <1162408100.985370.148650@m7g2000cwm.googlegroups.com> <1166144355.616642.127080@n67g2000cwd.googlegroups.com> <1168019043.523288.50770@38g2000cwa.googlegroups.com> <4866bea60701051151v4f7942bj2921b2143a18a092@mail.gmail.com> Message-ID: <32822fe60701051308g3d64e33fh9b94102cf2862bbc@mail.gmail.com> On 1/5/07, Chris Mellon wrote: > I guess this is your opportunity, as someone who thinks that MySQL > support for Python is important, to assist in maintaining and updating > those wrappers, right? believe me I have tried and in this particular case it's very complicated the main developer knows nothing about windows (by choise), then you need to buy the MS compiler or patch your python, after that you need mysql dev, and then you need to practically guess the compiler flags. From fredrik at pythonware.com Thu Jan 4 08:02:59 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 Jan 2007 14:02:59 +0100 Subject: Extending Embedded Python and execute external script References: <1167915019.940396.322390@s34g2000cwa.googlegroups.com> Message-ID: "Vertilka" wrote: > I saw several functions: PyRun_AnyFileExFlags, PyRun_SimpleFileExFlags, > PyRun_FileExFlags. > > Questions: > 1) Which one should i use in order to achieve what i need ? PyRun_SimpleFile or PyRun_SimpleString should be good enough. Using SimpleString is more robust: http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-on-unix-why.htm and also lets you implement additional glue in Python code instead of in C/C++. > 2) I couldn't understand the differance betwwen the three ? AnyFile supports interactive devices, RunFile requires you to provide a custom execution context. > 3) What is the difference between the "FILE *fp" and "const char > *filename" arguments of these functions. If i give a FILE*, why do i > need to give the file name ? Python needs the filename to be able to give meaningful error messages. From martin at v.loewis.de Sun Jan 21 03:38:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Jan 2007 09:38:18 +0100 Subject: A solution to the MSVCRT vs MSVCR71 problem? In-Reply-To: References: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> Message-ID: <45B3267A.80605@v.loewis.de> Gabriel Genellina schrieb: > This would only work, if runtime dll's were compatibles between them, > and they are not. You can't blindly redirect a call to msvcr71.__xyz to > msvcr80.__xyz and expect that to work magically - it may have a > different number of arguments, or different types, or even may not exist > anymore. Actually, the libraries *are* binary-compatible (on the ABI level). You just can't mix two libraries in a single program easily. > (And what about any symbol exported by ordinal?) That doesn't happen for msvcrt, as the import library links by name. Regards, Martin From mccredie at gmail.com Tue Jan 9 09:46:15 2007 From: mccredie at gmail.com (Matimus) Date: 9 Jan 2007 06:46:15 -0800 Subject: Determine an object is a subclass of another References: <1168353205.066357.39530@42g2000cwt.googlegroups.com> Message-ID: <1168353975.285391.212350@m30g2000cwm.googlegroups.com> First you need to subclass the classes so that Dog actually is a subclass of Animal which is a subclass of thing... class Thing: pass class Animal(Thing): pass class Dog(Animal): pass class Weapon(Thing): pass class Gun(Weapon): pass Then you can use 'isinstance' >>>d = Dog() >>>isinstance(d,Thing) True >>>isinstance(d,Animal) True >>>isinstance(d,Weapon) False >>>isinstance(d,Gun) False From gagsl-py at yahoo.com.ar Sat Jan 13 08:52:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Jan 2007 10:52:51 -0300 Subject: Command line arguments on Vista References: <1168613362.406648.304720@11g2000cwr.googlegroups.com> Message-ID: "Duncan Booth" escribi? en el mensaje news:Xns98B69A42F81D3duncanbooth at 127.0.0.1... > It sounds like the registry entry for running Python files is messed up. > Can you go to a command line and see what the command 'ftype Python.File' > displays? (Assuming that command lines and ftype still work on Vista) > > The output should be: > Python.File="C:\Python25\python.exe" "%1" %* > > but if it only says: > Python.File="C:\Python25\python.exe" "%1" > > then you would get the behaviour you observed (on any version of Windows, > not just Vista). That would happen if the association was not made by the Python installer, but by the user selecting Python.exe the first time he tried to execute a Python script by double-clicking on it. -- Gabriel Genellina From paddy3118 at netscape.net Thu Jan 25 14:03:49 2007 From: paddy3118 at netscape.net (Paddy) Date: 25 Jan 2007 11:03:49 -0800 Subject: The reliability of python threads In-Reply-To: References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> Message-ID: <1169751828.986583.47200@j27g2000cwj.googlegroups.com> On Jan 25, 9:26 am, n... at cus.cam.ac.uk (Nick Maclaren) wrote: > In article <1169675599.502726.5... at a34g2000cwb.googlegroups.com>,"Paddy" writes:|> > |> Three to four months before `strange errors`? I'd spend some time > |> correlating logs; not just for your program, but for everything running > |> on the server. Then I'd expect to cut my losses and arrange to safely > |> re-start the program every TWO months. > |> (I'd arrange the re-start after collecting logs but before their > |> analysis. Life is too short). > > Forget it. That strategy is fine in general, but is a waste of time > where threading issues are involved (or signal handling, or some types > of communication problem, for that matter). Nah, Its a great strategy. it keeps you up and running when all you know for sure is that you will most likely be able to keep things together for three months normally. The OP only thinks its a threading problem - it doesn't matter what the true fix will be, as long as arranging to re-start the server well before its likely to go down doesn't take too long, compared to your exploration of the problem, and, of course, you have to be able to afford the glitch in availability. > There are three unrelated > killer facts that interact: > > Such failures are usually probabilistic ("Poisson process"), and > so have no "history". > > The expected number is usually proportional to the square of the > activity, sometimes a higher power. > > Virtually nothing involved does any routine logging, or even has > options to log relevant events. > > The first means that the strategy of restarting doesn't help. All > three mean that current logs are almost never any use. > > Regards, > Nick Maclaren. From grante at visi.com Fri Jan 5 00:40:44 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 05:40:44 -0000 Subject: What is proper way to require a method to be overridden? References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> <12prkb29em82cac@corp.supernews.com> Message-ID: <12prp6sppuqdq17@corp.supernews.com> On 2007-01-05, Thomas Ploch wrote: >>> I learn so much from this list. I didn't even know this error >>> existed. >> >> And remember: even if it didn't, you could have created your >> own: > > Erm, it wasn't me who asked. I just wanted to say that I didn't know > that there is a NotImplementedError. Sorry, I sort of lost track. You can still invent your own Exceptions anyway. ;) Just don't do what I do and take the lazy way out: raise "method not implemented" That's considered bad form these days. -- Grant Edwards grante at visi.com From bdesth.quelquechose at free.quelquepart.fr Mon Jan 29 16:44:37 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Jan 2007 22:44:37 +0100 Subject: List Behavior when inserting new items In-Reply-To: <1170097845.805992.118870@h3g2000cwc.googlegroups.com> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> <526ut2F1n2q69U1@mid.uni-berlin.de> <1170097845.805992.118870@h3g2000cwc.googlegroups.com> Message-ID: <45be63e4$0$5953$426a74cc@news.free.fr> Drew a ?crit : >>What is your actual usecase? >> >>diez > > > The issue is that I don't know how long the list will eventually be. How is this an issue ? Python's lists are not fixed-sized arrays. > Essentially I'm trying to use a 2D list to hold lines that I will > eventually print to the screen. > > Blank elements in the list will be > printed as spaces. I suppose every time I add an element, I could find > the difference between the size of the list and the desired index and > fill in the range between with " " values, Yes. But note that [1,2,3,' ',' ',4] is not the same thing as [1,2,3,,,4] (which is not valid Python FWIW). > however I just wanted to > see if there was a more natural way in the language. I'm not sure I get it. Do you mean you're trying to use a list of lists as a representation of a 2D matrix (IOW, a bitmap) ? Something like bpm = [ ['X',' ',' ',' ','X'], [' ','X',' ','X',' '], [' ',' ','X',' ',' '], [' ','X',' ','X',' '], ['X',' ',' ',' ','X'], ] If so, using dicts can be somewhat simpler and less memory-consuming: d = {1:1, 2:2, 3:3} d[10] = 4 for i in range(1, max(d.keys())+1): print d.get(i, ' ') That is, instead of storing useless spaces for "blank cells" and having to do math to compute how many of them you have to insert/delete, you just place stuff at desired indices, and 'fill in' spaces when printing out to screen. HTH From jarausch at skynet.be Tue Jan 2 09:13:39 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 02 Jan 2007 15:13:39 +0100 Subject: python2.5 frameobject - how to upgrade? Message-ID: <459a6894$0$9322$ba620e4c@news.skynet.be> Hi, I'd like to install a package ('rekall') which uses frame->f_nlocals which is no longer contained in frameobject.h What's the recommended way to upgrade such an application? Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From robert.kern at gmail.com Sat Jan 27 16:50:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Jan 2007 15:50:08 -0600 Subject: distutils, sdist and tests In-Reply-To: References: Message-ID: Steven Bethard wrote: > How do I get distutils to include my testing module in just the "sdist" > distribution? Use a MANIFEST. http://docs.python.org/dist/source-dist.html > I want test_argparse.py to be available in the source distribution, but > I don't think it should be included in the binary distributions. > > Or am I just being to picky? Do folks normally include their tests in > the binary distributions? Some do, but only when they are packages and can thus hide.the.tests . -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From knipknap at gmail.com Sun Jan 14 08:49:32 2007 From: knipknap at gmail.com (Samuel) Date: 14 Jan 2007 05:49:32 -0800 Subject: Announcing: Spiff Guard (Generic Access Lists for Python) Message-ID: <1168782572.308514.171190@11g2000cwr.googlegroups.com> Introduction ------------ Spiff Guard is a library for implementing access lists in Python. It provides a clean and simple API and was implemented with performance and security in mind. It was originally inspired by phpGACL (http://phpgacl.sourceforge.net/), but features an API that is significantly cleaner and easier to use. Spiff Guard is the first library published as part of the Spiff platform. The Spiff platform aims to produce a number of generic libraries generally needed in enterprise (web) applications. Spiff Guard is free software and distributed under the GNU GPLv2. Dependencies ------------- sqlalchemy (http://www.sqlalchemy.org/) Download --------- Please check out the code from SVN: svn checkout http://spiff.googlecode.com/svn/trunk/libs/Guard/ Links: ------- Spiff project page: http://code.google.com/p/spiff/ Bug tracker: http://code.google.com/p/spiff/issues/list Documentation: http://spiff.googlecode.com/svn/trunk/libs/Guard/README Browse the source: http://spiff.googlecode.com/svn/trunk/libs/Guard/ Any questions, please ask (or file a bug). -Samuel From skip at pobox.com Wed Jan 17 09:43:59 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Jan 2007 08:43:59 -0600 Subject: 2.3-2.5 what improved? In-Reply-To: <45ADFACC.6080807@chamonix.reportlab.co.uk> References: <45ADFACC.6080807@chamonix.reportlab.co.uk> Message-ID: <17838.13871.896086.9204@montanaro.dyndns.org> Robin> I sort of remember claims being made about 2.5 being 10% faster Robin> than 2.4/2.3 etc etc. Can anyone say where the speedups were? What's New might be enlightening: http://www.google.com/search?q=what%27s+new+site%3Apython.org Skip From simon.hengel at siemens.com Thu Jan 25 13:25:59 2007 From: simon.hengel at siemens.com (Hengel, Simon) Date: Thu, 25 Jan 2007 19:25:59 +0100 Subject: Python for amd64 and x86 on Windows Message-ID: Hello List, I need the amd64 and the x86 version of Python installed on one Windows machine. Is there a way to do this? (I think I read about it somewhere, but now I can't find it anymore) Cheers, Simon Hengel Siemens AG Medical Solutions CO CHS CS 2 Mozartstr. 57 91052 Erlangen, Germany Tel.: +49 (9131) 7-24591 mobile: +49 (176) 61 064 074 simon.hengel at siemens.com Siemens Aktiengesellschaft: Vorsitzender des Aufsichtsrats: Heinrich v. Pierer; Vorstand: Klaus Kleinfeld, Vorsitzender; Johannes Feldmayer, Joe Kaeser, Rudi Lamprecht, Eduardo Montes, J?rgen Radomski, Erich R. Reinhardt, Hermann Requardt, Uriel J. Sharef, Klaus Wucherer Sitz der Gesellschaft: Berlin und M?nchen Registergericht: Berlin Charlottenburg, HRB 12300, M?nchen, HRB 6684 WEEE-Reg.-Nr. DE 23691322 From arkanes at gmail.com Thu Jan 25 14:02:42 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 25 Jan 2007 13:02:42 -0600 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> <4866bea60701240736v837d246w187ecb1ccb90eefd@mail.gmail.com> <4866bea60701250609u61e72d30q21dd11c8c8fd9bcd@mail.gmail.com> Message-ID: <4866bea60701251102o6af055e1j2d85de2f30b64c64@mail.gmail.com> On 1/25/07, Boris Borcic wrote: > Chris Mellon wrote: > > On 1/25/07, Boris Borcic wrote: > >> Chris Mellon wrote: > > >>>>> > >>>>> Some quick & dirty wxPython code > >>>>> > >>>>> def getTextBitmap(text, font, fgcolor, bgcolor): > >>>>> dc = wx.MemoryDC() > >>>>> dc.SetFont(font) > >>>>> width, height= dc.GetTextExtent(text) > >>>>> bmp = wx.EmptyBitmap(width, height) > >>>>> dc.SelectObject(bmp) > >>>>> dc.SetBackground(wx.Brush(bgcolor)) > >>>>> dc.Clear() > >>>>> dc.SetTextBackground(bgcolor) > >>>>> dc.SetTextForeground(fgcolor) > >>>>> dc.DrawText(text, 0, 0) > >>>>> dc.SelectObject(wx.NullBitmap) > >>>>> return bmp > >>>>> > >>>>> > >>>>> Raw win32 code will look similar but will be much more verbose. > >>>> Thx again for this base. > >>>> > >>>> Quickly testing this, it appears that the result is rendered half a pixel off in > >>>> the x-direction. Does this make sense ? Is it possible to position text with > >>>> subpixel accuracy ? > > >> In short, wx._gdi_ fights quite hard to enforce what I am trying to avoid :( I > >> might admire its consistency if it extended to treating both axes similarly... > >> > > > > I have not recently had a need to examine drawn text output this > > closely, but I am familiar with the C++ code that implements the > > drawing and it's a direct wrapping of win32 GDI calls. If it's not > > matching your source text, then the source may be drawn using a > > different method or using one of the alternate engines, like GDI+. > > Maybe. In any case, color separation solves my (sub)problem : the blue layer > from the wx generated model matches the green layer from the app's window, pixel > for pixel (at least with antialiasing and cleartype on, while writing black on > white). > That's... extremely interesting. If it works for you, go for it! If you're interested in some other things to try, wx.EmptyBitmap takes a depth parameter you can use to eliminate color. From ziga.seilnacht at gmail.com Fri Jan 26 06:00:23 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 26 Jan 2007 03:00:23 -0800 Subject: xml.dom.minidom.parseString segmentation fault on mod_python In-Reply-To: <1169804514.862290.274940@q2g2000cwa.googlegroups.com> References: <1169804514.862290.274940@q2g2000cwa.googlegroups.com> Message-ID: <1169809222.955833.176380@j27g2000cwj.googlegroups.com> On Jan 26, 10:41 am, qert... at gmail.com wrote: > Python 2.4.4 > mod_python 3.2.10 + Apache 2.0 > > def index( req, **params ): > from xml.dom.minidom import parseString > doc = parseString( "whatever" ) > > => blank screen, _no_any_exception_; Apache error_log: > [Fri Jan 26 10:18:48 2007] [notice] child pid 17596 exit signal > Segmentation fault (11) > > Outside mod_python code works well. Any ideas? I would be grateful. http://www.python.org/sf/1558223 http://www.python.org/sf/1295808 http://www.python.org/sf/1075984 Try to compile all your dependencies against the same version of Expat or upgrade to python 2.5. Ziga From grahn+nntp at snipabacken.dyndns.org Thu Jan 18 08:05:20 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 18 Jan 2007 13:05:20 GMT Subject: How can I create a linked list in Python? References: <1168983652.192715.235580@a75g2000cwd.googlegroups.com> Message-ID: On Wed, 17 Jan 2007 10:11:40 +0100, Marc 'BlackJack' Rintsch wrote: > In <1168983652.192715.235580 at a75g2000cwd.googlegroups.com>, bearophileHUGS > wrote: > >> In CPython they are dynamic arrays, they aren't lists. Try adding >> elements at the beginning of a list compared to adding elements at the >> beginning or in the middle of a python "list" and you will see the >> efficiency differences. > > Python has a list type without the "s, it's a real list. Don't confuse > the *ADT list* with *linked lists* which are just one implementation of > the ADT list. I think the terminology is already so confused that you cannot say "list" unless context implies that you mean e.g. a Python list. For example, SML (a language favored by people interested in types and type systems) uses the term "list", but a SML "list" really acts like a stack. FWIW, I oppose the idea (paraphrased from further up the thread) that linked lists and other data structures are obsolete and dying concepts, obsoleted by Python and other modern languages. 99% of the time. a Python list is the right tool for the job, but that's only because we have CPU cycles to spare and the 'n' in our 'O(n)' is limited. You cannot call yourself a computer scientist without understanding things like linked lists. No other data structure has the same characteristics (good and bad) as that one. Or those two, really. I mean, what would Knuth say? ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From ggrp1.20.martineau at dfgh.net Wed Jan 24 18:19:29 2007 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 24 Jan 2007 15:19:29 -0800 Subject: New os.path.exists() behavior - bug or feature? In-Reply-To: <1166401777.533652.208840@n67g2000cwd.googlegroups.com> References: <1166401777.533652.208840@n67g2000cwd.googlegroups.com> Message-ID: <1169680769.297818.189930@v45g2000cwv.googlegroups.com> FWIW, your code works correctly for me in all respects with Python 2.5 on Windows XP Pro. I no longer have Python 2.4.x installed, so can't easily do a comparison. Perhaps the problem has something to do with Python 2.5 with Windows 2K. -Martin On Dec 17 2006, 4:29 pm, "klappnase" wrote: > Hi all, > yesterday I installed Python-2.5 and python-2.4.4 on my windows2k box. > When trying to use os.path.exists() to detect which drives are present > on the system I noticed that > these behave differently: > > Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] > on win32 > Type "copyright", "credits" or "license()" for more information. > > >>> import os > >>> for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if os.path.exists('%s:\\' % char): > print '%s:\\' % char > > A:\ > C:\ > D:\ > E:\ > > ########################################### > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > > >>> import os > >>> for char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if os.path.exists('%s:\\' % char): > print '%s:\\' % char > > C:\ > > When I insert a floppy into A: os.path.exists('A:\\') will return True > on Python-2.5, too. > Does anyone know, is this inconsistent behavior a bug or a new feature? > > I also noticed that theTixbinaries are no longer present in 2.5, does > anyone know if it is > planned to remove them pemanently? > > Thanks in advance > > Michael From martin at v.loewis.de Wed Jan 3 10:40:53 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 16:40:53 +0100 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167757721.883547.70530@42g2000cwt.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> <1167757721.883547.70530@42g2000cwt.googlegroups.com> Message-ID: <459BCE85.5070707@v.loewis.de> Ben Sizer schrieb: > Firstly, that solution only works for actual Python scripts; it doesn't > solve the utility scripts that are often installed to the /scripts > directory. Those packages should install .bat files into /scripts on Windows. > It's a shame that many responses on this thread don't > address that half of the issue. Am I the only person who installs > packages that add scripts (not all of which are Python ones)? Perhaps not. However, people apparently disagree what the "full issue" is. If you have non-Python scripts (eg. VBScript) in /scripts, how will having python.exe on PATH help at all? >> Unfortunately the Python installer is not an InnoSetup installer. > > The page I linked to is a bit misleading but there is an executable on > that page. All you then have to do is invoke it with the relevant > parameter. Please submit a patch that does so, then. Make sure you add user interface to make it an option. These things are *not* easy, and claiming that they are is misleading. Regards, Martin From mirandacascade at yahoo.com Sun Jan 7 16:23:29 2007 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 7 Jan 2007 13:23:29 -0800 Subject: AES256 in PyCrypto References: <1168134542.337448.261510@s34g2000cwa.googlegroups.com> <1168184060.548851.11540@i15g2000cwa.googlegroups.com> Message-ID: <1168205009.554907.181120@v33g2000cwv.googlegroups.com> Sebastian 'lunar' Wiesner wrote: > Since you are apparently unable to read to docstrings of this module, I > will give you a short hint: yes, pycrypto supports AES with 256 bit > keys. Thank you for the information. The material I consulted was: a) the PyCrypto manual: http://www.amk.ca/python/writing/pycrypt/ b) the .py files that shipped with the PyCrypto package Is a docstring is the text between the three consecutive quote characters in a .py file? The reason for the question is that I looked at the .py files that shipped with PyCrypto. Of the various .py files that shipped with PyCrypto, there were two files (both __init__.py) that contained information seemed to pertain to AES. The stuff between the 3 consecutive quote chars in: Crypto.__init__.py Crypto.Cipher.__init__.py make reference to AES, but I wasn't able to determine from what I read if that was AES256. Which .py file contain the docstrings that flesh out the information summarized in the short hint? Can docstrings be embedded within the .pyd extension modules as well? Does the AES.pyd extension module have docstrings? How does one view the docstrings in a .pyd file? When I reference AES from the interactive of Pythonwin: >>> from Crypto.Cipher import AES >>> x = AES.new( As soon as I type the '(' character, the IDE displays: new(key, [mode], [IV]): Return a new AES encryption object then when x gets instantiated, and the encrypt method gets called... >>> x.encrypt( As soon as I type the '(' character, the IDE displays: Encrypt the provided string of binary data I'm guessing that what the IDE is displaying is the first line of what may be multiple-line docstring that is embedded within the .pyd extension module? Might there be more lines in the docstring? Thank you. From bearophileHUGS at lycos.com Tue Jan 16 12:24:45 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Jan 2007 09:24:45 -0800 Subject: A note on heapq module Message-ID: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> In few minutes I have just written this quite raw class, it lacks doctring (the same of the functions of the heapq module), it may contain bugs still, I haven't tested it much. It's just a simple wrapper around some of the functions of the heapq module (nsmallest and nlargest are missing). Usually I use classes only when I need then, I like functional programming enough, and this class seems to just slow down the functions of the heapq module. But I think an improved class similar to this one may be useful (added, replacing isn't necessary) into the heapq module, because it can avoid cetain errors: I know what Heaps are and how they work, but some time ago I have written a bug into small program that uses the functions of the heapq module, because I have added an item to the head of the heap using a normal list method, breaking the heap invariant. With a simple class like this one all the methods of your object keep the heap invariant, avoiding that kind of bugs. (If you are interested I can improve this class some, it't not difficult.) from heapq import heapify, heappush, heappop, heapreplace class Heap(object): def __init__(self, init=None): if init is None: self.h = [] elif isinstance(init, Heap): self.h = init.h[:] else: self.h = list(init) heapify(self.h) def smallest(self): return self.h[0] def sort(self, cmp=None, key=None): self.h.sort(cmp=cmp, key=key) def heappush(self, item): heappush(self.h, item) def heappop(self): return heappop(self.h) def heapreplace(self, item): return heapreplace(self.h, item) def clear(self): del self.h[:] def __contains__(self, item): return item in self.h def __hash__(self): raise TypeError("Heap objects are unhashable.") def __iter__(self): return self.h.__iter__() def __eq__(self, other): return isinstance(other, Heap) and self.h == other.h def __ne__(self, other): return not isinstance(other, Heap) or self.h != other.h def __len__(self): return len(self.h) def __nonzero__(self): return bool(self.h) def __str__(self): return str(self.h) def __repr__(self): return "Heap(%s)" % self.h if self.h else "Heap()" Bye, bearophile From rschroev_nospam_ml at fastmail.fm Fri Jan 12 15:27:47 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 12 Jan 2007 20:27:47 GMT Subject: Newbie imap lib question In-Reply-To: <1168611888.009894.271190@51g2000cwl.googlegroups.com> References: <1168611888.009894.271190@51g2000cwl.googlegroups.com> Message-ID: <7bSph.287183$Tz5.5784715@phobos.telenet-ops.be> jrpfinch schreef: > I have three messages in my inbox. Why does messageCount = > gServer.select('INBOX') not just return OK and 3. See below for > examples - seems to be completely random how many threes it returns. > The documentation for imaplib seems sparse. Does anybody have any good > links? Many thanks, Jon > > messageCount = > 0 : OK > 1 : ['3'] > messageCount = > 0 : OK > 1 : ['3', '3', '3'] > messageCount = > 0 : OK > 1 : [None] > messageCount = > 0 : OK > 1 : ['3', '3'] I'm afraid I can't help you: all I can say is that it works for my. It gives consistent results each time I run it. >>> import imaplib >>> M = imaplib.IMAP4('...') >>> M.login('...', '...') ('OK', ['User logged in']) >>> M.select('INBOX') ('OK', ['740']) Always the same. Though the number changes if I receive or delete mail of course. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From gagsl-py at yahoo.com.ar Thu Jan 11 02:16:23 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 04:16:23 -0300 Subject: Joining threads but allowing signals to main thread? In-Reply-To: <87irfeawrj.fsf@asfast.com> References: <87irfeawrj.fsf@asfast.com> Message-ID: <7.0.1.0.0.20070111040620.058d6cc0@yahoo.com.ar> At Thursday 11/1/2007 03:43, Lloyd Zusman wrote: > while threading.activeCount() > 1: > time.sleep(0.001) > > sys.exit(0) > >Is there any way to allow my program to respond to signals without >having to busy-wait in the main thread? Don't worry too much, this is *not* a busy wait, because you use sleep. You can use a longer sleep, it will be terminated by any signal. But not too long, or the check for activeCount() will be delayed in excess. (I use sleep(1) usually but your needs may be different) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From kay.schluehr at gmx.net Mon Jan 1 12:48:15 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 1 Jan 2007 09:48:15 -0800 Subject: PEP 3107 Function Annotations for review and comment In-Reply-To: References: <1167568000.728842.170160@48g2000cwx.googlegroups.com> Message-ID: <1167673695.249834.40100@a3g2000cwd.googlegroups.com> Tony Lownds wrote: > On Dec 31, 2006, at 4:26 AM, Kay Schluehr wrote: > > > I have two questions: > > > > 1) I don't understand the clause ('*' [tname] (',' tname ['=' test])* > > in the grammar rule of typedargslist. Does it stem from another PEP? > > > > Yes, PEP 3102 Keyword-only Arguments. > > > 2) Is the func_annotation information for def foo(*c: list) > > stored as {"*c": list} preserving optional argument information or > > {"c":list} ? > > > > {"c": list} > > -Tony Good. There is still one issue. I understand that you don't want to fix the semantics of function annotations but to be usefull some annotations are needed to express function types. Using those consistently with the notation of the enhanced function statement I suggest introducing an arrow expression and an __arrow__ special function: expr: arrow_expr ('->' arrow_expr)* arrow_expr: xor_expr ('|' xor_expr)* ... class Algebraic(type): ''' Metaclass used to enable operations on classes or subclasses ''' def __init__(cls, name, bases, dict): super(Algebraic, cls).__init__(name, bases, dict) def __arrow__(cls, codom): fntype = Function(*cls.dom) fntype.codom = codom return fntype def Function(*domains): "Function type generator" class FunType: __metaclass__ = Algebraic dom = domains codom = () return FunType maptype = Function( Function(object)->object, list) -> list From webmaster at cacradicalgrace.org Mon Jan 22 15:13:02 2007 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Mon, 22 Jan 2007 13:13:02 -0700 Subject: Does eval has the same features as Perl's? References: Message-ID: The python editor won't "get exit." It will raise an exception. With or without an eval, you can catch the exception. try: x = 1/0 except ZeroDivisionError: x = "infinity" Jm lists wrote: > Hello members, > > I want to know does the "eval" in python have the same features as in > Perl (capture errors)? > > For example,in perl I can wrote: > > $re = eval { 1 / 0 }; > > Though 1/0 is a fatal error but since it's in "eval" block so the perl > interpreter doesn't get exit. > > Thanks again. From duncan.booth at invalid.invalid Fri Jan 26 13:13:56 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Jan 2007 18:13:56 GMT Subject: Fixed length lists from .split()? References: <2007012611072716807-bob@passcalnmtedu> Message-ID: Bob Greschke wrote: > Is there a fancy way to get Parts=Line.split(";") to make Parts always > have three items in it, or do I just have to check the length of Parts > and loop to add the required missing items (this one would just take > Parts+=[""], but there are other types of lines in the file that have > about 10 "fields" that also have this problem)? >>> def nsplit(s, sep, n): return (s.split(sep) + [""]*n)[:n] >>> nsplit("bcsn; 1000001; 1456", ";", 3) ['bcsn', ' 1000001', ' 1456'] >>> nsplit("bcsn; 1000001", ";", 3) ['bcsn', ' 1000001', ''] >>> From michael at mustun.ch Sun Jan 7 16:23:22 2007 From: michael at mustun.ch (Michael M.) Date: Sun, 07 Jan 2007 22:23:22 +0100 Subject: how to find the longst element list of lists Message-ID: How to find the longst element list of lists? I think, there should be an easier way then this: s1 = ["q", "e", "d"] s2 = ["a", "b"] s3 = ["a", "b", "c", "d"] if len(s1) >= len(s2) and len(s1) >= len(s3): sx1=s1 ## s1 ist l?ngster if len(s2) >= len(s3): sx2=s2 sx3=s3 else: sx2=s3 sx3=s2 if len(s2) >= len(s3) and len(s2) >= len(s1): sx1=s2 ## s2 ist l?ngster if len(s3) >= len(s1): sx2=s3 sx3=s1 else: sx2=s1 sx3=s3 if len(s3) >= len(s1) and len(s3) >= len(s2): sx1=s3 ## s3 ist l?ngster if len(s1) >= len(s2): sx2=s1 sx3=s2 else: sx2=s2 sx3=s1 After, the list ist sorted: sx1 = ["a", "b", "c", "d"] sx2 = ["q", "e", "d"] sx3 = ["a", "b"] From aboudouvas at panafonet.gr Fri Jan 5 10:36:56 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 5 Jan 2007 07:36:56 -0800 Subject: program deployment In-Reply-To: <12psqqk75ij5ta5@corp.supernews.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <12psqqk75ij5ta5@corp.supernews.com> Message-ID: <1168011416.291950.286500@s80g2000cwa.googlegroups.com> > Under Windows, I ususally use py2exe+inno-setup. Xmmm...i have downloaded this and try a (very) simple project and it is working great. Of your experience, does it also working great when you have more complex solutions, e.x. many 3rd party modules like wxWidgets and so ?? From nmm1 at cus.cam.ac.uk Wed Jan 10 04:36:53 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 10 Jan 2007 09:36:53 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: In article , Tim Peters writes: |> |> Huh. I don't read it that way. If it said "numbers can be ..." I |> might, but reading that way seems to requires effort to overlook the |> "decimal" in "decimal numbers can be ...". I wouldn't expect YOU to read it that way, but I can assure you from experience that many people do. What it MEANS is "Numbers with a short representation in decimal can be represented exactly in decimal arithmetic", which is tautologous. What they READ it to mean is "One advantage of representing numbers in decimal is that they can be represented exactly", and they then assume that also applies to pi, sqrt(2), 1/3 .... The point is that the "decimal" could apply equally well to the external or internal representation and, if you aren't fairly clued-up in this area, it is easy to choose the wrong one. |> >|>> and how is decimal no better than binary? |> |> >|> Basically, they both lose info when rounding does occur. For |> >|> example, |> |> > Yes, but there are two ways in which binary is superior. Let's skip |> > the superior 'smoothness', as being too arcane an issue for this |> > group, |> |> With 28 decimal digits used by default, few apps would care about this |> anyway. Were you in the computer arithmetic area during the "base wars" of the 1960s and 1970s that culminated with binary winning out? A lot of very well-respected numerical analysts said that larger bases led to a faster build-up of error (independent of the precision). My limited investigations indicated that there was SOME truth in that, but it wasn't a major matter; I never say the matter settled definitively. |> > and deal with the other. In binary, calculating the mid-point |> > of two numbers (a very common operation) is guaranteed to be within |> > the range defined by those numbers, or to over/under-flow. |> > |> > Neither (x+y)/2.0 nor (x/2.0+y/2.0) are necessarily within the range |> > (x,y) in decimal, even for the most respectable values of x and y. |> > This was a MAJOR "gotcha" in the days before binary became standard, |> > and will clearly return with decimal. |> |> I view this as being an instance of "lose info when rounding does |> occur". For example, No, absolutely NOT! This is an orthogonal matter, and is about the loss of an important invariant when using any base above 2. Back in the days when there were multiple bases, virtually every programmer who wrote large numerical code got caught by it at least once, and many got caught several times (it has multiple guises). For example, take the following algorithm for binary chop: while 1 : c = (a+b)/2 if f(x) < y : if c == b : break b = c else : if c == a : break a = c That works in binary, but in no base above 2 (assuming that I haven't made a stupid error writing it down). In THAT case, it is easy to fix for decimal, but there are ways that it can show up that can be quite tricky to fix. Regards, Nick Maclaren. From rganesan at myrealbox.com Fri Jan 12 05:10:13 2007 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Fri, 12 Jan 2007 15:40:13 +0530 Subject: maximum number of threads References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: >>>>> Felipe Almeida Lessa writes: >> >> to modify the maximum number of user process (AFAIK each thread use a >> process entry on Linux) > I don't think it's only this. It isn't that at all. The default Linux POSIX threads stack size is 8MB. Linux user space is 3GB (Kernel is mapped at upper 1GB). 382 * 8 = 3056MB. Basically, you're running out of address space. I don't know if you have any control at python level. In C you can call pthread_attr_setstacksize(). Ganesan -- Ganesan Rajagopal From contact at hidden-master.yahoo.com Sun Jan 14 00:57:59 2007 From: contact at hidden-master.yahoo.com (Phloyd Bird) Date: Sun, 14 Jan 2007 05:57:59 GMT Subject: Sexy Vidz Message-ID: An HTML attachment was scrubbed... URL: From nick at craig-wood.com Tue Jan 23 13:30:08 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 23 Jan 2007 12:30:08 -0600 Subject: How to use time.clock() function in python References: <1169503516.425217.218790@q2g2000cwa.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > I am following this python example trying to time how long does an > operation takes, like this: > > My question is why the content of the file (dataFile) is just '0.0'? > I have tried "print >>dataFile, timeTaken" or "print >>dataFile,str( > timeTaken)", but gives me 0.0. > Please tell me what am I missing? > > > t1 = time.clock() > os.system(cmd) > > outputFile = str(i) + ".png" > > t2 = time.clock() > > timeTaken = t2 - t1 > allTimeTaken += timeTaken > print >>dataFile, timeTaken Under unix, time.clock() measures CPU time used by the current process. os.system() will consume almost zero CPU while it waits for the command you ran to finish. You probably want time.time(), eg >>> from time import clock, time >>> print clock(), time() 0.01 1169573460.96 >>> print clock(), time() 0.01 1169573463.76 >>> print clock(), time() 0.01 1169573467.09 >>> However running the same under windows you get a quite different result :- >>> from time import clock, time >>> print clock(), time() 7.54285810068e-006 1169574534.84 >>> print clock(), time() 3.32073322168 1169574538.16 >>> print clock(), time() 7.32428004118 1169574542.15 >>> In windows clock() counts in real time and at much higher resolution than time(). Under windows time() counts in 1ms steps wheras it usually counts in 1us steps under linux. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py at yahoo.com.ar Fri Jan 19 14:27:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 16:27:46 -0300 Subject: when format strings attack In-Reply-To: <1169232233.469572.298320@a75g2000cwd.googlegroups.com> References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> <1169232233.469572.298320@a75g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20070119162249.043e8cd8@yahoo.com.ar> At Friday 19/1/2007 15:43, John Zenger wrote: >Perhaps it is not as severe a security risk, but pure Python programs >can run into similar problems if they don't check user input for % >codes. Example: > > >>> k = raw_input("Try to trick me: ") >Try to trick me: How about %s this? > >>> j = "User %s just entered: " + k > >>> print j % "John" >Traceback (most recent call last): > File "", line 1, in ? > print j % "John" >TypeError: not enough arguments for format string That's not a problem, it's an exception. *This* is a problem: printf("Hello, %s") -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From wilder.usenet at gmail.com Thu Jan 11 17:24:04 2007 From: wilder.usenet at gmail.com (J) Date: 11 Jan 2007 14:24:04 -0800 Subject: Matching Directory Names and Grouping Them Message-ID: <1168554244.459131.190440@k58g2000hse.googlegroups.com> Hello Group- I have limited programming experience, but I'm looking for a generic way to search through a root directory for subdirectories with similar names, organize and group them by matching their subdirectory path, and then output their full paths into a text file. For example, the contents of the output text file may look like this: \Input1\2001\01\ \Input2\2001\01\ \Input3\2001\01\ \Input1\2002\03\ \Input2\2002\03\ \Input3\2002\03\ \Input2\2005\05\ \Input3\2005\05\ \Input1\2005\12\ \Input3\2005\12\ I tried working with python regular expressions, but so far haven't found code that can do the trick. Any help would be greatly appreciated. Thanks! J. From dimitri.pater at gmail.com Wed Jan 24 19:15:56 2007 From: dimitri.pater at gmail.com (dimitri pater) Date: Thu, 25 Jan 2007 01:15:56 +0100 Subject: matplotlib button problem In-Reply-To: <1169674642.577269.88950@l53g2000cwa.googlegroups.com> References: <1169674642.577269.88950@l53g2000cwa.googlegroups.com> Message-ID: Hi, post your question on matplotlib-users at lists.sourceforge.net regards, Dimitri On 24 Jan 2007 13:37:22 -0800, Zielinski wrote: > > Hi, > > Recently I started to use matplotlib with python. Now I would like to > have interaction with my plots. Here is the problem: > > I have a long vector of data, to long to display it on one picture, > because of, well you know to much data to big mess... so I decided to > extract some data from long_vector to short_vector with 100 elements. > So I have: > data_position = 1 > interval = 100 > for i in range (0, interval): > short_vector[i] = long_vector[data_position*interval + i] > > Then I plot it. works fine... > Now I created a button "next" I would like to press it and change the > data_position to +1 every time i press it, of course, and redraw the > picture. It can be a key on the keyboard, I don't care. > > Bottom line: how to change the global variable with the button in > matplotlib, and redraw a picture using this variable > > Thanks for help > Jerzy > jerzy.zielinski at gmail.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Fri Jan 12 09:14:59 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 12 Jan 2007 09:14:59 -0500 Subject: Rational Numbers In-Reply-To: References: Message-ID: <1168611299.3382.36.camel@dot.uniqsys.com> On Thu, 2007-01-11 at 23:47 +0000, Nick Maclaren wrote: > In article , > Facundo Batista writes: > |> Noud Aldenhoven wrote: > |> > |> > When I was programming in a mathematical project I began to wonder if python > |> > supports rational numbers[1]. In a language like magma[2] it's not such a > |> > problem. Does python supports something simular? > |> > |> Python does not have rational numbers. > |> > |> There's a (rejected) PEP about this, PEP-239: > |> > |> http://www.python.org/dev/peps/pep-0239/ > |> > |> Maybe you also want to read the section "Why not rational?" of > |> PEP-327... > |> > |> http://www.python.org/dev/peps/pep-0327/#why-not-rational > > Oh, God. Decimal delusions again :-( > > There are good arguments for not having a rational type, but the idea > that decimal floating-point is in any way a replacement is cuckoo. You're putting words in Facundo's mouth. Facundo didn't say why we should read that section of PEP 327. I think he merely pointed to the slow performance of rational numbers that's explained in that section. (Facundo is the author of PEP 327, so I find it unlikely that he has delusions about what decimals can and can't do.) It is true that decimal arithmetic is not a replacement for rational arithmetic, but I don't see anybody on this thread or in PEP 327 stating that it is. -Carsten From horpner at yahoo.com Thu Jan 18 13:03:41 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 18 Jan 2007 18:03:41 GMT Subject: Traversing the properties of a Class References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> Message-ID: On 2007-01-18, EdG wrote: > For debugging purposes, I would like to traverse the class > listing out all the properties. This is the first thing that came to mind. def show_properties(cls): for attr in dir(cls): if isinstance(getattr(cls, attr), property): print attr -- Neil Cerutti -- Posted via a free Usenet account from http://www.teranews.com From emin.shopper at gmail.com Fri Jan 12 09:10:39 2007 From: emin.shopper at gmail.com (Emin) Date: 12 Jan 2007 06:10:39 -0800 Subject: How much slower is dict indexing vs. list indexing? In-Reply-To: References: <1168555253.601611.258600@k58g2000hse.googlegroups.com> Message-ID: <1168611039.720278.13430@s34g2000cwa.googlegroups.com> On Jan 11, 5:53 pm, Steve Holden wrote: > > What technique were you thinking of to look up the cached index values > in Python, just as a matter of curiosity? Storing them in a dict? It > would be hard to think of a faster way ... ;-) I didn't have anything fancy in mind. I was just wondering whether it makes sense to replace a block of code like data = {'a' : 1, 'b' :2, 'c' : 3} for i in someLargeList: for name in ['a','b','c']: result.append(data[name]) with somthing like data = {'a' : 1, 'b' :2, 'c' : 3} dataValues = [data[k] for k in ['a','b','c'] for i in someLargeList: for index in [0,1,2]: result.append(dataValues[index]) It sounds like it's probably not worth the effort in general, but might be for extremely ultra-critical parts of code. Thanks From ptwobrussell at gmail.com Sun Jan 14 12:10:24 2007 From: ptwobrussell at gmail.com (MR) Date: 14 Jan 2007 09:10:24 -0800 Subject: Decorators inside of class and decorator parameters In-Reply-To: <1168763727.677028.149640@51g2000cwl.googlegroups.com> References: <1168728983.541526.202320@l53g2000cwa.googlegroups.com> <1168763727.677028.149640@51g2000cwl.googlegroups.com> Message-ID: <1168794623.987118.182460@51g2000cwl.googlegroups.com> Wow. Really neat stuff there. memoize seems especially cool since you can get lots of nice dynamic programming benefits "for free" (sorry if I just stated the obvious, but I thought was was especially cool.) Michele Simionato wrote: > Gabriel Genellina wrote: > > see this article by M. Simoniato > > http://www.phyast.pitt.edu/~micheles/python/documentation.html for a better > > way using its decorator factory. > > Actually the name is Simionato ;) > I have just released version 2.0, the new thing is an update_wrapper > function similar to the one > in the standard library, but with the ability to preserve the signature > on demand. For instance > > def traced(func): > def wrapper(*args, **kw): > print 'calling %s with args %s, %s' % (func, args, kw) > return func(*args, **kw) > return update_wrapper(wrapper, func, create=False) > > works exactly as functools.update_wrapper (i.e. copies__doc__, > __module__,etc. from func to wrapper without > preserving the signature), whereas update_wrapper(wrapper, func, > create=True) creates a new wrapper > with the right signature before copying the attributes. > > Michele Simionato From steve at holdenweb.com Sun Jan 28 04:59:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Jan 2007 09:59:45 +0000 Subject: More Python screencasts (Google videos) In-Reply-To: <1169959174.477911.105890@k78g2000cwa.googlegroups.com> References: <1169959174.477911.105890@k78g2000cwa.googlegroups.com> Message-ID: kirby.urner at gmail.com wrote: > Here're three sample 3-6 min videos showing off Python to math > teachers > thinking about using a computer language instead of just calculators: > > http://controlroom.blogspot.com/2007/01/python-for-math-teachers.html > > Higher resolution versions are available to teachers enrolling in our > program. > > Kirby > Kirby: Have you seen what can be done with Crunchy? That's a neat way to present interactive Python content with surrounding pedagogical information. See you at PyCon? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From evan at binarymanipulations.com Tue Jan 2 05:44:57 2007 From: evan at binarymanipulations.com (Evan Carmi) Date: Tue, 2 Jan 2007 10:44:57 +0000 (UTC) Subject: how to move files based on file-ending from dirs and =?utf-8?b?c3ViZGlycwl0bwlzcGVjaWZpYw==?= dir? References: Message-ID: Marc 'BlackJack' Rintsch gmx.net> writes: > This line is quite complicated and I don't really grasp what it's doing. > Maybe some comments, possible with examples, are needed here. And maybe > then you'll see why it doesn't work as wanted!? If these are the > destination paths and they should be at the same level as `top`, where is > `top` here? Shouldn't that be a prefix of all destination paths? > > Ciao, > Marc 'BlackJack' Rintsch I figured out the problem, with a lot of help. Thanks for the help Evan From tmaroff at yahoo.com Wed Jan 10 21:24:54 2007 From: tmaroff at yahoo.com (Tristan) Date: 10 Jan 2007 18:24:54 -0800 Subject: IDLE Python and Environment Variables Message-ID: <1168482294.349660.137380@i56g2000hsf.googlegroups.com> Hello community: I post this because I could not find satisfactory answers in the posts generated by this nice group. I work on winXP. I have many little python applications in different folders, each application can share or not other objects located in the same or other folders. The way I work to use these applications is: 1) For almost everyone, I execute a corresponding ".bat file" into which I define and/or include values for some "temporal" environment variables that let me find all the objects that the selected application uses. Sometimes I include in the .bat file the execution of the application, but generally I leave in a prompt status, ready to invoke python or some dos commands. 2) When I close the command prompt window, there are no traces of my enviroment variables in my windows system (that is right). Only the default windows environment variables remain. I tried to do the same with the IDLE (and I imagine tha same occurs with Python command line), but I have the next problem: I can not find in IDLE (or another app?) the way to previously define and/or include automatically values for my "temporal" environment variables as I do in the .bat files. The use of Control Panel -> System -> Advanced is tedious to use as, my enviroment variables values are "temporal". Any advice, please??? From jamesthiele.usenet at gmail.com Wed Jan 10 13:20:37 2007 From: jamesthiele.usenet at gmail.com (James Thiele) Date: 10 Jan 2007 10:20:37 -0800 Subject: Seattle Python Interest Group Thursday at 7:00 PM Message-ID: <1168453237.257064.142040@77g2000hsv.googlegroups.com> 7pm at the bar below Third Place books in Ravenna: http://www.seapig.org/ThirdPlaceMeetingLocation From kuldjlevelet at gmail.com Thu Jan 18 07:13:52 2007 From: kuldjlevelet at gmail.com (0k-) Date: 18 Jan 2007 04:13:52 -0800 Subject: classes: need for an explanation In-Reply-To: <1169121502.779509.138890@m58g2000cwm.googlegroups.com> References: <1169121502.779509.138890@m58g2000cwm.googlegroups.com> Message-ID: <1169122432.139579.310260@q2g2000cwa.googlegroups.com> oops, i forgot to mention i'm using interpreter version 2.4.3 From mohitbhatt79 at gmail.com Fri Jan 12 13:27:19 2007 From: mohitbhatt79 at gmail.com (mohit) Date: 12 Jan 2007 10:27:19 -0800 Subject: I need to consume a .NET web service in a Python client Message-ID: <1168626439.257622.134700@38g2000cwa.googlegroups.com> Hello, I am a .NET developer experimenting with Python. I need to consume a .NET web service in a Python client. how do I go about it? which libraries do i need? pointers to help me get started would be much appreciated. I am just a newbie to the Python world so please be bear with my novice queries. thanks in advance, Mohit From nagle at animats.com Tue Jan 30 13:24:20 2007 From: nagle at animats.com (John Nagle) Date: Tue, 30 Jan 2007 18:24:20 GMT Subject: Convert raw data to XML In-Reply-To: <1170125415.883023.316950@s48g2000cws.googlegroups.com> References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> <1170125415.883023.316950@s48g2000cws.googlegroups.com> Message-ID: Actually, that's not "raw data" coming in, that's valid XML. Why do you need to indent it? Just write it to a file. If you really need to indent XML, get BeautifulSoup, read the XML in with BeautifulStoneSoup, and write it back out with "prettify()". But if the next thing to see that XML is a program, not a human, why bother? John Nagle Justin Ezequiel wrote: > On Jan 30, 10:42 am, elrondru... at gmail.com wrote: > >>For example the raw data is as follows >> >>SomeText >Description>PassorFail >> >>without spaces or new lines. I need this to be written into an XML >>file as >> >> >> >> >> >> >> SomeText >> >> >> PassorFail >> >> >> >> > > raw = r' >>SomeText PassorFail > ABC>' > import xml.dom.ext > import xml.dom.minidom > doc = xml.dom.minidom.parseString(raw) > xml.dom.ext.PrettyPrint(doc) > > > > > SomeText > PassorFail > > > > From deets at nospam.web.de Wed Jan 31 13:11:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 31 Jan 2007 19:11:57 +0100 Subject: "Correct" db adapter References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> <1170262532.590048.247580@a75g2000cwd.googlegroups.com> Message-ID: <52c4fdF1o9fd9U1@mid.uni-berlin.de> king kikapu wrote: > Thanks for the replies. > > I think i do not need something like ORM, but just a db-module that i > can "work" the database with it. > I just want to know if pyodbc is the "correct" solution to do so or if > it is another db-module that is more > usefull for this job. I think you've got something wrong. There is no such thing as a generic DB-Adapter, except maybe from the mxODBC which pushes the abstraction to the ODBC-layer. If your app is DB-API2.0-compatible, you should be able to more or less just use your code with different adapters. There are several ways to accomplish a configurable way, but in the end it boils down to someting like this: if is_postgres: import psycopg2 as db if is_mysql: import MySQLdb as db Then db can be used to connect and query the db. A thin layer on top of that should maybe be written to cover different parameter-styles, but that shouldn't be too hard. Diez From cping at dso.org.sg Tue Jan 16 02:27:55 2007 From: cping at dso.org.sg (Jeremy) Date: Tue, 16 Jan 2007 15:27:55 +0800 Subject: Python Threads and C Semaphores Message-ID: Hello, I have a fat C++ extension to a Python 2.3.4 program. In all, I count five threads. Of these, two are started in Python using thread.start_new_thread(), and both of these wait on semaphores in the C++ extension using sem_wait(). There also are two other Python threads and one thread running wholly in the extension. I notice that when one of the Python threads calls the extension and waits on a semaphore, all but the C++ thread halt even when not waiting on any semaphore. How do we get this working right? Thank you, Jeremy From tdelaney at avaya.com Wed Jan 31 16:43:55 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 1 Feb 2007 08:43:55 +1100 Subject: Conditional expressions - PEP 308 Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1EC77@au3010avexu1.global.avaya.com> Colin J. Williams wrote: > Yes, I agree. The ternary operator is a step forward. That's still debateable ;) Pro: It puts paid to the "python doesn't have a ternary operator" and and/or abuse. Con: It shouldn't ever be used. Cheers, Tim Delaney From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 3 09:01:00 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 03 Jan 2007 15:01:00 +0100 Subject: list/dictionary as case statement ? References: <71pmp2tq1klma5urhkfiv8bpq6u8sgtj06@4ax.com> Message-ID: <501r8sF1dp76aU1@mid.individual.net> Tom Plunket wrote: > Often (always?) RISC architectures' instruction+operand lengths > are fixed to the word size of the machine. E.g. the MIPS 3000 and > 4000 were 32 bits for every instruction, and PC was always a ^^ > multiple of four. Intels aren't RISC, are they? But for PowerPC it's the same, every instruction has 32 bit. Regards, Bj?rn -- BOFH excuse #278: The Dilithium Crystals need to be rotated. From gagsl-py at yahoo.com.ar Sun Jan 28 20:03:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Jan 2007 22:03:46 -0300 Subject: memory leak In-Reply-To: References: Message-ID: <7.0.1.0.0.20070128214301.01c36438@yahoo.com.ar> At Wednesday 24/1/2007 22:06, john g wrote: >i have a memory leak issue with extension function that im working >on. it reads data from a binary file into a stl vector then creates >a new list to pass back to the python interface. the function works >the first 1021 times but then gives a segmentation fault (core >dumped). heres the business part of the code: > > >//read data > vector data; > float temp; > > > for(int x=0;x { > fread(&temp,sizeof(float),1,datfil); > data.push_back(temp); > } > > > //convert vector to list > PyObject *newlist = PyList_New(np*2); > PyList_SetItem(newlist, 0,PyFloat_FromDouble(data[0])); > for(int x=0;x { > PyList_SetItem(newlist, x,PyFloat_FromDouble(data[x])); > } > > > > > > > //send back list > return newlist; You have to check for possible errors. And you don't need to build the C++ vector, just use PyList_SET_ITEM on each value as you read it. (_SET_ITEM because it's a new, empty, list). This is how I'd do that (untested): float temp; PyObject *newlist; newlist = PyList_New(np*2); if (newlist == NULL) return NULL; for(int x=0;x References: <8301441.post@talk.nabble.com> <45a7bc70$0$299$426a34cc@news.free.fr> Message-ID: <45a80ad9$0$311$426a74cc@news.free.fr> tonydevlin a ?crit : > > > Bruno Desthuilliers wrote: > >>tonydevlin a ?crit : >> >>>I am creating a workflow in plone using argouml and archgenxml. I have >>>been >>>following the steps on the site:- >>>http://plone.org/documentation/tutorial/anonymously-adding-custom-content-types-with-argouml-and-archgenxml/creating-a-class-and-workflow-with-argouml >>> >>>However I am confused at step 9 in creating the class section, where it >>>says: >>>"Now, save this file as "ProcessImprovement.zargo". Pull up a command >>>prompt and navigate to that directory. Make sure that you've added the >>>ArchGenXML directory to your env path, and type the following: >>>C:\Sandbox\Plone\Tutorial>ArchGenXML.py ProcessImprovement.zargo" >>> >>>I have saved the file in the location >>>C:\Documents and Settings\Tony\Desktop\Test\ProcessImprovement.zargo >>>However I dont know what to type in the python command prompt!!! >> >>Which *python* command prompt ? The author is talking about a shell, >>here (you know, this strange stuff that looks like good ole time DOS...). >> >> >>-- >>http://mail.python.org/mailman/listinfo/python-list >> >> >>I yes sorry I was obviously not thinking properly, however there is still >>a problem, when I run this in dos after I have changed to the correct >>directory the ArchGenXML file that I downloaded does not work. "does not work" is the worst possible description of a problem. >> I renamed >>it from its original name because that did not work, it just came up with >>can not find program for it to run off. It still does the same. The same what ? (no, don't answer) Tony, I don't mean to be rude, but may I suggest that you first learn to use your system, then learn to run a Python program from the command line on your system ? FWIW, none of the problems you exposed so far is related to Python... From kmsmgill at gmail.com Fri Jan 19 09:00:20 2007 From: kmsmgill at gmail.com (kmsmgill at gmail.com) Date: 19 Jan 2007 06:00:20 -0800 Subject: Login Form References: Message-ID: <1169215219.940343.90960@51g2000cwl.googlegroups.com> Ghirai wrote: > Hello python-list, > > I need to make a login form, if possible without cookies. > Can anyone point me in the right direction? Or are there any > examples? > > Thanks. > > -- > Best regards, > Ghirai. You'd do pretty good using the 'cgi' module, which is documented at http://www.python.org/doc/lib/module-cgi.html A quick web search found an example site for the cgi module: http://www.cs.virginia.edu/~lab2q/lesson_7/ Don't be afraid to search for good examples on the web, adapt them, and try them out on your own box. --Kevin From steve at holdenweb.com Wed Jan 24 08:35:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Jan 2007 13:35:08 +0000 Subject: Thoughts on using isinstance In-Reply-To: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> Message-ID: <45B7608C.4000007@holdenweb.com> abcd wrote: > In my code I am debating whether or not to validate the types of data > being passed to my functions. For example > > def sayHello(self, name): > if not name: > rasie "name can't be null" > if not isinstance(name, str): > raise "name must be a string" > print "Hello " + name > > Is the use of isinstance a "bad" way of doing things? is it a "heavy" > operation? for example, if I use this in each function validate input > will it slow things down a lot? > > just curious how you might handle this type of situation (other than > not validating at all). > > thanks > The "Python way" is to validate by performing the operations you need to perform and catching any exceptions that result. In the case of your example, you seem to be saying that you'd rather raise your own exception (which, by the way, should really be a subclass of Exception, but we will overlook that) that relying on the interpreter to raise a ValueError or a TypeError. Is there really any advantage to this? You increase your code size and add *something* to execution time with little real purpose. People coming to Python after C++ or some similar language that allows or requires parameter type declarations often don't feel comfortable taking this direction to start with, but it works well for most of us. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From smusnmrNOSPAM at yahoo.com Sat Jan 20 14:41:33 2007 From: smusnmrNOSPAM at yahoo.com (Siggi) Date: Sat, 20 Jan 2007 20:41:33 +0100 Subject: Win GUI application: avoiding DOS console References: <45b25ec1$0$16367$426a74cc@news.free.fr> Message-ID: Thanks, but I don't mean that, I am looking for the method keeping *.py. "Bruno Desthuilliers" schrieb im Newsbeitrag news:45b25ec1$0$16367$426a74cc at news.free.fr... > Siggi a ?crit : >> Hi all, >> >> how do I avoid the DOS console show-up when starting a WinXP GUI >> application with mouseclick on the respective Python file? > > rename yourfile.py to yourfile.pyw From sschwarzer at sschwarzer.net Sat Jan 6 20:37:26 2007 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 07 Jan 2007 02:37:26 +0100 Subject: Why less emphasis on private data? In-Reply-To: References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <45A04ED6.2050403@sschwarzer.net> On 2007-01-07 01:54, BJ?rn Lindqvist wrote: > Google for "python for consenting adults" > > Or ask yourself the opposite question. Why does C++ and C# prefer more > private data? It is given that emphasizing private data > (encapsulation) leads to more internal complexity and more lines of > code because you have to write getters and setters and stuff. With > that in mind, why do you think that data encapsulation makes code less > error prone? Can you prove it? Or do you have anecdotal evidence of > where data encapsulation saved your ass? > > IMHO, that data hiding is good, is one of those ideas that have been > repeated so much that virtually everyone thinks it is true. But > Python proves that it isn't necessarily so. I think attributes (callable or not) which relate to the abstraction of the class should be "public" (special methods or without leading underscore). Attributes that are there for a specific implementation of the abstraction should be "private". The internal implementation of a class is more-often changed in incompatible ways than the abstraction, so distiguishing between a public and a private interface will probably save you from reworking the clients of a class if you prefer the public interface. It will also make the client code easier to understand. Admittedly, there are special cases where you want to access private attributes, e. g. debugging; that's ok. In summary, the distinction between public and non-public attributes IMHO makes sense, but I don't think that the distinction should be enforced by the language as in C++ or Java. Stefan From CRhode at LacusVeris.com Mon Jan 22 18:07:39 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Mon, 22 Jan 2007 17:07:39 -0600 Subject: beep or sound playing under linux In-Reply-To: References: Message-ID: <20070122230739.GG13804@loki> hg wrote this on Mon, Jan 22, 2007 at 04:12:50PM +0100. My reply is below. > Is there a way to do that? (Make noise.) In Gnome there is: gtk.gdk.beep() -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 28? ? Wind WSW 10 mph ? Sky overcast. From leonel.gayard at gmail.com Wed Jan 3 13:52:02 2007 From: leonel.gayard at gmail.com (leonel.gayard at gmail.com) Date: 3 Jan 2007 10:52:02 -0800 Subject: A python library to convert RTF into PDF ? In-Reply-To: <5stnp25m2uffc4n5k7g9e68hk2l85u4fmm@4ax.com> References: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> <5stnp25m2uffc4n5k7g9e68hk2l85u4fmm@4ax.com> Message-ID: <1167850322.373355.327020@s34g2000cwa.googlegroups.com> No, this won't work. First, pdflatex is too slow. Second, my templates are M$-Word doc files, and they cannot be easily converted to tex. I have tried to convert them to tex using OpenOffice, but the result is ugly as hell. I cannot convert the doc files into PDF, because I do not have a library that allows me to manipulate PDF files. Reportlab does *not* do the trick, it can create new pdf files, but it cannot manipulate existing pdf files. So, converting the doc files to RTF, in order to manipulate them is my best chance. Now how can I convert them to PDF ? []'s Leonel Tom Plunket wrote: > leonel.gayard at gmail.com wrote: > > > So, what library can I use to convert from RTF to PDF ? GPL / BSD > > Libraries are welcome. > > If you could write to LaTeX files instead, you could then just use > pdflatex that comes with all of the LaTeX distributions. > > > -tom! > > -- From guettli.usenet at thomas-guettler.de Wed Jan 17 10:26:52 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 17 Jan 2007 15:26:52 GMT Subject: IMAP SEARCH Error References: <1169043202.521317.226910@q2g2000cwa.googlegroups.com> Message-ID: <516thsF1iu0maU1@mid.individual.net> Roopesh wrote: > I am using the imaplib to fetch mails. There is an error thrown in the > search function, which I am not able to comprehend. I had difficulties with the imaplib, too. It is very low level. You need to know some parts of the IMAP protocol. I solved my problems by checking with ethereal (wireshark) what other applications (KMail, getmail) do. getmail is like fetchmail, but written in Python. I found some hints by looking at its source. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 15:50:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 21:50:40 +0100 Subject: Why less emphasis on private data? In-Reply-To: References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> Message-ID: <45a156e4$0$289$426a74cc@news.free.fr> Thomas Ploch a ?crit : > sturlamolden schrieb: (snip) > >>As mentioned in other replies, it is not rocket science to access a >>class private data. In C++ you can cast to void*, in Java and C# you >>can use reflection. C++ is said to be an "unsafe" language because >>programmers can, using a few tricks, mess with the vtables. But how >>many really do that? > > Exactly, if they were available, a lot more would do that. Do you have any concrete evidence ? FWIW, I've seen a *lot* of Python code, and very very few uses of _implementation stuff - most of them being legitimate. > I think this > is the point. Programmers who can do that normally are sensible towards > that people who have designed this or that knew what they were doing. > But there are enough people that don't have a clue and _will_ fiddle > around and then flame all kind of mailing lists with requests for help > cause they did it wrong. The fact is that there's no cure for stupidity. If you want a language explicitly designed to "protect" dummies from themselves, you know where to find it. Why should normally intelligent peoples have to suffer from this ? Are you going to forbid hammers because dummies could smash their fingers then complain ? From nospam at nospam.net Wed Jan 31 00:34:07 2007 From: nospam at nospam.net (Andrew) Date: Tue, 30 Jan 2007 21:34:07 -0800 Subject: socket.inet_ntop, and pton question In-Reply-To: <12rpns1tkp0e34@corp.supernews.com> References: <12rpns1tkp0e34@corp.supernews.com> Message-ID: <45C02A4F.6040000@nospam.net> Hi I just thought I would mention that I found what I needed from dnspython if anyone ever needs ;) http://www.dnspython.org/ From nmm1 at cus.cam.ac.uk Wed Jan 10 13:32:54 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 10 Jan 2007 18:32:54 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Message-ID: In article <1168452879.866265.36880 at i39g2000hsf.googlegroups.com>, "sturlamolden" writes: |> |> In any case, this means that Python can happily keep its GIL, as the |> CPU bound 'HPC' tasks for which the GIL does matter should be done |> using multiple processes (not threads) anyway. That leaves threads as a |> tool for programming certain i/o tasks and maintaining 'responsive' |> user interfaces, for which the GIL incidentally does not matter. Yes. That is the approach being taken at present by almost everyone. |> I wonder if too much emphasis is put on thread programming these days. |> Threads may be nice for programming web servers and the like, but not |> for numerical computing. Reading books about thread programming, one |> can easily get the impression that it is 'the' way to parallelize |> numerical tasks on computers with multiple CPUs (or multiple CPU |> cores). But if threads are inherently designed and implemented to stay |> idle most of the time, that is obviously not the case. You have to distinguish "lightweight processes" from "POSIX threads" from the generic concept. It is POSIX and Microsoft threads that are inherently like that, and another kind of thread model might be very different. Don't expect to see one provided any time soon, even by Linux. OpenMP is the current leader for SMP parallelism, and it would be murder to produce a Python binding that had any hope of delivering useful performance. I think that it could be done, but implementing the result would be a massive task. The Spruce Goose and Project Habbakuk (sic) spring to my mind, by comparison[*] :-) |> I like MPI. Although it is a huge API with lots of esoteric functions, |> I only need to know a handfull to cover my needs. Not to mention the |> fact that I can use MPI with Fortran, which is frowned upon by computer |> scientists but loved by scientists and engineers specialized in any |> other field. Yup. MPI is also debuggable and tunable (with difficulty). Debugging and tuning OpenMP and POSIX threads are beyond anyone except the most extreme experts; I am only on the borderline of being able to. The ASCI bunch favour Co-array Fortran, and its model matches Python like a steam turbine is a match for a heart transplant. [*] They are worth looking up, if you don't know about them. Regards, Nick Maclaren. From sturlamolden at yahoo.no Mon Jan 29 10:14:52 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 29 Jan 2007 07:14:52 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <7x64apzx8f.fsf@ruckus.brouhaha.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <7x3b5uwfa2.fsf@ruckus.brouhaha.com> <1170082883.393745.244840@a34g2000cwb.googlegroups.com> <7x64apzx8f.fsf@ruckus.brouhaha.com> Message-ID: <1170083692.114100.109100@k78g2000cwa.googlegroups.com> On Jan 29, 4:08 pm, Paul Rubin wrote: > "Szabolcs Nagy" writes: > > file('/dev/urandom').read(6).encode('base64') > > (oneliner and without import sa op requested)Nice, though Un*x dependent (os.urandom is supposed to be portable). Is os.urandom cryptographically strong on all platforms? From horpner at yahoo.com Wed Jan 10 09:31:47 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 10 Jan 2007 15:31:47 +0100 Subject: An iterator with look-ahead Message-ID: For use in a hand-coded parser I wrote the following simple iterator with look-ahead. I haven't thought too deeply about what peek ought to return when the iterator is exhausted. Suggestions are respectfully requested. As it is, you can't be sure what a peek() => None signifies until the next iteration unless you don't expect None in your sequence. Using itertools.tee is the alternative I thought about, but caveates in the documentation disuaded me. class LookAheadIter(object): """ An iterator with the a peek() method, so you can see what's coming next. If there is no look-ahead, peek() returns None. >>> nums = [1, 2, 3, 4, 5] >>> look = LookAheadIter(nums) >>> for a in look: ... print (a, look.peek()) (1, 2) (2, 3) (3, 4) (4, 5) (5, None) """ def __init__(self, data): self.iter = iter(data) self.look = self.iter.next() self.exhausted = False def __iter__(self): return self def peek(self): if self.exhausted: return None else: return self.look def next(self): item = self.look try: self.look = self.iter.next() except StopIteration: if self.exhausted: raise else: self.exhausted = True return item -- Neil Cerutti We've got to pause and ask ourselves: How much clean air do we really need? --Lee Iacocca From skip at pobox.com Mon Jan 8 09:15:01 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Jan 2007 08:15:01 -0600 Subject: Table In-Reply-To: <1168215643.745782.34050@s80g2000cwa.googlegroups.com> References: <1168215643.745782.34050@s80g2000cwa.googlegroups.com> Message-ID: <17826.20965.134699.397403@montanaro.dyndns.org> >> Someone know how do I get the collunm's number of a gkt.Table ? This is probably better asked on the pygtk mailing list. Your request seems underspecified. You want the column number given what input? A child widget of the Table? If so, look at gtk.Container's child_get_property method and the list of child properties for gtk.Table children: http://www.pygtk.org/docs/pygtk/class-gtkcontainer.html http://www.pygtk.org/docs/pygtk/class-gtktable.html Skip From vgvr620034 at gmail.com Fri Jan 19 07:07:12 2007 From: vgvr620034 at gmail.com (raghu) Date: 19 Jan 2007 04:07:12 -0800 Subject: Standard streams Message-ID: <1169208432.786099.199690@11g2000cwr.googlegroups.com> what is standard streams in case of python? From ziga.seilnacht at gmail.com Tue Jan 16 18:39:37 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 16 Jan 2007 15:39:37 -0800 Subject: Class data members in C References: Message-ID: <1168990776.614171.130940@v45g2000cwv.googlegroups.com> Nick Maclaren wrote: > Hmm. The extensions documentation describes how to add instance > members to a class (PyMemberDef), but I want to add a class member. > Yes, this is constant for all instances of the class. > > Any pointers? Add something like this to your PyMODINIT_FUNC after you have initialized your type with PyType_Ready: PyDictSetItemString(YourType.tp_dict, "attrname", attrvalue); Ziga From bdesth.quelquechose at free.quelquepart.fr Mon Jan 8 16:24:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Jan 2007 22:24:55 +0100 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> Message-ID: <45a2b060$0$296$426a74cc@news.free.fr> vizcayno a ?crit : > Hello: > Need your help in the "correct" definition of the next function. If > necessary, I would like to know about a web site or documentation that > tells me about best practices in defining functions, especially for > those that consider the error exceptions management. > I have the next alternatives but I think there are better: > > Alternative 1: > ============= > def ExecuteSQL(cmdSQL, cursor): The recommended naming scheme is all_lower for functions, methods and variables, CamelCase for classes and ALL_UPPER for pseudo-constants. > try: > cursor.execute(cmdSQL) > except Exception, e: > return e > return 1 > > Seems a good solution Err... The whole point of exceptions is to avoid using return values as error code. Your code would be *much* better without this braindead (sorry) "exception handling": def execute_sql(sql, cursor): cursor.execute(sql) And now, since it's obvious that it's just a totally useless function call. So just ditch this function, and just call cursor.execute directly !-) (snip other examples of how to not handle exceptions...) From m.yanowitz at kearfott.com Mon Jan 22 11:53:48 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Mon, 22 Jan 2007 11:53:48 -0500 Subject: Is there a better way to implement this: In-Reply-To: Message-ID: <01b101c73e45$e32b4dc0$0d7d12ac@kearfott.com> Thanks. I suppose I could have used time.sleep(seconds) here. I did it in 0.01 because in an earlier verion, I did something else between the sleeps. I guess I am looking for something portable (both Windows and Linux) where I can abort a function after a certain time limit expires. -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Benjamin Niemann Sent: Monday, January 22, 2007 11:19 AM To: python-list at python.org Subject: Re: Is there a better way to implement this: Michael Yanowitz wrote: > Hello: > > I wrote the code below (much irrelevant code removed). > This doesn't quite work. What I wanted it to do was > a) Execute function ftimed, which takes a function and a timeout > in seconds. > b) This will also execute function abort() as a thread. > This function just runs for the specified > number of seconds and returns. > However, before it returns, throws an exception. > c) If test() is still running when abort() is > finished, ftimed() should catch the exception and > return. > > It is catching the exception, however it continues running the function. > Why does it continue and not return? The exception is raised in the thread that executes the abort() function. The exception does not get caught and terminates this thread. The other (main) thread is unaffected - exceptions are local to a thread and there is currently no (portable) way to raise an exception in another thread. > What am I missing, or is there a better way to > implement this (having ftimed() return when the > abort-timer time is exceeded? You may use the signal.alarm() function, if you are on a UNIXoid system and you have only a signle time-out at a time (e.g. not nested). > import time, thread, sys > > thread_finished = "MAX RUN TIME EXCEEDED!" > > def abort (seconds): > start_time = time.time() > while ((time.time() - start_time) < seconds): > time.sleep(0.01) any reason for not using time.sleep(seconds) here? I suppose I could have, but in earlier versions > print "script run time exceeded max_run_time of", seconds, "seconds." > raise thread_finished > return > > > def test(): > i = 0 > while (True): > time.sleep(1) > print "HELLO", i > i+=1 > > > def ftimed (func, seconds): > thread.start_new_thread (abort, (seconds,)) > > try: > func() > except thread_finished: > print "Timeout" > return > > ftimed (test, 30) > print "Script finished" -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ -- http://mail.python.org/mailman/listinfo/python-list From no-spam at no-spam-no-spam.invalid Wed Jan 10 08:03:15 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 10 Jan 2007 14:03:15 +0100 Subject: add re module to a embeded device phyton interpreter In-Reply-To: <1168425645.340291.42720@p59g2000hsd.googlegroups.com> References: <1168425645.340291.42720@p59g2000hsd.googlegroups.com> Message-ID: odlfox wrote: > I hav to add the re (regular expressions) functionality to an > Embeded device that I'm using. I read the re.py file and it says I > need several dependencies, one of them is the pcre module but I found > no pcre.py or pcre.pyc file. Someone knows where to find something to > solve my problem. Thanks a lot > that drills down to a .dll/.so thing depending on installation and python version. Best make a project/test/dummy script using all the things you want - or actually your project as it. And then use cx-freeze like "FreezePython -OO mystart.py" to let him collect all the dependent modules in a dist-folder. Then you don't have to worry about all the details yourself. You can also use UPX and 7zip to further compress the dll's/so's and the py-modules zip archive well. Robert From tim at tdw.net Tue Jan 16 12:59:43 2007 From: tim at tdw.net (Tim Williams) Date: Tue, 16 Jan 2007 17:59:43 +0000 Subject: smtplib question In-Reply-To: References: Message-ID: <9afea2ac0701160959n61c32d27gc8ee627603366327@mail.gmail.com> On 16/01/07, gandalf gold wrote: > > Hi everyone, > > I was trying out smtplib and found out that I can email to anyone in my > domain but not to an email address not in the domain. From browsing on the > web, it seems that this has to do with the configuration of the mail server. > The mail server in my organization is MS exchange. Obviously I can email to > any email address from my MS outlook. > > What's the easiest way to fix the program? > > Thanks. > > - gan > > import sys, smtplib > fr = "xxx at yyy.com" > to = "xxx at zzz.com" # will not work > line = "testing" > subj = "subject line" > msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % (fr, to, subj, line) > server = smtplib.SMTP("EXCHCLUSTER.ccis.edu") > server.set_debuglevel(1) > server.sendmail(fr, [to], msg) > server.quit() > You will need to get smtplib to authenticate when connecting to the exchange server. Use the login function and the same username/pw that you use to login to Outlook. server.login(user, password) Note: Your exchange administrator may have disabled this function. ( Your Outlook will almost certainly be using MAPI not SMTP to talk to the server). HTH :) From martin at v.loewis.de Wed Jan 3 14:14:21 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 20:14:21 +0100 Subject: When argparse will be in the python standard installation In-Reply-To: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> Message-ID: <459C008D.5040404@v.loewis.de> PengYu.UT at gmail.com schrieb: > I feel argparse has some useful things that optparse doesn't have. But > I can't find it argparse in python library reference. I'm wondering > when it will be available in the python standard installation. On its own, never. Somebody has to contribute it to Python, and that somebody has to be the author. However, it would be better if missing features where provided in existing libraries, rather than introducing new libraries to replace the existing ones (i.e. I would likely reject a patch to add yet another argument parsing library - we already have getopt and optparse). Regards, Martin From dummy at dummy.nl Thu Jan 18 08:23:10 2007 From: dummy at dummy.nl (Cecil Westerhof) Date: Thu, 18 Jan 2007 14:23:10 +0100 Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> <1169126216.239740.202950@38g2000cwa.googlegroups.com> Message-ID: <45af74be$0$330$e4fe514c@news.xs4all.nl> Daniele Varrazzo wrote: > Cecil Westerhof wrote: >> I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse >> I can not time the time used to import time, but os and sys do not take >> more as a millisecond. My script itself takes 3 or 4 milliseconds. But >> importing cgi takes 95 milliseconds. (This is on my test system a PII 300 >> MHz. Is there a way to make this more fast? The import off cgi makes the >> script at least 20 times as slow. Something like mod-python is not a >> possibility. I could use it on my test machine, but not at the osting >> provider. > > Does the hosting provider support fastcgi? It would avoid starting the > interpreter at each request too. I am afraid not. It is very bare bone. Also they do not really support python. (When they had a problem, perl and bash scripts worked within a day, python scripts had to wait for one and a halve week.) I am thinking about switching my provider. What are important things to keep in mind when selecting another one? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jan 9 13:14:33 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 09 Jan 2007 19:14:33 +0100 Subject: help: code formatter? References: <50f5nnF1fb5uqU1@mid.individual.net> Message-ID: <50i4c9F1fvo3rU2@mid.individual.net> siggi wrote: > Bjoern wrote: >> Why don't you just write one? :) > > Very funny! Just learning Python :( It isn't funny at all. You'll learn by doing and trying things. That's how all programmers start. Regards, Bj?rn -- BOFH excuse #265: The mouse escaped. From letezo at fw.hu Tue Jan 30 18:31:26 2007 From: letezo at fw.hu (=?iso-8859-2?B?TOl0ZXr1?=) Date: Wed, 31 Jan 2007 00:31:26 +0100 Subject: Why don't have an object() instance a __dict__ attribute by default? Message-ID: <004c01c744c6$c2cf5710$8600a8c0@ANNA> I use Python 2.5, Win32 MSI release. Setting attributes on an empty object does not work: >>> a=object() >>> a.x=1 Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'x' >>> setattr(a, 'x', 1) Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'x' >>> a.__setattr__('x', 1) Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'x' The dir(a) function indicates, that the object instance has no __dict__ attribute. However using an empty new style class works fine: >>> class C(object): pass ... >>> c=C() >>> setattr(c, 'x', 1) >>> The dir(c) function indicates, that the C instance has a __dict__ attribute. Python 2.5 manual says: "Return a new featureless object. object is a base for all new style classes. It has the methods that are common to all instances of new style classes." Why don't have an object() instance a __dict__ attribute by default? This may need some explanation in the Python manual. Viktor -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Wed Jan 17 17:27:14 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 17 Jan 2007 16:27:14 -0600 Subject: Units of measurement In-Reply-To: <7x8xg1xr62.fsf_-_@ruckus.brouhaha.com> References: <7x8xg1xr62.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I'm sure this has been done before, but it just struck my fancy, an > example of Python's "emulating numeric types", inspired by the old > Unix "units" utility, and the Frink language. Oh yeah, it's been done before. Several times over, in fact. Unum http://home.tiscali.be/be052320/Unum.html Caltech's pyre.units http://www.cacr.caltech.edu/projects/pyre/ Konrad Hinsen's Scientific.Physics.PhysicalQuantity http://dirac.cnrs-orleans.fr/ScientificPython/ Will Ware posted one to the list. http://groups.google.com/group/comp.lang.python/browse_frm/thread/8ed89844218b92c7/0f05aea353c1563d And there was another one announced here sometime in the past year or so, IIRC, but I don't recall the name of it or that of the author. :-( -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From dongarbage at hotmail.com Sat Jan 6 13:37:17 2007 From: dongarbage at hotmail.com (dongarbage at hotmail.com) Date: 6 Jan 2007 10:37:17 -0800 Subject: c# application calling Scipy Message-ID: <1168108637.270801.155950@42g2000cwt.googlegroups.com> Hi, Novice here. :) I'm building a c# application and I want to call functions in SciPy from that application. What's the best way to call SciPy methods from a C# program? Is there a best Python implementation for this? Ironython? Python for .NET? Enthought? Thanks in advance, Don From sjmachin at lexicon.net Sun Jan 28 16:32:54 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Jan 2007 13:32:54 -0800 Subject: string byte dump In-Reply-To: <9609c$45bce423$d8a87c2a$8428@NEXICOM.NET> References: <9609c$45bce423$d8a87c2a$8428@NEXICOM.NET> Message-ID: <1170019974.514558.247590@v45g2000cwv.googlegroups.com> On Jan 29, 4:57 am, Jammer wrote: > Does anyone that knows python want to write me a byte dump for strings? :-) > > I am trying to modify a plugin (that someone else wrote) that uses > interprocess communication. > It works on strings without special characters but it fails on other > stings like "Bj?rk". > > It calls decode('utf8') but I guess the strings are not utf8 so I need > to find out what is being input. Try the repr() built-in function. Any byte not in printable ASCII will be displayed in hex. | >>> foo = "\xfforick" | >>> foou = unicode(foo, 'latin1') | >>> foo8 = foou.encode('utf8') | >>> print repr(foo), repr(foou), repr(foo8) | '\xfforick' u'\xfforick' '\xc3\xbforick' From Hieu.D.Hoang at gmail.com Wed Jan 24 11:44:55 2007 From: Hieu.D.Hoang at gmail.com (Hieu.D.Hoang at gmail.com) Date: 24 Jan 2007 08:44:55 -0800 Subject: for thibaut: genuinely excellent pictures - umcu - (1/1) In-Reply-To: <76554951z39773H643349837Z967779246Q5681E633493486P@news.cuartilla.jp> References: <76554951z39773H643349837Z967779246Q5681E633493486P@news.cuartilla.jp> Message-ID: <1169657095.059949.70930@s48g2000cws.googlegroups.com> Just inclined to fire up python to decode the latter part, just to realise i've got dictd binding yet ;-) Probably injected 2 instances of pythons in the spammer thread, for completion's sake. From rawebadvert at yahoo.com Tue Jan 30 21:48:50 2007 From: rawebadvert at yahoo.com (rawebadvert) Date: 30 Jan 2007 18:48:50 -0800 Subject: Learn How To Write A Resume / CV On Our Free Informational Site Message-ID: <1170211730.112780.272250@j27g2000cwj.googlegroups.com> This Website is designed for you to learn how to write a resume on your own. Hiring someone to do a resume is not enough learn how to do it on your own. If you do hire someone to help you write a resume this will help you guide the resume writer to put in the correct information for you to increase your chances on getting a job. This is a free site no fees. People do need resume templates and resume samples as a base to get started on their resumes, but this information that I have on my site will help you fill in the resume templates or resume samples with the best information to present the best possible resume to your potential employer. No matter what type of resume you are writing either a technical resume, sales resume, marketing resume, teaching resume, nursing resume, or general resume this free site will help you. We do not provide resume samples or resume templates just information. If you are a Career Worker looking to change positions, a potential new immigrant, or entry level worker, Please check us out. http://www.resumewritersguide.com ARE YOUR EMPLOYMENT REFERENCES OK WHEN YOU APPLY FOR A JOB HERE ARE SOME TIPS If your looking for employment and you are planning to use references read this site first to learn how to protect yourself from bad references.. http://www.resumewritersguide.com/resumetipsref.htm From stephen.mc at gmail.com Sat Jan 27 05:01:29 2007 From: stephen.mc at gmail.com (Steve) Date: 27 Jan 2007 02:01:29 -0800 Subject: wx Python event question In-Reply-To: <1169881014.463339.257190@v45g2000cwv.googlegroups.com> References: <1169881014.463339.257190@v45g2000cwv.googlegroups.com> Message-ID: <1169892089.110196.98010@a75g2000cwd.googlegroups.com> use wx.Timer - you bind a method to a timer event and define the timer's interval when you start it timer = wx.Timer(self, -1) self.Bind(wx.EVT_TIMER, self.timerMethod, timer) timer.Start(500) On Jan 27, 5:56 pm, "dudds" wrote: > Hi I really haven't used wxPython before and I was just wondering if > there was some sort of timer event that can be used. For example if I > have a database that I want to query at regular intervals and display > the results in a window is that possibly to do under a wx Python > program? > > So far I have come across certain event handlers, but they all seem to > wait for something to happen, like moving the mouse, clicking on a > button etc. I just want to display the results of a query every so > often automatically without having to press a button to do so. > > I'm not looking for a complete solution as I'm doing this so I can > teach myself Python, but a bit of a hint or a nudge in the right > direction would be great. From facundo at taniquetil.com.ar Wed Jan 17 11:48:45 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 17 Jan 2007 16:48:45 +0000 (UTC) Subject: urrlib2 multithreading error References: <1168958510.834175.184730@a75g2000cwd.googlegroups.com> Message-ID: viscanti at gmail.com wrote: > I'm using urllib2 to retrieve some data usign http in a multithreaded > application. > Here's a piece of code: > req = urllib2.Request(url, txdata, txheaders) > opener = urllib2.build_opener() > opener.addheaders = [('User-agent', user_agent)] > request = opener.open(req) > data = request.read(1024) > > I'm trying to read only the first 1024 bytes to retrieve http headers > (if is html then I will retrieve the entire page). Why so much bother? You just can create the Request, open it, and ask for the headers: >>> req = urllib2.Request("http://www.google.com.ar") >>> u = urllib2.urlopen(req) >>> u.headers["content-type"] 'text/html' >>> Take into account that you can add the headers where you put "txheaders", it's not necessary to use "addheaders". And see that I'm not reading the page at all, urllib2.urlopen just retrieves the headers... Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From steven.bethard at gmail.com Thu Jan 4 19:45:36 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 4 Jan 2007 17:45:36 -0700 Subject: [ANN] argparse 0.4 - Command-line parsing library Message-ID: Announcing argparse 0.4 ----------------------- argparse home: http://argparse.python-hosting.com/ argparse single module download: http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw argparse bundled downloads at PyPI: http://www.python.org/pypi/argparse/ New in this release =================== * The add_argument method now allows a positional argument with nargs='*' to specify a default value:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('foo', nargs='*', default=['def']) >>> parser.parse_args('1 2 3'.split()) Namespace(foo=['1', '2', '3']) >>> parser.parse_args([]) Namespace(foo=['def']) About argparse ============== The argparse module is an optparse-inspired command line parser that improves on optparse by: * handling both optional and positional arguments * supporting parsers that dispatch to sub-parsers * producing more informative usage messages * supporting actions that consume any number of command-line args * allowing types and actions to be specified with simple callables instead of hacking class attributes like STORE_ACTIONS or CHECK_METHODS as well as including a number of other more minor improvements on the optparse API. To whet your appetite, here's a simple program that sums its command-line arguments and writes them to a file:: parser = argparse.ArgumentParser() parser.add_argument('integers', type=int, nargs='+') parser.add_argument('--log', type='outfile', default=sys.stdout) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() From gagsl-py at yahoo.com.ar Thu Jan 11 04:54:51 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 06:54:51 -0300 Subject: os.popen() not executing command on windows xp In-Reply-To: <1168508553.151827.261420@k58g2000hse.googlegroups.com> References: <1168508553.151827.261420@k58g2000hse.googlegroups.com> Message-ID: <7.0.1.0.0.20070111065147.04149160@yahoo.com.ar> At Thursday 11/1/2007 06:42, nic wrote: >a = os.popen('"c:\Program Files\Grisoft\AVG Free\avgscan.exe" >"c:\program files\temp1\test1.txt"') Your string contains backquotes, and they have to be escaped. Either use a raw string: os.popen(r'"c:\Program...) or double all backquotes: os.popen('"c:\\Program...) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From yozara at terra.es Wed Jan 31 02:17:21 2007 From: yozara at terra.es (Zara) Date: Wed, 31 Jan 2007 08:17:21 +0100 Subject: PY Zip References: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> Message-ID: On 30 Jan 2007 21:18:52 -0800, "GISDude" wrote: >Hi all. > >I am trying to find a module that has a Zip utility that I can use in >Python. I would like to be able to call the module and ZIP up a >directory. I thought there was such a module, but I have not been able >to find it. > >I need this to be able to be used in Python Win. Is there a ZIP utilty >already stored with a basic PYTHON download? > >Thanks all. It is included with basic Python installation. Look at Pyton Manulas, Library Reference, 12. Data Compression and Archiving. Best regards, Zara From eight02645999 at yahoo.com Sat Jan 27 00:33:47 2007 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 26 Jan 2007 21:33:47 -0800 Subject: strip question Message-ID: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> hi can someone explain strip() for these : [code] >>> x='www.example.com' >>> x.strip('cmowz.') 'example' [/code] when i did this: [code] >>> x = 'abcd,words.words' >>> x.strip(',.') 'abcd,words.words' [/code] it does not strip off "," and "." .Why is this so? thanks From deets at nospam.web.de Fri Jan 12 03:43:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Jan 2007 09:43:28 +0100 Subject: FUCK YOU Jerub on #python, you desynced me for no good reason In-Reply-To: <1168584166.949097.233620@11g2000cwr.googlegroups.com> References: <1168584166.949097.233620@11g2000cwr.googlegroups.com> Message-ID: <50p01oF1hcjs2U1@mid.uni-berlin.de> gavino schrieb: > I can't fucking believe this guy. The chat was jsut getting > interesting about epoll on linux and twisted moduel for it and he > desyncs me. > FUCK JERUB > complete fucking asshole!! I've not been there, and maybe it was rather a network glitch than evil scheming by "Jerub", whoever that may be. But if this post serves as an example of your l337 communication skillz, I can't blame him from banning you. So - restrain yourself. Diez From robert.kern at gmail.com Tue Jan 2 11:10:41 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Jan 2007 10:10:41 -0600 Subject: Unsubscribing from the list In-Reply-To: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> Message-ID: Dotan Cohen wrote: > I need to unsubscribe from this list. I've mailed > users-unsubscribe at python.org but that did not unsubscribe me. I've > also gone to the list homepage and entered my user information, but > that just sent me a message that someone had tried to resubscribe this > username. What must one do to unsubscribe from python-list? Go here: http://mail.python.org/mailman/listinfo/python-list Go to the bottom of the page. Next to the button "Unsubscribe or edit options", enter your email address. Click the button. On the next page, click "Unsubscribe". Follow the instructions in the email that is sent to you. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From Roberto.Bonvallet at cern.ch Sat Jan 13 18:57:56 2007 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Sat, 13 Jan 2007 23:57:56 +0000 (UTC) Subject: Comparing a matrix (list[][]) ? References: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> Message-ID: jairodsl wrote: > How can I find the minus element greater than zero in a matrix, my > matrix is > > matrix= > [9,8,12,15], > [0,11,15,18], > [0,0,10,13], > [0,0,0,5] > > I dont want to use "min" function because each element in the matrix is > associated to (X,Y) position. What output are you expecting from your example matrix? If you are expecting it to be 5 (the smallest positive element), using "min" is the way to do it: >>> matrix = [[9, 8, 12, 15], ... [0, 11, 15, 18], ... [0, 0, 10, 13], ... [0, 0, 0, 5]] >>> min(min(x for x in row if x > 0) for row in matrix) 5 -- Roberto Bonvallet From nmm1 at cus.cam.ac.uk Fri Jan 12 14:41:52 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 12 Jan 2007 19:41:52 GMT Subject: Rational Numbers References: Message-ID: In article , "Simon Brunning" writes: |> |> > |> but there are more use |> > |> cases for Decimal than for Rational. |> > |> > That is dubious, but let's not start that one again. |> |> Decimals are good for holding financial values. There's a whole lot of |> software out there that deals with money. Sigh. I was hoping not to have that myth perpetrated again. Financial calculations need decimal FIXED-point, with a precisely specified precision. It is claimed that decimal FLOATING-point helps with providing that, but that claim is extremely dubious. I can explain the problem in as much detail as you want, but would very much rather not. Regards, Nick Maclaren. From duncan.booth at invalid.invalid Wed Jan 24 08:48:56 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jan 2007 13:48:56 GMT Subject: Thoughts on using isinstance References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> Message-ID: "abcd" wrote: > In my code I am debating whether or not to validate the types of data > being passed to my functions. For example > > def sayHello(self, name): > if not name: > rasie "name can't be null" > if not isinstance(name, str): > raise "name must be a string" > print "Hello " + name > > Is the use of isinstance a "bad" way of doing things? is it a "heavy" > operation? for example, if I use this in each function validate input > will it slow things down a lot? > > just curious how you might handle this type of situation (other than > not validating at all). > For a start, don't raise strings as exceptions: only use instances of Exception. Now consider what your first test does: it throws an error if you pass in an empty string. Perhaps you do want to check for that, in which case you will need to test for it and throw an appropriate exception. The first test also catches values such as None, 0 or []. Do you really want to throw a different exception for sayHello(0) and sayHello(1)? It seems a bit pointless, so the first test should just check against an empty string and not against other false objects which would get caught by the second test. Now for the second test. It would probably be useful to say in the exception which type was involved, not just that it wasn't a string. An appropriate exception for these would be something like: TypeError: cannot concatenate 'str' and 'int' objects since that tells you both the types and the operation that failed. Delete that second test altogether and you'll get an appropriate exception instead of a string which hides all the information. A good rule is if you want to hide exception information from the user do it when displaying the exception not when raising it. That way you can get at all the exception information available by changing one place in the code instead of having to do it everywhere. So your modified function should look like: def sayHello(name): if name=="": raise ValueError("name can't be blank") print "Hello "+name (this is slightly different than your original in a few other ways: it will accept unicode strings so long as they can be encoded in ascii, and its a function as there isn't much point having a method which doesn't use self.) From smusnmrNOSPAM at yahoo.com Sat Jan 20 12:37:49 2007 From: smusnmrNOSPAM at yahoo.com (Siggi) Date: Sat, 20 Jan 2007 18:37:49 +0100 Subject: Code reformater? References: Message-ID: "Vincent Delporte" wrote: > Hello > > When I copy/paste Python code from the web, every so often, > the TABs are wrong, which means that the code won't work and I have to > manually reformat the code. > > Is there a code reformater that can parse the code to make it right? > > Thanks. Maybe my thread "help: code formatter, 08/01/2007 helps a little? Here are some of the answers: * Why don't you just write one? :) Seriously: Try. * Tools\scripts\reindent.py in your Python distribution. * Why, yes, there is: http://lacusveris.com/PythonTidy/PythonTidy.python * tabnanny ? siggi From Roland.Puntaier at br-automation.com Fri Jan 19 08:50:19 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Fri, 19 Jan 2007 14:50:19 +0100 Subject: how to mimik a main() function to start a program with entry point? In-Reply-To: Message-ID: Hi, >From a python module you could use subprocess and start the exe. Normally one must leave it to the OS to load a binary module, because there are certain things done during loading. Nevertheless the location of the entry point is coded in the binary file format (e.g. PE for windows or ELF for Linux) Whether it is possible from python to make an import of a python module in a python package gone through py2exe, I cannot answer. But I think you mean how to tell py2exe, where the entry point is. Read: http://www.py2exe.org/index.cgi/Tutorial Roland python-list-bounces+roland.puntaier=br-automation.com at python.org schrieb am 19.01.2007 14:30:33: > hello all. > I have one simple query and may be that's to stupid to answer but I am > not finding the answer any ways. > I have a set of modules in my package and out if which one is my > actual starting point to my entire program. say for example I have an > entire database application ready and I want a main (as in java or c) > to initiate the program and may be bring up a login screen and then > pass the control on to the main window. > if I am giving raw source code that is easy because I will tell user > to run the command ./xyz.py which has that function. > but if I freze it into an executable with py2exe for example , how do > I solve this problem? > thanks. > Krishnakant. > -- > http://mail.python.org/mailman/listinfo/python-list > From gherron at islandtraining.com Wed Jan 31 16:45:55 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 31 Jan 2007 13:45:55 -0800 Subject: win32com.client In-Reply-To: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> Message-ID: <45C10E13.8000406@islandtraining.com> vithi wrote: > Hi > Any one tell me where I can get (or download) python modules win32com > or win32com.client because I have to use "Dispatch" thanks > > You want the "python for windows" extension, available from http://sourceforge.net/projects/pywin32/ Gary Herron From Jeff.Demel at JavelinDirect.com Thu Jan 11 12:44:36 2007 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Thu, 11 Jan 2007 11:44:36 -0600 Subject: Learning Python book, new edition? Message-ID: <136ED738BD4F1545B97E4AC06FF6370734C18E@DMSP-MSG-EVS01.mail.pvt> >Demel, Jeff wrote: >> Does anyone know if there's a plan in the works for a new edition of >> Learning Python? The current edition (2nd) is a few years old and >> looks like it only covers Python 2.3. Bj?rn replied: >IIRC, differences to 2.4 are in it, too. Interesting. The description I read said 2.3. That's good to know. I'd still like to know if there will be a new edition soon, covering 2.5. Anyone? >Jeff's mail server auto-appended: >> This email is intended only for the individual or entity to which it >> is addressed. Bj?rn replied: >Mails are _by_definition_ intended only for the addressee. :) According to our legal department it must be specified, apparently. They append that legal crap to every email, and it annoys me to no end. -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From omelnyk at gmail.com Mon Jan 29 00:18:34 2007 From: omelnyk at gmail.com (Olexandr Melnyk) Date: Mon, 29 Jan 2007 07:18:34 +0200 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <45bd8130$0$17928$4d3efbfe@news.sover.net> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <45bd8130$0$17928$4d3efbfe@news.sover.net> Message-ID: 2007/1/29, Leif K-Brooks : > > NoName wrote: > > from random import choice > > import string > > print ''.join([choice(string.letters+string.digits) for i in > > range(1,8)]) > > > > !!generate password once :( > > So add a while true: line. > > > who can write this smaller or without 'import'? Being very short in price of readability isn't one of the Python's main goals. -------------------------------- Olexandr Melnyk, http://omelnyk.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Sat Jan 13 02:51:04 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 12 Jan 2007 23:51:04 -0800 Subject: Boilerplate in rich comparison methods References: Message-ID: <1168674664.792869.213260@m58g2000cwm.googlegroups.com> Steven D'Aprano wrote: > I'm writing a class that implements rich comparisons, and I find myself > writing a lot of very similar code. If the calculation is short and > simple, I do something like this: > > > class Parrot: > def __eq__(self, other): > return self.plumage() == other.plumage() > def __ne__(self, other): > return self.plumage() != other.plumage() > def __lt__(self, other): > return self.plumage() < other.plumage() > def __gt__(self, other): > return self.plumage() > other.plumage() > def __le__(self, other): > return self.plumage() <= other.plumage() > def __ge__(self, other): > return self.plumage() >= other.plumage() > > If the comparison requires a lot of work, I'll do something like this: > > class Aardvark: > def __le__(self, other): > return lots_of_work(self, other) > def __gt__(self, other): > return not self <= other > # etc. > > But I can't help feeling that there is a better way. What do others do? Once upon a time I had written a metaclass to generate the boilerate, filling in the gaps. It doesn't impose any constraints on which comparisons you must implement, e.g you may implement __le__ and __eq__, or __gt__ and __ne__, etc. Season to taste. http://rafb.net/p/mpvsIQ37.nln.html George From gagsl-py at yahoo.com.ar Tue Jan 9 19:05:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Jan 2007 21:05:30 -0300 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A6D@eugsrv400.psc.psc net.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A6D@eugsrv400.psc.pscnet.com> Message-ID: <7.0.1.0.0.20070109203637.0422acb8@yahoo.com.ar> At Tuesday 9/1/2007 20:31, Carroll, Barry wrote: >I've spent about a day investigating our "too many open files" error. I >found the following: > > 1. Windows XP allows a Python 2.5 script to open 509 concurrent > files. And do you actually need so many open files simultaneously? Try to close them explicitely when you finish working on them - do not rely on GC for closing files. This has *always* been the recomended practice (except maybe, inside a short script that finishes quickly). On Python 2.5 you can use the new `with` statement. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From Roland.Puntaier at br-automation.com Thu Jan 11 03:34:40 2007 From: Roland.Puntaier at br-automation.com (Roland Puntaier) Date: Thu, 11 Jan 2007 09:34:40 +0100 Subject: Antwort: Re: SubProcess _make_inheritable In-Reply-To: <7.0.1.0.0.20070111011800.03d03258@yahoo.com.ar> Message-ID: Thanks for pointing me to the tracker. I've seen there is already an entry for this: [ 1603907 ] subprocess: error redirecting i/o from non-console process Roland Gabriel Genellina schrieb am 11.01.2007 05:24:03: > At Wednesday 10/1/2007 13:10, Roland Puntaier wrote: > > >SubProcess.py needs to be patched - at least in 2.4 - to work from > >windows GUIs: > > > > def _make_inheritable(self, handle): > > """Return a duplicate of handle, which is inheritable""" > > if handle==None: handle=-1 > > return DuplicateHandle(GetCurrentProcess(), handle, > > GetCurrentProcess(), 0, 1, > > DUPLICATE_SAME_ACCESS) > > You should submit it to the tracker, not post here and hope someone > would notice... > http://sourceforge.net/tracker/?group_id=5470 > > Anyway, I don't see in which case would handle be None. > > > -- > Gabriel Genellina > Softlab SRL > > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas > > > From ask.me at mail.com Sun Jan 28 14:04:35 2007 From: ask.me at mail.com (Jammer) Date: Sun, 28 Jan 2007 14:04:35 -0500 Subject: string byte dump In-Reply-To: <874pqb9fs1.fsf@smsnet.pl> References: <9609c$45bce423$d8a87c2a$8428@NEXICOM.NET> <874pqb9fs1.fsf@smsnet.pl> Message-ID: <3ff58$45bcf3c3$d8a87c2a$18333@NEXICOM.NET> Rob Wolfe wrote: > Jammer writes: > >> Does anyone that knows python want to write me a byte dump for strings? :-) >> >> I am trying to modify a plugin (that someone else wrote) that uses >> interprocess communication. >> It works on strings without special characters but it fails on other >> stings like "Bj?rk". >> >> It calls decode('utf8') but I guess the strings are not utf8 so I need >> to find out what is being input. > > Try this: > >>>> "abc".encode("hex") > '616263' > Awesome, thanks. From scolnik at fibertel.com.ar Fri Jan 12 05:37:28 2007 From: scolnik at fibertel.com.ar (scolnik) Date: Fri, 12 Jan 2007 07:37:28 -0300 Subject: Integer solutions to linear equation? Message-ID: <001501c73635$a82d0dc0$0200a8c0@scolnik> http://mathworld.wolfram.com/DiophantineEquation.html You can use this web application for solving diophantine equations: http://www.math.uwaterloo.ca/~snburris/htdocs/linear.html Hugo Scolnik Imagination is more important than knowledge. -------------- next part -------------- An HTML attachment was scrubbed... URL: From will at willNOmcguganSPAM.com Mon Jan 8 11:03:55 2007 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Mon, 08 Jan 2007 16:03:55 +0000 Subject: sys.exit versus raise SystemExit Message-ID: <45a26b70$0$32019$fa0fcedb@news.zen.co.uk> Hi, Is there any difference between calling sys.exit() and raise SystemExit? Should I prefer one over the other? Regards, Will McGugan -- blog: http://www.willmcgugan.com From akhavr at kds.com.ua Tue Jan 16 05:38:48 2007 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Tue, 16 Jan 2007 12:38:48 +0200 Subject: html + javascript automations = [mechanize + ?? ] or something else? References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> Message-ID: John, "J" == John wrote: J> I have to write a spyder for a webpage that uses html + javascript. I J> had it written using mechanize but the authors of the webpage now use a J> lot of javascript. Mechanize can no longer do the job. Does anyone J> know how I could automate my spyder to understand javascript? Is there J> a way to control a browser like firefox from python itself? How about J> IE? That way, we do not have to go thru something like mechanize? Up to my knowledge, there no way to test javascript but to fire up a browser. So, you might check Selenium (http://www.openqa.org/selenium/) and its python module. -- Andrey V Khavryuchenko Software Development Company http://www.kds.com.ua/ From horpner at yahoo.com Fri Jan 26 13:03:45 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 26 Jan 2007 18:03:45 GMT Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> Message-ID: On 2007-01-26, Fabrice DELENTE wrote: > I'm trying to display french characters (? -- that's e grave -- > or ? -- agrave) in python 2.5, with the ncurses wrapper that > comes it, and I can't. My locale is set correctly > (fr_FR.iso885915), and my terminal (rxvt-unicode) is able to > display those chars. What have you tried? -- Neil Cerutti -- Posted via a free Usenet account from http://www.teranews.com From bdesth.quelquechose at free.quelquepart.fr Fri Jan 12 17:42:47 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Jan 2007 23:42:47 +0100 Subject: What is a perl hash in python In-Reply-To: References: Message-ID: <45a80882$0$22916$426a34cc@news.free.fr> Karyn Williams a ?crit : > I am new to Pyton. I am trying to modify and understand a script someone > else wrote. I am trying to make sense of the following code snippet. I know > line 7 would be best coded with regex. I first would like to understand > what was coded originally. thelistOut looks like a hash to me (I'm more > familiar with perl). It's not a hash (the Python type for hashtables is 'dict'), it's a list of 2-tuples. FWIW, the dict type can accept such a list as an argument to it's constructor - but then you loose the ordering. Also, the data structure is somewhat weird, since the second item of each tuple is always a one-element list. > Perhaps someone could translate from perl to python Do you mean "from Python to Perl" ? > for me - not in code but just in concept. > > > Here is the code. This script is reading the list thelistOut and then > removing any items in RSMlist and taking the remainder and putting them in > graphAddressOut with the formatting. > > This is a SAMPLE of what is in the lists referenced below in the loop: > > > thelistOut = [(632, > ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_9.log']), (145, > ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_13.log']), (0, > ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_5.log'])] > > RSMList = ['172.16.0.1_1', '172.16.0.1_2', '172.16.0.1_3', '172.16.0.1_4', > '172.16.0.1_5'] > > > > #--------------------------Loop 1 ------------------------- > > w = 0 > while w < 45: > > fileOut = string.split(thelistOut[w][1][0],".log") > fileOutSplitedCommon = string.split(fileOut[0], "main/") > fileOut2D = string.split(fileOutSplitedCommon[1], "/") > fileOut = string.split(fileOut[0],"data-dist") > > if fileOut2D[1] in RSMList: > w = w + 1 > continue > graphAddressOut = tag1 + logUrl + fileOut[1] + extention1 + tag2 + > "SWITCH: " + string.swapcase(fileOut2D[0]) + "  & > nbsp;PORT ID: " + fileOut2D[1] + "
" + imgTitleTag + imgTag1 + > logUrl + fileOut[1] + extention2 + imgTag2 + tag3 + tag5 > outputOut.append(graphAddressOut) > strOut = strOut + graphAddressOut > > w = w + 1 > > #--------------------------Loop 1 ------------------------- > Yuck. This code stinks. Whoever wrote this ought to be shot down. I refuse to try&clean this mess unless I get payed (and well payed). From george.sakkis at gmail.com Sun Jan 7 22:57:35 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 7 Jan 2007 19:57:35 -0800 Subject: Recommendations (or best practices) to define functions (or methods) References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> Message-ID: <1168228655.184248.113310@v33g2000cwv.googlegroups.com> vizcayno wrote: > Hello: > Need your help in the "correct" definition of the next function. If > necessary, I would like to know about a web site or documentation that > tells me about best practices in defining functions, especially for > those that consider the error exceptions management. > I have the next alternatives but I think there are better: > > Alternative 1: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > return e > return 1 > > Seems a good solution but the function is not returning an uniform > type, should the code that receives the function result decides the > error display according of datatype? If I do this in C# I think I will > have problems. > > > Alternative 2: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > return 0, e # or return (0,e.message) > return 1, "ok" # or return (1, "ok") > Sounds good, but seems forced. When doing return 1, "ok" I am doing > redundancy and I have problems with the type (e is exception type and > "ok" is string). > > > Alternative 3: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > print "ERROR:", e > return 0 > return 1 > > It solves the problem of alternative 1 and 2, but the print keyword > would have problems if the function is called from an WEB or GUI > application and, because there are plans to convert print into a > function in py3k. > > > Alternative 4: > ============= > def ExecuteSQL(cmdSQL, cursor): > try: > cursor.execute(cmdSQL) > except Exception, e: > print >> logerr, e.message > return 0 > return 1 > > Seems a good solution but I should always be persuaded to have an open > global file (logerr) when invoking this function; otherwise code will > generate another error. The function is not totally independent.I think > I would be in the same situation when using the "logging" battery. > > Thanks for your attention. > > Regards, My vote goes to None Of The Above. In neither alternative you actually do anything useful with the exception other than reporting it in some ad-hoc way. If that's all you can and/or want to do with it (i.e. no error recovery of some sort), the typical thing to do is nothing; just let it propagate up the call stack until the appropriate level. This might be the console, a GUI, a logfile, an automatically sent email or any combination of these or more. If it's a programmer's error (aka bug), it should propagate all the way up and end in printing the stack trace. The bottom line is, it's simply not this function's (ExecuteSQL) job to deal with the error, so it shouldn't. Most important, returning an error or status code is rarely (if ever) desirable or necessary in Python; that's what exceptions are for. George From bjourne at gmail.com Fri Jan 19 04:38:33 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 19 Jan 2007 10:38:33 +0100 Subject: Is it possible to fasten the import of cgi? In-Reply-To: <45af6f47$0$322$e4fe514c@news.xs4all.nl> References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> Message-ID: <740c3aec0701190138m41b29099tacd2bd7d5f386ea9@mail.gmail.com> On 1/18/07, Cecil Westerhof wrote: > I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I > can not time the time used to import time, but os and sys do not take more > as a millisecond. My script itself takes 3 or 4 milliseconds. But importing > cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is > there a way to make this more fast? The import off cgi makes the script at > least 20 times as slow. Something like mod-python is not a possibility. I > could use it on my test machine, but not at the osting provider. Maybe python-launcher-daemon can help you? http://blogs.gnome.org/view/johan/2007/01/18/0 But if you can not use mod_python then you probably can not use any long running processes either. -- mvh Bj?rn From kylotan at gmail.com Fri Jan 12 05:05:13 2007 From: kylotan at gmail.com (Ben Sizer) Date: 12 Jan 2007 02:05:13 -0800 Subject: How to modify object attribute by python C API In-Reply-To: <1168551428.114028.278940@77g2000hsv.googlegroups.com> References: <1168551428.114028.278940@77g2000hsv.googlegroups.com> Message-ID: <1168596313.853805.148790@v45g2000cwv.googlegroups.com> Huayang Xia wrote: > PyObject* py_obj_attr1 = PyObject_GetAttrString(obj, "attr1"); > PyObject_SetAttrString(py_obj_attr1, "attr2", > PyString_FromString("a")); > Py_DECREF(py_obj_attr1); > > The object py_obj_attr1 is said to be a "New reference". It's > confusing, does it refer to the same object as "obj.attr1" in python's > term? Yes, it refers to the same object. Each object can have many references, and is deleted when all the references are gone. The new reference in this case means that Python has taken note that there's a new use of that object - your C code. It means it won't delete that object, even if no more Python code refers to it, because it knows your C code holds a reference to it. Therefore, when your C code no longer needs to access the object, you call Py_DECREF. -- Ben Sizer From weekender_ny at yahoo.com Sun Jan 21 23:47:59 2007 From: weekender_ny at yahoo.com (John) Date: 21 Jan 2007 20:47:59 -0800 Subject: html + javascript automations = [mechanize + ?? ] or something else? In-Reply-To: References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> Message-ID: <1169441279.556814.16770@38g2000cwa.googlegroups.com> My python2.5 installation on windows did not come with "win32com". How do I install/get this module for windows? Thanks, --j Duncan Booth wrote: > "John" wrote: > > > Is there a way > > to control a browser like firefox from python itself? How about IE? > > IE is easy enough to control and you have full access to the DOM: > > >>> import win32com > >>> win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB- > 0000C05BAE0B}', 0, 1, 1) > 'C:\Python25\lib\site-packages\win32com\gen_py\EAB22AC0-30C1-11CF-A7EB- > 0000C05BAE0Bx0x1x1.py'> > >>> IE = win32com.client.DispatchEx('InternetExplorer.Application.1') > >>> dir(IE) > ['CLSID', 'ClientToWindow', 'ExecWB', 'GetProperty', 'GoBack', 'GoForward', > 'GoHome', 'GoSearch', 'Navigate', 'Navigate2', 'PutProperty', > 'QueryStatusWB', 'Quit', 'Refresh', 'Refresh2', 'ShowBrowserBar', 'Stop', > '_ApplyTypes_', '__call__', '__cmp__', '__doc__', '__getattr__', > '__init__', '__int__', '__module__', '__repr__', '__setattr__', '__str__', > '__unicode__', '_get_good_object_', '_get_good_single_object_', '_oleobj_', > '_prop_map_get_', '_prop_map_put_', 'coclass_clsid'] > >>> IE.Visible=True > >>> IE.Navigate("http://plone.org") > >>> while IE.Busy: pass > > >>> print IE.Document.getElementById("portlet-news").innerHTML >
href="feed://plone.org/news/newslisting/RSS">RSS href="http://plone.org/news">News
> > ... and so on ... > > > See > http://msdn.microsoft.com/workshop/browser/webbrowser/reference/objects/int > ernetexplorer.asp > for the documentation. From basti.wiesner at gmx.net Sun Jan 7 13:14:41 2007 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sun, 07 Jan 2007 19:14:41 +0100 Subject: AES256 in PyCrypto References: <1168134542.337448.261510@s34g2000cwa.googlegroups.com> <1168184060.548851.11540@i15g2000cwa.googlegroups.com> Message-ID: [ mirandacascade at yahoo.com ] > > Marc 'BlackJack' Rintsch wrote: > >> `a` must be of length 32 for AES256. And the length of `plainText` >> must be a multiple of 16 because it's a block cypher algorithm. > > Thank you. I have some follow up questions and 1 tangential question. > > Follow up question: > Would it be correct to infer that: > a) the AES.pyd extension module (plus whatever additional files > within the PyCrypto package that it uses) has the capability to > perform AES256 encryption? > b) the AES256 encryption happens based on the characteristics of the > input to the new() method...if the first argument has a length of 32, > the result will be AES256-style encryption? Since you are apparently unable to read to docstrings of this module, I will give you a short hint: yes, pycrypto supports AES with 256 bit keys. > c) will AES256-style encryption also happen if the first argument to > the new() method has a length that is a multiple of 32, e.g. 64? Why didn't you try this? It would have answered your question: [12]--> AES.new(os.urandom(64), AES.MODE_CBC, os.urandom(16)) --------------------------------------------------------------------------- exceptions.ValueError Traceback (most recent call last) /home/lunar/ ValueError: AES key must be either 16, 24, or 32 bytes long > Tangential question: > Is there functionality available (either in the PyCrypto package or > some other package) that generates an initialization vector that can > be used as input to the new() method? What prompts this question is > that the original posting referenced a snippet of C# code; some other > related snippets I saw seemed to suggest that: > a) a RijndaelManaged() class gets instantiated > b) that class has a GenerateIV() method which appears to populate > someting in a IV property > c) the application that was employing the AES256 encryption made use > of the left-most 16 characters of the IV property > So, I was curious whether something analgous exists in the Python > world. os.urandom will be your friend... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From steve at REMOVE.THIS.cybersource.com.au Sat Jan 27 00:42:11 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 27 Jan 2007 16:42:11 +1100 Subject: instancemethod References: <45b51298$0$8289$426a74cc@news.free.fr> <45ba2b72$0$3007$426a34cc@news.free.fr> Message-ID: On Sat, 27 Jan 2007 01:03:50 -0300, Gabriel Genellina wrote: > "Steven D'Aprano" escribi? en el > mensaje > news:pan.2007.01.27.00.07.59.387012 at REMOVE.THIS.cybersource.com.au... > >> On Fri, 26 Jan 2007 17:25:37 +0100, Bruno Desthuilliers wrote: >>>> def __del__(self): >>>> try: >>>> self.close() >>>> finally: >>>> pass >>>> except: >>>> pass >>> >>> The finally clause is useless here. >> >> In principle, closing a file could raise an exception. I've never seen it >> happen, but it could. From the Linux man pages: [...] >> I assume that the same will apply in Python. > > Note that he said that the *finally* clause were useless (and I'd say so, > too), not the *except* clause. Doh! Yes, he's right. Worse, the code as show can't possibly work: the finally clause must come AFTER the except clause. >>> try: ... pass ... finally: ... pass ... except: File "", line 5 except: ^ SyntaxError: invalid syntax -- Steven. From http Sat Jan 13 16:53:04 2007 From: http (Paul Rubin) Date: 13 Jan 2007 13:53:04 -0800 Subject: Threaded for loop References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> Message-ID: <7xr6ty8ugv.fsf@ruckus.brouhaha.com> "John" writes: > I want to do something like this: > > for i = 1 in range(0,N): > for j = 1 in range(0,N): > D[i][j] = calculate(i,j) > > I would like to now do this using a fixed number of threads, say 10 > threads. What is the easiest way to do the "parfor" in python? It won't help in terms of actual parallelism. Python only lets one thread run at a time, even on a multi-cpu computer. From mike.klaas at gmail.com Thu Jan 4 14:24:19 2007 From: mike.klaas at gmail.com (Klaas) Date: 4 Jan 2007 11:24:19 -0800 Subject: Set type? In-Reply-To: References: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> Message-ID: <1167938659.079359.267300@11g2000cwr.googlegroups.com> Fredrik Lundh wrote: > > if type(var) is types.SetType: > > blah > > > > but that is not available in types module. I am using 2.4 > > # set or subclass of set > if isinstance(var, set): > ... or if isinstance(var, (set, frozenset)): ... -Mike From pgarrone at acay.com.au Sat Jan 20 01:46:53 2007 From: pgarrone at acay.com.au (pgarrone at acay.com.au) Date: 19 Jan 2007 22:46:53 -0800 Subject: Py 2.5 on Language Shootout References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> Message-ID: <1169275613.093797.67320@v45g2000cwv.googlegroups.com> Isaac Gouy wrote: > pgarrone at acay.com.au wrote: > > Alioth is a great site for selecting the language in which to implement > > primitives. Usually it's C. > > And for selecting a language for which you might need to implement > primitives in C :-) Well if you like C so much, just do it in C. ":-)" > > > > > Two of the alioth benchmarks, Partial-sums and Spectral-norm, could be > > done using Numarray, or would be done with Numarray if most of the > > program was in Python and there was a need to implement a similar > > numerical procedure. The speed would be up near the compiled language > > benchmarks. However the specific wording of these benchmarks prohibits > > this approach. Spectral-norm must pretend the dataset is infinite, and > > Partial-sums has to be implemented in a simple dumb loop. > > And we wouldn't use a na?ve recursive algorithm to find fibonnaci > numbers ... unless we were interested in recursion for its own sake. > > Maybe the author of spectral-norm was interested in function calls. > Maybe the author of partial-sums was interested in simple dumb loops > and simple dumb Math. I am not disputing this. I think you take my point though. > > > > Looking over the benchmarks, one gains the impression that Python is a > > slow language. > > What does that even mean - a slow language? > The alioth benchmarks provide a set of numbers by which languages may be compared. > > > My first serious Python programming exercise involved converting a 900 > > line Bash Shell program to a 500 line Python program, with a speedup > > factor of 17. Using Python allowed an OO structure and advanced > > containers, meaning the program was more maintainable and portable, > > which were the main aims of the exercise. The speedup was a surprising > > and welcome side benefit. I think it was mosly because the Python > > byte-code interpreter is probably an order of magnitude faster than > > Bash's direct interpretation, and because in Python system calls to > > recurse directories and create symbolic links were not forked to > > separate processes. In fact I would guess that the overall speed of the > > Python program would be little less than a C program, given that most > > of the time would be spent in system calls. > > /I would guess/ I don't have the time, or interest, to recode it in C to find out. In reality the choice would be C++ because of OO and STL. Perhaps traversing and linking a tree containing about 1000 files would not take a full second. I might be wrong. All i know is, its a lot faster than Bash. > > > Its almost possible to make a large Python program arbitrarily fast by > > profiling it and implementing slow bits as primitives. Size is probably > > of greater concern. > > We could read that simply as - /it's not possible/ to make a large > Python program arbitrarily fast. Is that what you meant? No. I meant that if my Python program is too big in terms of its execution memory requirements, then that would be a difficult issue to deal with. Rather than optimizing execution hotspots, I might have to use another language. Cheers, P.S. Alioth is a great site. From bignose+hates-spam at benfinney.id.au Mon Jan 15 22:48:40 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 Jan 2007 14:48:40 +1100 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <874pqr7ht3.fsf@benfinney.id.au> "Steven D'Aprano" writes: > On Tue, 16 Jan 2007 08:54:09 +1100, Ben Finney wrote: > > def __add__(self, other): > > result = perform_addition(self, other) > > return result > > But that could just as easily be written as: > > def __add__(self, other): > return perform_addition(self, other) Yes. I was merely suggesting that there would probably be more steps involved than "return some_simple_expression", without actually detailing those steps. -- \ "Having sex with Rachel is like going to a concert. She yells a | `\ lot, and throws frisbees around the room; and when she wants | _o__) more, she lights a match." -- Steven Wright | Ben Finney From smusnmrNOSPAM at yahoo.com Mon Jan 15 09:00:09 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Mon, 15 Jan 2007 15:00:09 +0100 Subject: python and MOV or MPEG References: <510uf3F1i9oo6U1@mid.uni-berlin.de> <511ehiF1i1c86U1@mid.individual.net> Message-ID: "Bjoern Schliessmann" wrote: > 1.3? I've found both for 2.4, and in one site's forum some guy > offers windows binaries for 2.5. The links, please! Thank you, siggi "Bjoern Schliessmann" schrieb im Newsbeitrag news:511ehiF1i1c86U1 at mid.individual.net... > siggi wrote: > >> Thanks, Diez. I forgot to mention that I am learning Python with >> python 2.5 on WinXP. And both pymedia and pygame require somewhat >> older versions of python, 1.3 and 2.4, respectively. > > 1.3? I've found both for 2.4, and in one site's forum some guy > offers windows binaries for 2.5. > > Regards, > > > Bj?rn > > -- > BOFH excuse #303: > > fractal radiation jamming the backbone > From jeremit0 at gmail.com Thu Jan 4 21:52:03 2007 From: jeremit0 at gmail.com (jeremito) Date: 4 Jan 2007 18:52:03 -0800 Subject: What is proper way to require a method to be overridden? Message-ID: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> I am writing a class that is intended to be subclassed. What is the proper way to indicate that a sub class must override a method? Thanks, Jeremy From gblais at cox.net Sun Jan 7 17:43:11 2007 From: gblais at cox.net (gblais at cox.net) Date: Sun, 7 Jan 2007 22:43:11 GMT Subject: Working with Excel inside Python References: <1168205727.130771.257030@51g2000cwl.googlegroups.com> Message-ID: Or, you might want to look at two packages: xlrd pyExcelerator The first can "read" .xls files, and the second can write them. I've had great results with both. Gerry From wolf_tracks at invalid.com Sun Jan 21 15:34:02 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 21 Jan 2007 20:34:02 GMT Subject: Beginners Tutorial in PDF Format? Message-ID: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net> I'd like to print a tutorial in one fell swoop, but it seems most on the various sites are page by page embedded descriptions in the page. Any available as a pdf? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Two laws Newton and Einstein didn't discover: 1. Time is money. 2. Matter will be damaged in direct proportion to its value. -- Web Page: From mensanator at aol.com Tue Jan 16 18:47:32 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 16 Jan 2007 15:47:32 -0800 Subject: I wrote a C++ code generator in Python, would anyone please help me to review the code? :) In-Reply-To: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> References: <1168930067.970099.164620@s34g2000cwa.googlegroups.com> Message-ID: <1168991250.445208.159020@v45g2000cwv.googlegroups.com> Kevin Wan wrote: > fgen is a free command line tool that facilitates cross platform c++ > development, including header generation, cpp file generation, makefile > generation, unit test framework generation, etc. > > http://sf.net/projects/fgen > > I'm not very familiar with Python. Any feedback are appreciated! No documentation? Am I supposed to reverse engineer all the source files to figure out how I'm supposed to use it? > Or > anyone like to develop it with me? > > Thanks. From mirandacascade at yahoo.com Sun Jan 14 22:50:06 2007 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 14 Jan 2007 19:50:06 -0800 Subject: on which site or Usenet group should this question be posted? Message-ID: <1168833006.078282.46430@11g2000cwr.googlegroups.com> Operating system: Win XP Version of Python: 2.4 I recognize that this question is not about Python...it has only a tangential Python connection. I'm using a Python package to run a process; that process is issuing an error, and I'm hoping that someone on this site can point me to the site that has the appropriate expertise. Situation is this: 1) using win32com.client.Dispatch to work with the MSXML2.XMLHTTP COM object 2) I use the open() method of the COM object and specify a "POST", then I use the send() method of the COM object 3) when the url is an http url, able to send and then check the responseText property without problems 4) when the url is an https url, the open() method works, but when the send() method is invoked, it raises an exception with the error message: "the download of the specified resource has failed" 5) when I use Google with searches such as "XMLHTTP", "https", "download of the specified resource", I see that other people are experiencing the issue, but I didn't see any solutions, nor did I see whether there was a site (perhaps a Usenet group) on which it would make sense to post this issue Eventually, I want to learn whether the XMLHTTP COM object can work with https url's, but what I'm hoping to learn from this post is advice as to which site I should post this question so that it might be read by folks with the appropriate subject-matter expertise. Thank you. From dingbat at codesmiths.com Fri Jan 5 10:34:25 2007 From: dingbat at codesmiths.com (Andy Dingley) Date: 5 Jan 2007 07:34:25 -0800 Subject: program deployment In-Reply-To: <1168010377.179056.220500@s80g2000cwa.googlegroups.com> References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> <1168010377.179056.220500@s80g2000cwa.googlegroups.com> Message-ID: <1168011265.016893.207830@42g2000cwt.googlegroups.com> king kikapu wrote: > > > Are they embarassed by their code? > > hehehe...no, just worried about stealing their ideas... Ever heard of "Open Source" ? I do better by letting other people steal my ideas (and stealing theirs too) than I'd ever do by keeping things secret. From steve at holdenweb.com Wed Jan 24 09:21:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Jan 2007 14:21:16 +0000 Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A96@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A96@eugsrv400.psc.pscnet.com> Message-ID: Carroll, Barry wrote: > Greetings: > > Personally, I don't think top-posting is the most annoying newsgroup > habit. I think it's making a big fuss about minor inconveniences. > > One of the nicest things about being human is the amazing flexibility of > our brains. For example, if a block of text isn't arranged in the order > we're used to, we can easily rearrange it mentally and read it anyway. > Oriental and Arabic peoples, for example, do this each time they read > something written in English. It's EASY, once you get used to it! > That's as may be. but just last week I was presented with a printed five-page message where all contributors to the thread had top-posted. There were four and five levels of quoting in some places, line wrapping was all over the place as a result, and it was difficult to even make out which bits were quoted at the same level. If everyone had refrained from top-posting then it would have been much easier to read the ensuing (linear) conversation. In short: top-posting doesn't hurt in simple cases, but it's a real hurdle to understanding in the long-running threads typically generated on mailing lists and newsgroups. There are many people who find it natural to consider their own convenience over that of hundreds or thousands of others, so by all means continue with your top-posting habit if it's too much trouble to avoid it. It's unlikely to get you killed, but it *does* say something about you, and people will draw conclusions, possibly incorrect ones, about you as a result. As a final riposte, our personal opinions aren't really much of a guide to the wishes of the masses, whereas the reaction of the masses (as in: "Why do you top-post?") often is. How often do you see someone ask "please start top-posting"? I've had precisely one such request in many many years of email and Internet usage. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From http Thu Jan 25 07:29:35 2007 From: http (Paul Rubin) Date: 25 Jan 2007 04:29:35 -0800 Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> <1169725374.504546.153890@v33g2000cwv.googlegroups.com> Message-ID: <7xirevuw5s.fsf@ruckus.brouhaha.com> "gangesmaster" writes: > what i see as a bug is this code not working as expected: > > >>> def make_foos(names): > ... funcs = [] > ... for n in names: > ... def foo(): > ... print "my name is", n > ... funcs.append(foo) > ... return funcs But it does work as expected, if your expectations are based on what closures actually do. > i have to create yet another closure, make_foo, so that the name > is correctly bound to the object, rather than the frame's slot: The Python idiom is: def make_foos(names): funcs = [] for n in names: def foo(n=n): print "my name is", n funcs.append(foo) return funcs The n=n in the "def foo" creates the internal binding that you need. From free.condiments at gmail.com Sun Jan 21 16:00:13 2007 From: free.condiments at gmail.com (Sam) Date: Sun, 21 Jan 2007 21:00:13 +0000 Subject: Accessing class variables in staticmethods. In-Reply-To: <1169412557.737589.105120@a75g2000cwd.googlegroups.com> References: <1169412557.737589.105120@a75g2000cwd.googlegroups.com> Message-ID: On 21 Jan 2007 12:49:17 -0800, Ramashish Baranwal wrote: > class Base: > staticvar = 'Base' > > @staticmethod > def printname(): > # this doesn't work > # print staticvar > # this does work but derived classes wouldn't behave as I want > print Base.staticvar > > class Derived(Base): > staticvar = 'Derived' > > Base.printname() # should print 'Base' > Derived.printname() # should print 'Derived' > > Any idea on how to go about this? Also from a staticmethod how can I > find out other attributes of the class (not objects)? Do static methods > get some classinfo via some implicit argument(s)? No, staticmethods get told nothing about the class they're being defined in. What you want is a classmethod, which gets passed the class to work with. Using classmethods, your code becomes: #untested, bear in mind class Base: staticvar = 'Base' @classmethod def printname(cls): print cls.staticvar class Derived(Base): staticvar = 'Derived' Base.printname() #prints 'Base' Derived.printname() #prints 'Derived' Incidentally, you can also use cls.__name__ for this purpose, but I guess that your actual motivation for this is more complicated than class names. From exarkun at divmod.com Sun Jan 28 16:08:13 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 28 Jan 2007 16:08:13 -0500 Subject: Trouble with max() and __cmp__() In-Reply-To: <1170017167.165222.325800@a34g2000cwb.googlegroups.com> Message-ID: <20070128210813.25807.693766372.divmod.quotient.1623@ohm> On 28 Jan 2007 12:46:07 -0800, Thomas Nelson wrote: >My code: > >class Policy(list): > def __cmp__(self,other): > return cmp(self.fitness,other.fitness) > >j = Policy() >j.fitness = 3 >k = Policy() >k.fitness = 1 >l = Policy() >l.fitness = 5 >print max([j,k,l]).fitness > >prints 3, when I was expecting it to print 5. What have I done wrong? > max() uses >, apparently. Which means the builtin list.__gt__ is consulted, not your __cmp__ implementation: >>> class x(list): ... def __cmp__(self, other): ... print 'yes' ... return 1 ... >>> max([x(), x(), x()]) [] >>> class y(list): ... def __lt__(self, other): ... print 'yes' ... return cmp(id(self), id(other)) ... >>> max([y(), y(), y()]) [] >>> class z(list): ... def __le__(self, other): ... print 'yes' ... return cmp(id(self), id(other)) ... >>> max([z(), z(), z()]) [] >>> class w(list): ... def __ge__(self, other): ... print 'yes' ... return cmp(id(self), id(other)) ... >>> max([w(), w(), w()]) [] >>> class v(list): ... def __gt__(self, other): ... print 'yes' ... return cmp(id(self), id(other)) ... >>> max([v(), v(), v()]) yes yes [] Note that this is different from the operation used by list.sort(): >>> [v(), v(), v()].sort() >>> [w(), w(), w()].sort() >>> [x(), x(), x()].sort() >>> [z(), z(), z()].sort() >>> [y(), y(), y()].sort() yes yes >>> So, if you implement __gt__, max will work right. If you also implement __le__, sorting will work right. Your best bet is probably to implement all of the rich comparison methods. Jean-Paul From mnations at gmail.com Mon Jan 8 16:56:28 2007 From: mnations at gmail.com (Mudcat) Date: 8 Jan 2007 13:56:28 -0800 Subject: Getting started with Crystal Reports...little help in the far court. Message-ID: <1168293388.349793.256790@s80g2000cwa.googlegroups.com> I am not that familiar with Crystal Reports, but having read some other posts I know that the way to integrate the API with Python is through the COM interface provide by win32all. However, I have been unable to find any other information on how to get started. I've used the COM interface before in integrating Excel and a couple of other things. So I am familiar with how that works. But there are at least 40 options dealing with Crystal and Business Objects. I have no idea which makepy file to create or which one provides the functionality I need. I'm not looking to do much. All I'm really trying to do is provide one application where a list of crystal reports can be selected and ran in series. Right now we have a lot of reports that all have to be run manually (takes a while). So I think all I need api access to is server selection, parameter selection, and output formats. Any pointers in the right direction would be helpful. Thanks, Marc From bluejump at mac.com Sat Jan 13 12:35:39 2007 From: bluejump at mac.com (Kajsa Anka) Date: Sat, 13 Jan 2007 18:35:39 +0100 Subject: HTML Calendar code Message-ID: <0001HW.C1CED6FB000CC50DF0407648@News.Individual.DE> Before I re-invent something I would like to ask if there exists some code that can be used for create the HTML code for a calendar which I then can include on a web page. The module in the standard library can create a calendar but I would like display my schedule. My idea is that it would read a simple text file and then create a weekly calendar view (and/or a monthly) with my schedule. Does some the code for this exist? (the ones I found all created calendars but doesn't seem to include any schedule) jem From nmm1 at cus.cam.ac.uk Fri Jan 19 11:19:08 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 19 Jan 2007 16:19:08 GMT Subject: when format strings attack References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> Message-ID: In article , "Gabriel Genellina" writes: |> escribi? en el mensaje |> news:1169207467.989977.162940 at q2g2000cwa.googlegroups.com... |> |> > http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN |> > |> > I saw a warning from homeland security about this. I only comment on |> > the because I am trying to use os.system('command1 arg') and it doesn't |> > work but I do see examples with % that is borrowed from the c language. |> > Seems like if I can write a batch file that does something the same |> > behavior should happen in the os module.. |> |> Pure Python programs are not affected, but a review of the C implementation |> should be made to see if any (variant of) printf is used without a proper |> format. Anyway I doubt you could find something, because the vulnerability |> is so well known for ages. Not really. There are LOTS of vulnerabilities that have been known for ages and are still legion. The reason that this is unlikely is that it is both easy to spot and trivial to fix. Regards, Nick Maclaren. From Who at yakindasorta Tue Jan 30 23:23:00 2007 From: Who at yakindasorta (Tommy) Date: Tue, 30 Jan 2007 20:23:00 -0800 Subject: Bush, clean up your shit and farts before you leave - Hillary Clinton References: <1170116661.078191.238840@k78g2000cwa.googlegroups.com> Message-ID: I' m not a Bush or Hillary fan, but this strikes me as pretty funny. Hillary: I'm not for any fixed date, as long as it's before the 2008 election. Dammit, George, I don't want Iraq to be a campaign issue! wrote in message news:1170116661.078191.238840 at k78g2000cwa.googlegroups.com... > But Bush was merely an ego front for the neocons ... He spoke their > speeches, signed their recommendations, and ordered their wars, go and > listen to Benjamin Friedman's excellent video in his very passionate > voice ... > > http://video.google.com/videoplay?docid=3552214685532803163&q > > > ==================================================== > http://www.nydailynews.com/front/story/492891p-415149c.html > > Hil to W: Clean up your own mess > Leaving it to next Prez is irresponsible, she tells Iowa crowd > > BY MICHAEL McAULIFF > DAILY NEWS WASHINGTON BUREAU > > Hillary Clinton addresses crowd at town-hall style meeting yesterday > in Davenport, Iowa. Her two-day swing through Iowa, where she hit hard > on issues like Iraq war and health care, was first trip to state with > earliest caucus since announcing presidential candidacy. > DAVENPORT, Iowa - President Bush should clean up the mess he made in > Iraq and bring American troops home before he leaves the White House > in 2009, Sen. Hillary Clinton said yesterday. > > Clinton fired her rhetoric-raising broadside at Bush and the Iraq war > on her first swing through Iowa as a presidential hopeful, painting > herself as tough, warm and presidential all at the same time. > > "The President has said this is going to be left to his successor," > she said at a rally in Davenport. "I think it's the height of > irresponsibility, and I really resent it. > > "This was his decision to go to war; he went with an ill-conceived > plan, an incompetently executed strategy, and we should expect him to > extricate our country from this before he leaves office," the former > First Lady said. > > White House spokesman Rob Saliterman criticized Clinton (D-N.Y.) for > "a partisan attack that sends the wrong message to our troops and the > Iraqi people." > > One questioner challenged Clinton to explain her vote in late 2002 to > authorize the war. She said Congress was "misled" at the time by the > President. > > "He took the authority that I and others gave him, and he misused it," > she said. "And I regret that deeply. And if we had known then what we > know now, there never would have been a vote, and I never would have > voted to give this President that authority." > > Dawn Trettin, 33, and her son Ramon Briones, 18, who has joined the > Army, said they liked what they heard from Clinton. Trettin, though, > teared up when someone in the crowd told her son not to go to Iraq. > > "I don't want to just pull out and leave it in chaos," she said, > though she was waiting to make up her mind on whom to vote for next > year. > > Her son, who said he liked Clinton's depth, was ready to commit after > hearing her pitch. "I liked her," he said. "I would vote for her." > > Clinton is leading her Democratic rivals in national polls, but she is > not the front-runner in Iowa. If Iowa's first-in-the-nation caucus was > held now, she would lose to 2004 vice presidential nominee John > Edwards. She also trails former Iowa Gov. Tom Vilsack and Illinois > Sen. Barack Obama in state polls. > > She completed a two-day swing through the state last night in a bid to > close the gap and tried to erase the perception among many Iowans that > she can't win, talking to them in small groups in living rooms and by > the thousands in large halls. > > The reception was strong, and Camp Clinton liked what it saw. > > "We are thrilled with the weekend," said Clinton spokesman Howard > Wolfson. > > Clinton also focused on middle-class issues like making college more > affordable and obtaining universal health care coverage. > > She promised to try to at least get universal coverage for kids during > her next two years in the Senate. > > Today, she's picking up the war theme theme again in Texas, attending > the dedication of Brooke Army Medical Center's $50 million Center for > the Intrepid. The 60,000-square-foot physical rehabilitation center is > for veterans injured in the war. > > Originally published on January 28, 2007 > From codecraig at gmail.com Wed Jan 31 07:44:21 2007 From: codecraig at gmail.com (abcd) Date: 31 Jan 2007 04:44:21 -0800 Subject: marshal.loads ValueError Message-ID: <1170247461.799295.227550@a75g2000cwd.googlegroups.com> I have the following code which is sent over the wire as a string... from time import time class Foo: def go(self): print "Time:", time() I get this code and store it as, "data" data = receivePythonSource() Then I try... exec marshal.loads(data) in my_module.__dict__ However I get an error saying: ValueError: invalid literal for __float__: om time import time class Foo: def go(self): ....almost like when I try to marshal and exec it misses the first two characters, "fr" ...any ideas? From bill.tydeman at gmail.com Mon Jan 15 18:02:43 2007 From: bill.tydeman at gmail.com (Bill Tydeman) Date: Mon, 15 Jan 2007 18:02:43 -0500 Subject: download win32file In-Reply-To: <200701151805.19483.inq1ltd@verizon.net> References: <_mTqh.49191$kn7.39312@newsfe23.lga> <200701151805.19483.inq1ltd@verizon.net> Message-ID: <501e09e0701151502x352e4b42hb353a44d0319fd54@mail.gmail.com> > > > ?? Do I have to download pywin32 to get win32ui, > or win32file, or win32api Yes -- There is no reason for any individual to have a computer in his home. Ken Olsen, President, Digital Equipment, 1977 US computer engineer & industrialist (1926 - ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at boddie.org.uk Sat Jan 20 12:05:04 2007 From: david at boddie.org.uk (David Boddie) Date: Sat, 20 Jan 2007 18:05:04 +0100 Subject: The proper use of QSignalMapper References: <1169045073.138626.60770@l53g2000cwa.googlegroups.com> <1169049100.393777.269350@v45g2000cwv.googlegroups.com> <1169085859.586698.149400@51g2000cwl.googlegroups.com> <1169135947.039984.108930@51g2000cwl.googlegroups.com> <1169305392.100624.295850@11g2000cwr.googlegroups.com> Message-ID: <86ec2$45b24bc1$54d1d767$19264@news.chello.no> On Saturday 20 January 2007 16:03, borntonetwork wrote: > David, thanks for your help. Unfortunately, all attempts of making this > solution work have failed. I would be interested to know if anyone has > used QSignalMapper successfully in a similar situation. Looking again at what you originally wrote, and looking at your solution below, I don't think it's really appropriate to use a QSignalMapper for this purpose. (That's what I understood from the signature of the deleteProductIngredient() method you had in your original code.) What you appear to want is a way of being notified about state changes to widgets that also identifies the individual widget that changed. You can do that by connecting the individual widgets to the same slot and call sender() to find out which object emitted the signal; for example: # ... ????????for?idx?in?range(1,?maxIngredients+1): ????????????wName?=?'chkProductIngredientsDelete_'+str(idx) ????????????w?=?self.__dict__[wName] ????????????self.connect(w,?QtCore.SIGNAL("stateChanged(int)"), ???????????? self.deleteProductIngredient) def deleteProductIngredient(self, state): """Delete a product ingredient.""" print self.sender(), "changed state to", state What QSignalMapper does is collect signals from different objects, assigning an ID to each of them, and emits a single signal with an ID whenever it receives a signal from one of those objects. In other words, it allows the actions of a group of objects to be described by a parameter but discards the signal's arguments. It's most useful for things like collections of push buttons where you only need to know that they were clicked. > For any interested, I worked around the problem using a closure, > which seems a bit cleaner from a coding point of view, although > I don't have any idea if it is more efficient or not: [...] > Each iteration then created a new function based on the closure: [...] It's good to know that you got something working in the end. There's also another solution that involves QSignalMapper, but it may not make the resulting code any simpler. David From casevh at comcast.net Thu Jan 4 02:43:28 2007 From: casevh at comcast.net (casevh at comcast.net) Date: 3 Jan 2007 23:43:28 -0800 Subject: code optimization (calc PI) / Full Code of PI calc in Python and C. In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> <1167872076.937415.250340@11g2000cwr.googlegroups.com> Message-ID: <1167896607.991340.32120@s34g2000cwa.googlegroups.com> Michael M. wrote: > Ok, here is the code. It is a translation of the following code, found > on the internet. > > * The C is very fast, Python not. > * Target: Do optimization, that Python runs nearly like C. There is an error in the translated code. It returns 1600 digits instead of 800 digits. > > counter=c > while 0<=counter+4000: > f.append(2000) # f.append( int(a/5) ) > counter=counter-1 > # b=b+1 This creates a list f with length 9601. It should have a length of 2801. I found an explanation of the original C program at http://rooster.stanford.edu/~ben/maths/pi/code.html Using the variable names from the above explanation and editing the code posted by bearophile to match the explanation, I have the following: from time import clock def compute_pi(): pi = [] a = 10000 i = k = b = d = c = 0 k = 2800 r = [2000] * 2801 while k: d = 0 i = k while True: d += r[i] * a b = 2 * i - 1 r[i] = d % b d //= b i -= 1 if i == 0: break d *= i k -= 14 pi.append("%04d" % int(c + d // a)) c = d % a return "".join(pi) start_time = clock() pi = compute_pi() print pi print "Total time elapsed:", round(clock() - start_time, 2), "s" print len(pi) You're original version takes 2.8 seconds on my computer. The above version takes .36 seconds. I tried a couple of optimizations but couldn't make any more improvements. casevh From agriff at tin.it Sun Jan 7 03:59:02 2007 From: agriff at tin.it (Andrea Griffini) Date: Sun, 07 Jan 2007 09:59:02 +0100 Subject: Why less emphasis on private data? In-Reply-To: <7xd55rzke9.fsf@ruckus.brouhaha.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> Message-ID: <45a0b4e3$0$19089$4fafbaef@reader4.news.tin.it> Paul Rubin wrote: > Yes I've had plenty of > pointer related bugs in C programs that don't happen in GC'd > languages, so GC in that sense saves my ass all the time. My experience is different, I never suffered a lot for leaking or dangling pointers in C++ programs; and on the opposite I didn't expect that fighting with object leaking in complex python applications was that difficult (I've heard of zope applications that just gave up and resorted to the "reboot every now and then" solution). With a GC if you just don't plan ownership and disposal carefully and everything works as expected then you're saving some thinking and code, but if something goes wrong then you're totally busted. The GC "leaky abstraction" requires you to be lucky to work well, but unfortunately IMO as code complexity increases one is never lucky enough. Andrea From fuzzyman at gmail.com Sun Jan 7 15:37:07 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Jan 2007 12:37:07 -0800 Subject: Capturing stderr and stdout of a subprocess as a single stream In-Reply-To: <1168201039.867515.35300@38g2000cwa.googlegroups.com> References: <1168198435.629380.136080@42g2000cwt.googlegroups.com> <1168201039.867515.35300@38g2000cwa.googlegroups.com> Message-ID: <1168202227.147827.294910@s80g2000cwa.googlegroups.com> Gabriel Genellina wrote: > On 7 ene, 16:33, "Fuzzyman" wrote: [snip..] > > My current code works, but *doesn't* capture stderr : > > > > from threading import Thread > > > > pipe = os.popen(executable) > > > > def DisplayOutput(): > > while True: > > output = pipe.read(1) > > if not output: > > break > > display(output) > > > > Thread(target=DisplayOutput).start() > > > > All the best, > > > > Fuzzyman > > http://www.voidspace.org.uk/python/articles.shtml > > Try using popen4 instead. But since you already have a thread, it may > be better to use popen2 and two threads to read from stdout and stderr > to avoid a potential deadlock; they can put read lines into a Queue, > and DisplayOutput just get these lines in order. (See the warnings in > the popen2 module documentation). > popen4 works great, I didn't even know it existed. Two threads and a queue sounds horrible. Thanks Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -- > Gabriel Genellina From nmm1 at cus.cam.ac.uk Mon Jan 8 10:58:56 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 8 Jan 2007 15:58:56 GMT Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> Message-ID: In article <50f5snF1fb5uqU2 at mid.individual.net>, Bjoern Schliessmann writes: |> Nick Maclaren wrote: |> |> > Ah! That explains it. I would call that reason intermediate |> > between rational and an artifact of the way the code has evolved! |> |> Which code has evolved? Those precision problems are inherent |> problems of the way floats are stored in memory. The use of different precisions for the two cases is not, however, and it is that I was and am referring to. Regards, Nick Maclaren. From nogradi at gmail.com Wed Jan 31 18:23:18 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 1 Feb 2007 00:23:18 +0100 Subject: pil, histogram, mask Message-ID: <5f56302b0701311523gc7a3620o7a5e8cb2b2941d1c@mail.gmail.com> How does one do a histogram on only a part of an image? This is what I found in the PIL documentation about histogram( ): """ im.histogram(mask) => list Returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). """ But I don't quite understand what "mask image is non-zero" mean. Does it mean non-white? For instance how would I get a histogram from the border of an image where the border is, say, 5% in width and height of the width and heigth of the full image? Do I need to prepare a mask image that is white in the middle and non-white at the edges? I should maybe add that I don't need the histogram really, only the mean color value, but as far as I can see the 'mean' attribute only applies to an image and a mask can not be specified. In case I overlooked something in the docs (which is easily possible) please point me to the appropriate page. From bblais at bryant.edu Thu Jan 11 14:58:00 2007 From: bblais at bryant.edu (Brian Blais) Date: Thu, 11 Jan 2007 14:58:00 -0500 Subject: Need better run/edit method. I have to restart the shell after every script change. In-Reply-To: <1168544475.849070.92160@77g2000hsv.googlegroups.com> References: <1168544475.849070.92160@77g2000hsv.googlegroups.com> Message-ID: <45A696C8.3050708@bryant.edu> Mark wrote: > I'm currently running the IDLE shell under Python 2.5, on Windows XP. > > Every time I edit my .txt or .py file, I have to restart the IDLE shell > for the changes to take effect. It's pretty annoying. Assuming IDLE is > already open, here are the steps that I typically take: > > 1. Open .txt version of module or script using notepad > 2. make changes > 3. save .txt file as .txt file > 4. save .txt file as .py file > 5. reset IDLE > 6. import module again > why do you involve notepad, and .txt files? Instead, try this: 1. Run Idle 2. Choose File/New Window 3. Edit your .py file, and save it as a .py file 4. Choose Run/Run Module 5. Make changes, and save again 6. Choose Run/Run Module 7. etc... you don't need to close IDLE ever. IDLE refers to the editor, and the shell that runs connected to it. If you have just the shell, you can open the editor with File/New Window. If you have just the editor, you can choose Run/Python Shell or Run/Run Module depending on what you want to do, to get the shell. You can also take a .py file in the Windows explorer, right-click, and choose "Open with IDLE" to start editing it directly. You shouldn't save things as .txt, because then IDLE will not recognize it is python you are writing, and the right-click trick probably won't work either. You should never use Notepad, because it is just icky, and doesn't know about any programming languages. :) Hope this helps, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From tinaweb at bestemselv.com Fri Jan 26 04:26:29 2007 From: tinaweb at bestemselv.com (Tina I) Date: Fri, 26 Jan 2007 10:26:29 +0100 Subject: Prefered install method? In-Reply-To: <51tu02F1lqdjbU1@mid.uni-berlin.de> References: <51tu02F1lqdjbU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > These days, it's setuptools. Google for it. It will let you distribute > your application in a convenient way as so-called EGG (basically a > ZIP-file), additionally you will get support for installing scripts in > /usr/bin or wherever you like, and you have versioning support. > > If you plan to release the app publically, it will also handle the > upload to the PyPI, the python package index - also known(?) as cheeseshop. > > Diez Great! Obviously exactly what I'm looking for. I already had it installed even, and it seem to be quite well documented and noob friendly. Thanks :) Tina From parallelpython at gmail.com Sun Jan 14 04:32:57 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 14 Jan 2007 01:32:57 -0800 Subject: Threaded for loop In-Reply-To: <1168750487.337511.213600@38g2000cwa.googlegroups.com> References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> <1168747208.275625.55590@51g2000cwl.googlegroups.com> <1168750487.337511.213600@38g2000cwa.googlegroups.com> Message-ID: <1168767176.995011.327620@l53g2000cwa.googlegroups.com> John wrote: > Thanks. Does it matter if I call shell commands os.system...etc in > calculate? > > Thanks, > --j The os.system command neglects important changes in the environment (redirected streams) and would not work with current version of ppsmp. Although there is a very simple workaround: print os.popen("yourcommand").read() instead of os.system("yourcommand") Here is a complete working example of that code: http://www.parallelpython.com/component/option,com_smf/Itemid,29/topic,13.0 From dickinsm at gmail.com Mon Jan 15 11:18:09 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 15 Jan 2007 08:18:09 -0800 Subject: Conflicting needs for __init__ method In-Reply-To: <1168822140.799071.153390@s34g2000cwa.googlegroups.com> References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> <1168822140.799071.153390@s34g2000cwa.googlegroups.com> Message-ID: <1168877889.309925.312860@11g2000cwr.googlegroups.com> On Jan 14, 7:49 pm, "Ziga Seilnacht" wrote: > Mark wrote:[a lot of valid, but long concerns about types that return > an object of their own type from some of their methods] > > I think that the best solution is to use an alternative constructor > in your arithmetic methods. That way users don't have to learn about > two different factories for the same type of objects. It also helps > with subclassing, because users have to override only a single method > if they want the results of arithmetic operations to be of their own > type. Aha. I was wondering whether __new__ might appear in the solution somewhere, but couldn't figure out how that would work; I'd previously only ever used it for its advertised purpose of subclassing immutable types. > Hope this helps, It helps a lot. Thank you. Mark From michael at mustun.ch Wed Jan 3 14:04:36 2007 From: michael at mustun.ch (Michael) Date: Wed, 03 Jan 2007 20:04:36 +0100 Subject: code optimization (calc PI) In-Reply-To: <1167844466.030065.303280@k21g2000cwa.googlegroups.com> References: <5020j6F1du59cU1@mid.uni-berlin.de> <1167844466.030065.303280@k21g2000cwa.googlegroups.com> Message-ID: Hmm.. thanks. I did this changes, but without any performance profits. Matimus wrote: > Using the '+' operator for string concatonation can be slow, especially > when done many times in a loop. > > >> pi = pi + str("%04d" % int(e + d/a)) ## this should be fast?! I dont > > > The accepted solution would be to make pi an array and append to the > end... > > pi = [] #create the array (empty) > ... > ... > pi.append(str("%04d"%int(e+d/a))) # append to it > > And when it is time to print the results do the following: > > print "".join(pi) > > It may look strange, but it is a common Python idiom. You might also > look into an optimizer such as psycho: http://psyco.sourceforge.net/. > From Thomas.Ploch at gmx.net Sat Jan 6 11:27:21 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sat, 06 Jan 2007 17:27:21 +0100 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: <459FCDE9.4030100@gmx.net> W. Watson schrieb: > The wiki site lead to a link to download pythonwin, but the download is > broken. Googling invariably leads back to that link. I found > , which has > two files listed: oadist.exe and win32dbg.exe. Do I need both or is just the > latter one? A google query 'pythonwin' directly brings me here: https://sourceforge.net/projects/pywin32/ I think this is the place to go Thomas From vatamane at gmail.com Fri Jan 12 09:31:24 2007 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 12 Jan 2007 06:31:24 -0800 Subject: Tools Designing large/complicated applications References: Message-ID: <1168612284.730059.225640@11g2000cwr.googlegroups.com> Carl, Some well known design applications have plugins for UML<->Python translation. For example EnterpriseArchitect (http://www.sparxsystems.com.au/resources/mdg_tech/) has a plugin for Python. ObjectDomain though supports it natively: http://www.objectdomain.com/products/od/overview.do The good thing about Python is that it is concise enough to not need UML diagrams. Python can be used as a prototype language itself. In other words it could take longer to draw the UML diagram than it would take to type up a mock-up in Python. While with Java, for example, it is very helpful to have a code generation application to take care of all the getters and setters. But of course if you have non-technical people who just know how to read UML diagrams, it makes sense to invest in a good design tool. Hope this helps, -Nick Carl J. Van Arsdall wrote: > For those of you that work on larger applications but still code in > python... do your development teams use any tools to facilitate the > design? (i'm not asking about editors here, i'm really asking about > software design tools) Are these the same tools you would use to help > engineer software in another language? > > Is there anyone here who is forced to use a tool to design python > software that completely hates it? Why do you hate it? > > Thanks! > > -carl > > > -- > > Carl J. Van Arsdall > cvanarsdall at mvista.com > Build and Release > MontaVista Software From bborcic at gmail.com Tue Jan 23 09:59:46 2007 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 23 Jan 2007 15:59:46 +0100 Subject: Rendering text question (context is MSWin UI Automation) Message-ID: <45b6231b$1_2@news.bluewin.ch> Hello, I am trying to use UI Automation to drive an MS Windows app (with pywinauto). I need to scrape the app's window contents and use some form of OCR to get at the texts (pywinauto can't get at them). As an alternative to integrating an OCR engine, and since I know the fonts and sizes used to write on the app's windows, I reasoned that I could base a simple text recognition module on the capability to drive MSWindows text rendering - eg to generate pixmaps of texts I expect to find in the driven app's windows, exact to the pixel. The advantage of that approach would be exactitude and self-containment. I've verified manually inside an Idle window, that indeed I could produce pixmaps of expected app texts, exact to the pixel (with Tkinter+screen capture at least). I could use help to turn this into a programmable capability, ie : A simple - with Tkinter or otherwise - way to wrap access to the MS Windows UI text rendering engine, as a function that would return a picture of rendered text, given a string, a font, a size and colors ? And ideally, without interfering with screen contents ? Thanks in advance for any guidance, Boris Borcic From gagsl-py at yahoo.com.ar Sun Jan 21 19:56:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Jan 2007 21:56:47 -0300 Subject: Beginners Tutorial in PDF Format? References: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net><1169415358.277431.130640@s34g2000cwa.googlegroups.com> Message-ID: "W. Watson" escribi? en el mensaje news:FJTsh.36658$Gr2.32367 at newssvr21.news.prodigy.net... Robert Hicks wrote: > W. Watson wrote: >> I'd like to print a tutorial in one fell swoop, but it seems most on the >> various sites are page by page embedded descriptions in the page. Any >> available as a pdf? > > http://docs.python.org/download.html > > http://www.diveintopython.org/ > > Thanks, but the first url takes me to a web page that contains the > complete > tutorial. Does choosing pdf (USA) in the table download a file that > contains > all the documents on the list below and to the left? Try again. The first url goes to this page: Download Python 2.5 Documentation (19 September 2006): To download an archive containing all the documents for this version of Python in one of various formats [pdf included, you can choose between Letter/A4]. Below, it says "These documents are not available for download individually." -- Gabriel Genellina From pgarrone at acay.com.au Fri Jan 19 21:00:23 2007 From: pgarrone at acay.com.au (pgarrone at acay.com.au) Date: 19 Jan 2007 18:00:23 -0800 Subject: Py 2.5 on Language Shootout References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> Message-ID: <1169258423.824108.228810@s34g2000cwa.googlegroups.com> Alioth is a great site for selecting the language in which to implement primitives. Usually it's C. Two of the alioth benchmarks, Partial-sums and Spectral-norm, could be done using Numarray, or would be done with Numarray if most of the program was in Python and there was a need to implement a similar numerical procedure. The speed would be up near the compiled language benchmarks. However the specific wording of these benchmarks prohibits this approach. Spectral-norm must pretend the dataset is infinite, and Partial-sums has to be implemented in a simple dumb loop. Looking over the benchmarks, one gains the impression that Python is a slow language. My first serious Python programming exercise involved converting a 900 line Bash Shell program to a 500 line Python program, with a speedup factor of 17. Using Python allowed an OO structure and advanced containers, meaning the program was more maintainable and portable, which were the main aims of the exercise. The speedup was a surprising and welcome side benefit. I think it was mosly because the Python byte-code interpreter is probably an order of magnitude faster than Bash's direct interpretation, and because in Python system calls to recurse directories and create symbolic links were not forked to separate processes. In fact I would guess that the overall speed of the Python program would be little less than a C program, given that most of the time would be spent in system calls. Its almost possible to make a large Python program arbitrarily fast by profiling it and implementing slow bits as primitives. Size is probably of greater concern. From steven.bethard at gmail.com Wed Jan 17 18:43:56 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 17 Jan 2007 16:43:56 -0700 Subject: aligning ElementTrees to text Message-ID: I'm trying to align an XML file with the original text file from which it was created. Unfortunately, the XML version of the file has added and removed some of the whitespace. For example:: >>> plain_text = ''' ... Pacific First Financial Corp. said shareholders approved its ... acquisition. ... ''' >>> xml_text = ''' Pacific First Financial Corp. ... said shareholders ... approved its ... acquis ition . ... ... ''' I want to determine which offsets in the *original* text each element from the XML text is supposed to cover. So I want something like:: >>> xml_tree = etree.fromstring(xml_text) >>> align(xml_tree, plain_text) [(, 31, 35), (, 49, 57), (, 62, 73), (, 1, 74)] where ``align`` has returned a list of all elements in the XML text along with their start and end indices in the original text:: >>> plain_text[31:35] 'said' >>> plain_text[49:57] 'approved' >>> plain_text[62:73] 'acquisition' Note that I want to ignore whitespace as much as possible, so the elements are aligned only to the non-whitespace text they include. Below is my current implementation of the ``align`` function. It seems pretty messy to me -- can anyone offer me some advice on how to clean it up or write it differently? def align(tree, text): def align_helper(elem, elem_start): # skip whitespace in the text before the element while text[elem_start:elem_start + 1].isspace(): elem_start += 1 # advance the element end past any element text elem_end = elem_start if elem.text is not None: for char in elem.text: if not char.isspace(): while text[elem_end:elem_end + 1].isspace(): elem_end += 1 assert text[elem_end] == char elem_end += 1 # advance the element end past any child elements for child_elem in elem: elem_end = align_helper(child_elem, elem_end) # advance the start for the next element past the tail text next_start = elem_end if elem.tail is not None: for char in elem.tail: if not char.isspace(): while text[next_start:next_start + 1].isspace(): next_start += 1 assert text[next_start] == char next_start += 1 # add the element and its start and end to the result list result.append((elem, elem_start, elem_end)) # return the start of the next element return next_start result = [] align_helper(tree, 0) return result Thanks, STeVe From dotancohen at gmail.com Wed Jan 3 11:21:58 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 3 Jan 2007 18:21:58 +0200 Subject: Unsubscribing from the list In-Reply-To: References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> Message-ID: <880dece00701030821y7f97504n5c8e658da14ba05f@mail.gmail.com> On 03/01/07, Fredrik Lundh wrote: > if you're unable to follow written instructions, how on earth did you manage > to subscribe to this list ? > > > Actually, I'm a compete idiot and I always post to the mailing list instead of RTFM or STFW. What's the name of that big big website? goobble or something?!? The first sentance under the heading "Python-list Subscribers" is: The subscribers list is only available to the list administrator. Admin address: Password: As I'm not an admin, I read no further. Dotan Cohen http://lyricslist.com/lyrics/artist_albums/169/duran_duran.html http://dapot.com From kKR_NIE_PISZ at gazeta.pl Tue Jan 23 03:55:08 2007 From: kKR_NIE_PISZ at gazeta.pl (kKR) Date: Tue, 23 Jan 2007 09:55:08 +0100 Subject: libhOCR-python - has somebody any experience with it? Message-ID: Hi people! I spent some time looking for any tutorials or examples, but I didn't find anything. All the Best, kKR From melih.onvural at gmail.com Wed Jan 31 16:25:02 2007 From: melih.onvural at gmail.com (Melih Onvural) Date: 31 Jan 2007 13:25:02 -0800 Subject: SyntaxError: 'return' outside function Message-ID: <1170278702.599741.212420@l53g2000cwa.googlegroups.com> Has anyone seen this error before and been able to solve it? I can't seem to find anything that leads to a solution. I found this post http://zope.org/Collectors/Zope/1809, but can't really understand it. I've attached my code below to see if anything looks funny. It happens at the very last return at the end. Thanks in advance, --melih ===========Code======== def legiturl(self, url): # this breaks down the url into 6 components to make sure it's "legit" t = urlparse.urlparse(url) if t[0] != 'http': return "" # remove URL fragments, but not URL if len(t[5]) > 0: url = urlparse.urlunparse((t[0],t[1],t[2],"","","")) t = urlparse.urlparse(url) # stupid parser sometimes leaves frag in path x = find(t[2], '#') if x >= 0: return "" From nszabolcs at gmail.com Mon Jan 29 12:06:48 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 09:06:48 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170088693.768440.26580@h3g2000cwc.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170088693.768440.26580@h3g2000cwc.googlegroups.com> Message-ID: <1170090408.495646.85720@v33g2000cwv.googlegroups.com> > while > 1:i=__import__;print''.join(i('random').choice(i('string').letters > +'1234567890')for x in range(8)),;raw_input() > while 1:i=__import__;r='random';print''.join(i(r).choice(i('string').letters +'1234567890')for x in`r`),;raw_input() even shorter: range -> `'random'` :) From rory at campbell-lange.net Mon Jan 8 16:30:15 2007 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Mon, 8 Jan 2007 21:30:15 +0000 Subject: Maths error Message-ID: <20070108213015.GA2838@campbell-lange.net> >>> (1.0/10.0) + (2.0/10.0) + (3.0/10.0) 0.60000000000000009 >>> 6.0/10.0 0.59999999999999998 Is using the decimal module the best way around this? (I'm expecting the first sum to match the second). It seem anachronistic that decimal takes strings as input, though. Help much appreciated; Rory -- Rory Campbell-Lange From robert.kern at gmail.com Tue Jan 9 14:31:19 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Jan 2007 13:31:19 -0600 Subject: Maths error In-Reply-To: <50i49iF1fvo3rU1@mid.individual.net> References: <50fudtF1g1nplU1@mid.individual.net> <50i49iF1fvo3rU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Nick Maclaren wrote: > >> No, don't. That is about another matter entirely, > > It isn't. Actually it really is. That thread is about the difference between str(some_float) and repr(some_float) and why str(some_tuple) uses the repr() of its elements. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Tue Jan 9 01:18:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Jan 2007 07:18:59 +0100 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <1168262998.765702.38760@i15g2000cwa.googlegroups.com> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <50ehtmF1fh46iU1@mid.uni-berlin.de> <1168262998.765702.38760@i15g2000cwa.googlegroups.com> Message-ID: <50gqeoF1dnbdqU1@mid.uni-berlin.de> vizcayno schrieb: > Diez B. Roggisch ha escrito: > >> vizcayno schrieb: >>> Hello: >>> Need your help in the "correct" definition of the next function. If >>> necessary, I would like to know about a web site or documentation that >>> tells me about best practices in defining functions, especially for >>> those that consider the error exceptions management. >>> I have the next alternatives but I think there are better: >> >> >> IMHO none of them is good. Python has exceptions. Use them. There is no >> need to awkwardly communicate error conditions using return-values. Use >> return values to return values. Use exceptions in case of errors. >> >> Diez > > Diez, in that case I woul prefer not to use exceptions and wait for > Python to abort itself and wait to see the message it issues. You are not making sense here - to me at last. If you don't handle the exceptions, exactly what you seem to want will happen - you will see the interpreter stop, and why. Handling errors in a graceful way can't be done by a standardized way, as you seem to want. It depends to much on what the actual code is doing. Sometimes an abort is necessary, sometimes you can continue working - but it all depends on what your actual usecase is, on a very detailed level. All you did was to take the unpythonic (and un-javaic and un-C#ic) road to transform an exception to a returncode. But that has nothing to do with actually _dealing_ with the error. Instead, it just makes it more likely that you _don't_ deal with it, as a return-code evaluation might be more easily forgotten, and turn out with a program that will be error-prone, as it continues to run even when the preconditions for pieces of code aren't met anymore. Diez From jonc at icicled.net Sat Jan 6 18:39:26 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sat, 6 Jan 2007 17:39:26 -0600 Subject: Traceback of hanged process In-Reply-To: <200701061737.20605.jonc@icicled.net> References: <1168123532.3498.51.camel@chopin> <200701061737.20605.jonc@icicled.net> Message-ID: <200701061739.27027.jonc@icicled.net> Heh, I kinda messed up the code there. It should be: import sys log_file = open('errors.log', 'w') sys.stderr = log_file log_file.close() As for the Ctrl-C, you can catch that when KeyboardInterrupt exception is raised. - Jonathan From gagsl-py at yahoo.com.ar Fri Jan 19 10:22:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 12:22:57 -0300 Subject: Why this script can work? References: <51bjskF1jbnhrU1@mid.uni-berlin.de> Message-ID: "Jm lists" escribi? en el mensaje news:fbe35f750701190254i79ecddf6id4dd9a7e726d1f5b at mail.gmail.com... > I'm not habitual for this usage of 'else',other languages seem don't > support this syntax. > i.g,writting the codes below by Perl would get an error: > > [[[censored example]]] If all languages had the same features, what would be the point of having different languages at all? -- Gabriel Genellina From __peter__ at web.de Wed Jan 17 11:20:17 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 Jan 2007 17:20:17 +0100 Subject: question about module resolution References: <1169050133.438101.90030@a75g2000cwd.googlegroups.com> Message-ID: Emin wrote: > I often find myself wanting to have a child module get some parameters > defined in a parent module. For example, imagine I have the following > directory structure and want something in baz.py to look at a value in > config.py. I end up putting in things like import sys; > sys.path.append('../..'). Is there a better way? > > foo/ > __init__.py > config.py > bar/ > __init__.py > baz.py from __future__ import absolute_import from .. import config Peter From mail at microcorp.co.za Tue Jan 9 00:31:03 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 9 Jan 2007 07:31:03 +0200 Subject: recursive function References: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> <1168277289.970128.44880@38g2000cwa.googlegroups.com> Message-ID: <021801c733c8$3f2ae500$03000080@hendrik> "cesco" wrote: > > Neil Cerutti wrote: > > On 2007-01-08, cesco wrote: > > > Hi, > > > > > > I have a dictionary of lists of tuples like in the following example: > > > dict = {1: [(3, 4), (5, 8)], > > > 2: [(5, 4), (21, 3), (19, 2)], > > > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]] > > > > > > In this case I have three lists inside the dict but this number > > > is known only at runtime. I have to write a function that > > > considers all the possible combinations of tuples belonging to > > > the different lists and return a list of tuples of tuples for > > > which the sum of the first element of the most inner tuple is > > > equal to N. > > > > > > For example, assuming N = 24, in this case it should return: > > > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19, > > > 2), (0, 2))] > > > > What do you mean by "most inner tuple"? > > > > > A simple list comprehension would be enough if only I knew the > > > number of keys/lists beforehand > > > > len(dict.keys()). > > What I mean is that the number of keys/lists is not known until runtime > and it changes randomly from time to time which means I would have to > write every time a different list comprehension (or a different number > of nested loops) to accomplish the same thing. > In the example the result of the search should be a list containing > three tuples each of which contains again three tuple (the most inner > tuples). If you consider the first element of each tuple the sum is 24 > (like in 3+5+16, or 3+21+0 or 5+19+0). > > Any other help will be appreciated Is there any reliable structure in the data? - for instance in your example, the first list has two tuples, the second one three, and the third one four - Is this a pattern? - Hendrik From Robert.Katic at gmail.com Tue Jan 16 12:36:15 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 16 Jan 2007 09:36:15 -0800 Subject: arguments of a function/metaclass In-Reply-To: References: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> <1168964835.087773.221950@s34g2000cwa.googlegroups.com> Message-ID: <1168968973.527414.239960@38g2000cwa.googlegroups.com> Gabriel Genellina je napisao/la: > "goodwolf" escribi? en el mensaje > news:1168964835.087773.221950 at s34g2000cwa.googlegroups.com... > > A simply solution: > > > > def __init__(self, a=1, b=2, c=3, ......): > > for key, val in locals().items(): > > if key != 'self': > > setattr(self.__class__, key, val) > > > > in addition: > > > > def set(self, **kwarg): > > for key in kwargs: > > if hasattr(self.__class__, key): > > setattr(self.__class__, key, kwargs[key]) > > else: > > raise .... > > Why setattr(self.__class__,...) instead of setattr(self, ...)? You're > modifying the class attributes, and that's not usually intended. > > -- > Gabriel Genellina My error. Post was written directly. Sorry. From deets at nospam.web.de Fri Jan 12 09:48:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Jan 2007 15:48:16 +0100 Subject: Python nuube needs Unicode help References: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> <1168613067.354487.40840@51g2000cwl.googlegroups.com> Message-ID: <50pldgF1gecd0U2@mid.uni-berlin.de> gheissenberger at gmail.com wrote: > Can you attach files in this forum? Couldn't find the option. Oh well, > here's the file. > > #!/usr/bin/python > # Version: 1.1 > # Author: Steve Losh > > from sets import Set > from optparse import OptionParser > from xml.dom.minidom import parse > > AudioPath = 'audio/' > DatafilePath = 'utterances.trmxml' > CONFIDENCE_LOW = None #'500' > CONFIDENCE_HIGH = None #'500' > > utterancesFile = None > > > class Utterance: > def __init__(self, audio, grammarSet, text): > self.audio = audio > self.grammarSet = grammarSet > self.text = text > > def __str__(self): > return "SWIrecAcousticStateReset\ntranscription " + self.text \ > + "\nrecognize " + AudioPath + self.audio There your __str__-method is. self.text and self.audio come from the xml-parsing and are unicode objects - so they need to be encoded, like this: def __str__(self): return "SWIrecAcousticStateReset\ntranscription " + self.text.encode('utf-8') + "\nrecognize " + AudioPath + self.audio.encode('utf-8') Diez From tjreedy at udel.edu Mon Jan 22 22:41:14 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Jan 2007 22:41:14 -0500 Subject: match nested parenthesis References: <1169521381.814119.27020@11g2000cwr.googlegroups.com> Message-ID: wrote in message news:1169521381.814119.27020 at 11g2000cwr.googlegroups.com... | hi | i wish to find an reg exp for matching nested parenthesis of varying | level like | string = | "somewords1(words(somewords2)-(some(some)words3)somestuff)somestuff" | and be able to evaluate the pair starting from the inner most(the | deepest level) , ie (some) | up till the outer most. What is a good reg exp to do this? or is simple | string manipulations enough? | thanks The presence of indefinitely nested fence markers, like parens, differentiates a context-free language, generated from a context-free grammar, from a regular language/grammar. You cannot parse such sentences with a regex engine or even with an extended regex engine such as Python's. Use a more general parser. tjr From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 14:53:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 20:53:52 +0100 Subject: newbieee References: <1168280831.323496.277020@38g2000cwa.googlegroups.com> Message-ID: <50flqgF1fotpdU1@mid.individual.net> lee wrote: > I getting familiarised with python...can any one suggest me a good > editor available for python which runs on windows xp.... Look here: http://wiki.python.org/moin/PythonEditors > one more request guys...can nyone tell me a good reference manual > for python.. Either the python homepage, or "Python in a Nutshell". The 2nd edition covers 2.5. Regards, Bj?rn -- BOFH excuse #324: Your packets were eaten by the terminator From hg at nospam.org Tue Jan 2 06:58:27 2007 From: hg at nospam.org (hg) Date: Tue, 02 Jan 2007 12:58:27 +0100 Subject: array of class References: Message-ID: mm wrote: > > How can I do a array of class? > > s1=[] ## this array should hold classes > > ## class definition > class Word: > word="" > > > ## empty words... INIT > for i in range(100): ## 0..99 > s1.append(Wort) > > s1[0].word="There" > s1[1].word="should" > s1[2].word="be" > s1[3].word="different" > s1[4].word="classes" > > ... but it's not. > > > print s1 > ------------ > [, > , > , > , > , > , > ........ > ----------- > > Here, this "classes" are all at the same position in memory. So there > are no different classes in the array. > > So I access with s1[0], s1[1], s1[2], etc. always the same data. > > Any idea? > > -- > Michael do you mean object ? your append should be append(Word()) as you need to create instances. hg From subscriber100 at rjs.org Tue Jan 9 00:14:35 2007 From: subscriber100 at rjs.org (Ray Schumacher) Date: Mon, 08 Jan 2007 21:14:35 -0800 Subject: multi-threaded webcam with SimpleAsyncHTTPServer.py Message-ID: <6.2.3.4.2.20070108203953.02e99eb0@pop-server.san.rr.com> >>Question, though: how can I unblock asyncore.loop(), or at least be >>able to interrupt it? >Why do you want to do that? I was then thinking along the lines of a Netmeeting/visual chat program, rather than a daemon-type server, where one might want to terminate more quickly. Searching further, I see that a common idiom is like: while some_condition: try: asyncore.loop(timeout=1, count = 1) except KeyboardInterrupt: break or, spawn asyncore.loop() threads. Zope and Medusa seem to use a variety of methods. A regular web-cam program serving up 2 or 3 cams on one machine will require more thought on my part, of course. I only run one cam, but a friend runs 3 and is pissed at the X10 software he paid for. Thanks, Ray From shansen at advpubtech.com Thu Jan 11 13:59:51 2007 From: shansen at advpubtech.com (Stephen Hansen) Date: Thu, 11 Jan 2007 10:59:51 -0800 Subject: RotatingFileHandler + subprocess module problems Message-ID: <7a9c25c20701111059q1186377nde4021eaf768d345@mail.gmail.com> Hey, there. I'm currently having a problem with what *looks* like an interaction between using subprocess and RotatingFileHandler. This is on Windows with Python 2.3 I have two console applications: app1 and app2. For most of app2 to function properly, app1 must already be running. App1 logs to c:\app1.log. App2 logs to c:\app2.log, both using RotatingFileHandler from the logging module. If I run app1, and then app2, it all works fine. Specifically, the apps are logging correctly and I can see with Process Explorer that each has a handle to the appropriate files. However, I have a setting to make App2 run App1 in the background for convienance. This is using the subprocess module. When this setting is on, App2 will die horribly the first time that the doRollover comes along: specifically it gets a permission denied error when it tries to rename App2.log to App2.log.1 After doing some debugging, it appears that App1 (if started by App2 using the subprocess module) has a handle to App2.log /somehow/. It never starts it, or touches it (verified through debug messages), but seems to inherit it. Is there anything obvious I'm doing wrong? :) If it doesn't jump out at anyone, I'll write up a mockup. I'm hoping I just did something of a goof that will be obvious though, since the apps are a bit complicated and distilling them down to a testcase will be mildly annoying. :) Thanks in advance. --Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Thu Jan 11 11:02:49 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Jan 2007 17:02:49 +0100 Subject: What happened to SPE? References: Message-ID: On 2007-01-11, Paulo Pinto wrote: > does anyone know what happened to SPE? > > It seems that the address http://pythonide.stani.be > is no longer valid. :( SPE lost its web host, and last I heard is looking for a new home. For now you can get it here: http://sourceforge.net/projects/spe/ -- Neil Cerutti We don't necessarily discriminate. We simply exclude certain types of people. --Colonel Gerald Wellman From mneagul at gmail.com Thu Jan 25 10:13:21 2007 From: mneagul at gmail.com (mneagul) Date: 25 Jan 2007 07:13:21 -0800 Subject: Python email parser Message-ID: <1169738001.643280.140880@a75g2000cwd.googlegroups.com> Hello, I want to use email.Parser for parsing some email messages but I have a small problem: it is very, very slow... For 110MB of email messages it takes ~29-30 seconds for parsing. Do you know some other email parser for python? Marian Neagul From mw at visenso.de Tue Jan 30 04:50:07 2007 From: mw at visenso.de (Marco Wahl) Date: 30 Jan 2007 10:50:07 +0100 Subject: Explanation about pickle module References: <1170149840.610362.319690@h3g2000cwc.googlegroups.com> Message-ID: <9o3b5su9m8.fsf@gonzo.vircinity> "raghu" writes: > can any one explain about pickle i read in the book but they have not > provided any example for that so please explain with a simple example > >>> class Foo(object): ... def __init__(self): ... self.bar = 1 ... >>> import pickle >>> a = Foo() >>> pickle.dumps(a) "ccopy_reg\n_reconstructor\np0\n(c__main__\nFoo\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'bar'\np6\nI1\nsb." >>> b = pickle.loads("ccopy_reg\n_reconstructor\np0\n(c__main__\nFoo\np1\nc__builtin__\nobject\np2\nNtp3\nRp4\n(dp5\nS'bar'\np6\nI1\nsb.") >>> b.bar 1 >>> b <__main__.Foo object at 0x402ae68c> >>> There is also pickle.dumps and pickle.loads to work directly with files. Further there is module cpickle which offers the same functionality as pickle but which is faster. Bye -- Marco Wahl http://visenso.com From skip at pobox.com Mon Jan 29 13:28:11 2007 From: skip at pobox.com (Skip Montanaro) Date: Mon, 29 Jan 2007 18:28:11 +0000 (UTC) Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <17848.60341.346203.660506@montanaro.dyndns.org> Message-ID: > Andy Dustman, the author of the package is quite responsive to requests > raised in the mysql-python forums on SourceForge > (http://sourceforge.net/forum/?group_id=22307). If you have problems with > MySQLdb, bring them up there. I'm sure Andy will respond. I apologize in advance for beating this dead horse... This morning a possible bug was reported in MySQLdb. Andy determined it was indeed a bug, had a fix checked into the source repository in a couple hours and reported that it would be in the next 1.2 beta release. Skip From spam at chezmarshall.freeserve.co.uk Fri Jan 19 16:41:53 2007 From: spam at chezmarshall.freeserve.co.uk (Robert Marshall) Date: Fri, 19 Jan 2007 21:41:53 +0000 Subject: Determining when a file is an Open Office Document References: Message-ID: On Fri, 19 Jan 2007, Steven D'Aprano wrote: > On Fri, 19 Jan 2007 12:22:04 +1100, Ben Finney wrote: > >> tubby writes: >> >>> Silly question, but here goes... what's a good way to determine >>> when a file is an Open Office document? I could look at the file >>> extension, but it seems there would be a better way. >> >> The Unix 'file' command determines the type of a file by its >> contents, not its name. This functionality is essentially a >> database of "magic" byte patterns mapping to file types, > > Ah, another lousy, unreliable way to make a definite statement about > the actual contents of a file. Looking at magic bytes inside a file > is hardly bullet-proof (although file seems to be moderately > reliable in practice, at least under Linux). > > Simple example: is the file consisting of two bytes "x09x0A" meant > to be a text file with a tab and a newline, or a binary file > consisting of a single two-byte int? There's no way to tell just > from the contents. And see for example the problem that development versions of emacs is (were?) having with C files that started #define and were then treated as graphics files! http://thread.gmane.org/gmane.emacs.devel/64823/focus=65228 Robert -- La grenouille songe..dans son ch?teau d'eau Links and things http://rmstar.blogspot.com/ From deets at nospam.web.de Fri Jan 19 12:42:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 Jan 2007 18:42:54 +0100 Subject: confused on python rpc with apache, is it possible? References: Message-ID: <51ce8uF1k0tl5U1@mid.uni-berlin.de> krishnakant Mane wrote: > hello all. > I will like to know if the following combination is possible. > I have looked around on google and did not find any thing productive > so bothering the list: sorry. > I am developing a distributed application which will have 3 layers > namely the thin client written in wxpython, an application layer on a > server and a database server of course. database and application > server will be on same physical machine. > what I want to know is if I can use python as the base for developing > the application layer as an rpc server and use apache server to > handle http remote procedure requests from the client? > if yes then what basic configuration settings I will need? > I believe I must first have apache recognise python interpreter and > then do some settings in apache so that it knows that what is > happening is not a web page request but an xml-rpc application created > in python. > can some one guide me? I'm unclear why you want the apache in there in the first place. Why don't you just create an e.g. twisted-based XMLRPC-server, and simply let that run? What is the apache intended for? Diez From baur79 at gmail.com Wed Jan 3 04:27:23 2007 From: baur79 at gmail.com (baur79) Date: 3 Jan 2007 01:27:23 -0800 Subject: how to use execfile with argument under windows In-Reply-To: References: <1167757591.465076.314700@h40g2000cwb.googlegroups.com> Message-ID: <1167816443.596799.66060@a3g2000cwd.googlegroups.com> os.system() solve my problem thanks you guys and happy new year with best wishes from Kazakhstan / Shymkent city / sodbisystems.kz On Jan 2, 11:49 pm, Peter Otten <__pete... at web.de> wrote: > baur79 wrote: > > i need to execute this command line (different source for n times) > > > filename.exe -type png -source sourcearg -file filename.png > > i try with python (python script and filename.exe in same directory) > > execfile("filename.exe -type png -source sourcearg -file filename.png")That does not do what you think it does, see > > http://docs.python.org/lib/built-in-funcs.html#l2h-26 > > You need os.system() or, for more complex applications, the subprocess > module. > > Peter From bj_666 at gmx.net Fri Jan 12 13:24:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 12 Jan 2007 19:24:43 +0100 Subject: What is a perl hash in python References: Message-ID: In , Karyn Williams wrote: > I am new to Pyton. I am trying to modify and understand a script someone > else wrote. I am trying to make sense of the following code snippet. I know > line 7 would be best coded with regex. What is line 7 in the snippet? > I first would like to understand what was coded originally. thelistOut > looks like a hash to me (I'm more familiar with perl). It's a list which contains tuples. Each tuple contains an integer and a list with one string that looks like a pathname. > Perhaps someone could translate from perl to python for me - not in code > but just in concept. Which Perl? You gave us Python!? > Here is the code. This script is reading the list thelistOut and then > removing any items in RSMlist and taking the remainder and putting them > in graphAddressOut with the formatting. There's nothing removed from `thelistOut`. Names where the filename/basename without the extension is in `RSMList` are not processed and added to `outputOut`. > This is a SAMPLE of what is in the lists referenced below in the loop: > > > thelistOut = [(632, > ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_9.log']), (145, > ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_13.log']), (0, > ['/usr/local/www/data-dist/mrtg/main/test/172.16.0.23_5.log'])] > > RSMList = ['172.16.0.1_1', '172.16.0.1_2', '172.16.0.1_3', > '172.16.0.1_4', '172.16.0.1_5'] > > > > #--------------------------Loop 1 ------------------------- > > w = 0 > while w < 45: The loop looks odd. Is it really a literal 45 here or are all elements of `thelistOut` processed? Then a for loop over the list if you don't need `w` for something other than indexing into the list or an `xrange()` object are much cleaner than using a while loop and updating the counter manually. That the second element of the tuple seems to be always a list with one item looks odd too. > fileOut = string.split(thelistOut[w][1][0],".log") > fileOutSplitedCommon = string.split(fileOut[0], "main/") > fileOut2D = string.split(fileOutSplitedCommon[1], "/") > fileOut = string.split(fileOut[0],"data-dist") This might be more readable and understandable if `os.path.splitext()` and `os.path.split()` where used. > if fileOut2D[1] in RSMList: > w = w + 1 > continue Might be cleaner to negate the test and use the remaining code as body of that ``if`` statement. > graphAddressOut = tag1 + logUrl + fileOut[1] + extention1 + tag2 > + > "SWITCH: " + string.swapcase(fileOut2D[0]) + "  & nbsp;PORT > ID: " + fileOut2D[1] + "
" + imgTitleTag + imgTag1 + logUrl + > fileOut[1] + extention2 + imgTag2 + tag3 + tag5 > outputOut.append(graphAddressOut) > strOut = strOut + graphAddressOut That's an unreadable mess. Better use string formatting. And last but not least: a hash is called dictionary in Python. Ciao, Marc 'BlackJack' Rintsch From gagsl-py at yahoo.com.ar Tue Jan 16 21:25:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 23:25:52 -0300 Subject: Regex Question In-Reply-To: <1168976209.504793.51890@38g2000cwa.googlegroups.com> References: <1168976209.504793.51890@38g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070116231540.0466dbd0@yahoo.com.ar> At Tuesday 16/1/2007 16:36, Bill Mill wrote: > > py> import re > > py> rgx = re.compile('1?') > > py> rgx.search('a1').groups() > > (None,) > > py> rgx = re.compile('(1)+') > > py> rgx.search('a1').groups() > >But shouldn't the ? be greedy, and thus prefer the one match to the >zero? This is my sticking point - I've seen that plus works, and this >just confuses me more. Perhaps you have misunderstood what search does. search( pattern, string[, flags]) Scan through string looking for a location where the regular expression pattern produces a match '1?' means 0 or 1 times '1', i.e., nothing or a single '1'. At the start of the target string, 'a1', we have nothing, so the re matches, and returns that occurrence. It doesnt matter that a few characters later there is *another* match, even if it is longer; once a match is found, the scan is done. If you want "the longest match of all possible matches along the string", you should use findall() instead of search(). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From hpsekhon at googlemail.com Mon Jan 1 18:43:39 2007 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 1 Jan 2007 23:43:39 +0000 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> Message-ID: <4f45772d0701011543w5cc27f84q165ae60bc657d8e9@mail.gmail.com> That is shell scripting with a python layer on top. Is there a specific reason you have to use python? Why not just use shell, that's what it's designed for? Unless you have some complex maths/networking requirement or something on top. -h On 01/01/07, Daniel Klein wrote: > On 1 Jan 2007 11:33:42 -0800, "Ramdas" wrote: > > >How do I add users using Python scripts on a Linux machine? > > > >Someone has a script? > > This should be as easy as something like: > > os.system("/usr/sbin/useradd -m -d /home/newuser -s /bin/ksh") > > Dan > -- > http://mail.python.org/mailman/listinfo/python-list > -- Hari Sekhon From arkanes at gmail.com Tue Jan 23 10:24:22 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 23 Jan 2007 09:24:22 -0600 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <45b6231b$1_2@news.bluewin.ch> References: <45b6231b$1_2@news.bluewin.ch> Message-ID: <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> On 1/23/07, Boris Borcic wrote: > Hello, > > I am trying to use UI Automation to drive an MS Windows app (with pywinauto). > > I need to scrape the app's window contents and use some form of OCR to get at > the texts (pywinauto can't get at them). > > As an alternative to integrating an OCR engine, and since I know the fonts and > sizes used to write on the app's windows, I reasoned that I could base a simple > text recognition module on the capability to drive MSWindows text rendering - eg > to generate pixmaps of texts I expect to find in the driven app's windows, exact > to the pixel. > > The advantage of that approach would be exactitude and self-containment. > > I've verified manually inside an Idle window, that indeed I could produce > pixmaps of expected app texts, exact to the pixel (with Tkinter+screen capture > at least). > > I could use help to turn this into a programmable capability, ie : A simple - > with Tkinter or otherwise - way to wrap access to the MS Windows UI text > rendering engine, as a function that would return a picture of rendered text, > given a string, a font, a size and colors ? > > And ideally, without interfering with screen contents ? > > Thanks in advance for any guidance, > > Boris Borcic There are actually several different text rendering methods (and 2 or more totally different engines) and they will give different results, so if you want a fully generic solution that could be quite difficult. However, it sounds like this is for a specific purpose. Using the pywin32 modules to directly access the appropriate windows API calls will be the most accurate. It will be fairly complicated and you'll require knowledge of the win32 api to do it. You could also use wxPython, which uses what will probably be the right API and will take less code than win32 will. I'd suggest this if you aren't familiar with the win32 API. PyQt uses it's own text rendering engine, as far as I know, so it is less likely to generate correct bitmaps. I'm not sure at what level tkinters text drawing is done. Using either win32 or wxPython you will be able to produce bitmaps directly, without needing to create a visible window. Some quick & dirty wxPython code def getTextBitmap(text, font, fgcolor, bgcolor): dc = wx.MemoryDC() dc.SetFont(font) width, height= dc.GetTextExtent(text) bmp = wx.EmptyBitmap(width, height) dc.SelectObject(bmp) dc.SetBackground(wx.Brush(bgcolor)) dc.Clear() dc.SetTextBackground(bgcolor) dc.SetTextForeground(fgcolor) dc.DrawText(text, 0, 0) dc.SelectObject(wx.NullBitmap) return bmp Raw win32 code will look similar but will be much more verbose. From david at boddie.org.uk Thu Jan 25 16:46:51 2007 From: david at boddie.org.uk (David Boddie) Date: Thu, 25 Jan 2007 22:46:51 +0100 Subject: pdf to text References: Message-ID: <86714$45b9254c$54d1d767$3741@news.chello.no> On Thursday 25 January 2007 22:05, tubby wrote: > I know this question comes up a lot, so here goes again. I want to read > text from a PDF file, run re searches on the text, etc. I do not care > about layout, fonts, borders, etc. I just want the text. I've been > reading Adobe's PDF Reference Guide and I'm beginning to develop a > better understanding of PDF in general, but I need a bit of help... this > seems like it should be easier than it is. It _seems_ that way. ;-) One of the more promising suggestions for a way to solve this came up in a comp.lang.python thread last year: http://groups.google.com/group/comp.lang.python/msg/cb6c97a44ce4cbe9?dmode=source Basically, if you have access to the pdftotext command on a system that supports xpdf, you should be able to get something reasonable out of a PDF file. > I know the text is compressed... that it would have stream and endstream > makers and BT (Begin Text) and ET (End Text) and that the uncompressed > text is enclosed in parenthesis (this is my text). Has anyone here done > this in a simple fashion? I've played with the pyPdf library some, but > it seems overly complex for my needs (merge PDFs, write PDFs, etc). I > just want a simple PDF text extractor. The pdftotext tool may do what you want: http://www.foolabs.com/xpdf/download.html Let us know how you get on with it. David From http Wed Jan 24 16:07:16 2007 From: http (Paul Rubin) Date: 24 Jan 2007 13:07:16 -0800 Subject: Simple Matrix class References: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> <1169602411.917985.89840@l53g2000cwa.googlegroups.com> <1169617221.481444.135820@v45g2000cwv.googlegroups.com> <1169664540.120687.211350@s48g2000cws.googlegroups.com> <1169670271.547292.141110@l53g2000cwa.googlegroups.com> Message-ID: <7xodooi16j.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > Dang, I thought I was testing the results sufficiently! What is the > accuracy problem? In my test cases, I've randomly created test > matrices, inverted, then multiplied, then compared to the identity > matrix, with the only failures being when I start with a singular > matrix, which shouldn't invert anyway. There's a lot of ill-conditioned matrices that you won't hit at random, that aren't singular, but that are nonetheless very stressful for numerical inversion. The Hilbert matrix a[i,j]=1/(i+j+1) is a well known example. If you're taking exponential time to invert matrices (sounds like you're recursively using Cramer's Rule or something) that doesn't begin to be reasonable even for very small systems, in terms of accuracy as well as speed. It's a pure math construct that's not of much practical value in numerics. You might look at the Numerical Recipes books for clear descriptions of how to do this stuff in the real world. Maybe the experts here will jump on me for recommending those books since I think the serious numerics crowd scoffs at them (they were written by scientists rather than numerical analysts) but at least from my uneducated perspective, I found them very readable and well-motivated. From pjmlp at progtools.org Thu Jan 11 10:43:45 2007 From: pjmlp at progtools.org (Paulo Pinto) Date: Thu, 11 Jan 2007 15:43:45 GMT Subject: What happened to SPE? Message-ID: Hi, does anyone know what happened to SPE? It seems that the address http://pythonide.stani.be is no longer valid. :( Thanks in advance, Paulo From sebastien.thur at laposte.net Thu Jan 18 11:40:56 2007 From: sebastien.thur at laposte.net (seb) Date: 18 Jan 2007 08:40:56 -0800 Subject: connection to server not accepted (but no error) only after several hours In-Reply-To: <2%trh.15629$X72.10440@newsread3.news.pas.earthlink.net> References: <1168961973.099821.318920@l53g2000cwa.googlegroups.com> <1169021332.523258.192510@s34g2000cwa.googlegroups.com> <2%trh.15629$X72.10440@newsread3.news.pas.earthlink.net> Message-ID: <1169138455.544356.161240@s34g2000cwa.googlegroups.com> Hi Dennis, I think I have some new informations. My system is "blocked" now but the following change make it work again !!! I will test it for tonight to be sure of the improvements. I changed : service.bind(("", self.PORT)) to service.bind((socket.gethostname(), self.PORT)) The strange thing is that using the "" it works for a few hours. Regards. Sebastien. Dennis Lee Bieber a ?crit : > On 17 Jan 2007 00:08:52 -0800, "seb" > declaimed the following in comp.lang.python: > > > > > 1) I have enabled one time server that can be run as a service (R C C > > time server) and this service is responding correctly, when at the same > > time (before I kill it ) the python time server is not responding. > > > > What behavior do you see if you don't run them as background > services, but rather from a regular console login? > > > 2) I have also tried two python time server downloaded from effbot > > site. Both are not responding after the "non response from the time > > server I rn" even for the first interrogation once they are started. > > (Of course I have killed my time server when I run a new one). > > Same behaviour no response given but no error neither. > > > If you've now got a total of three programs that are not reporting > error conditions, I'd suspect there is something else wrong in the > system... > > > It is only python programs that are listening from the port 37 that are > > blocked at a certain time. > > How is it possible (without firewall enabled) ? > > > What response do you get from the clients attempting to connect to > this server? (I'd expect a either a flat out "denied" or, for a > stealthed firewall, a timeout with no response). > > > You also have a race condition in your log-file... > > > a.start() > > a.set_log_file("log_nw.txt") > > a.reset_log_file() > > It is possible that the thread gets a few connections between the > .start() and the .set_log_file() and logs them to the default file name. > Also, it is possible for connections to be logged between the > .set_log_file() and the .reset_log_file() (where you wipe out the > contents of the log file). > > I'd suggest putting the .start() call third in that list. That way > you create the thread object, but it is not running. Change the log file > name, wipe out any old contents, and THEN start the thread running. > > My only other comment would be to add a few wolf-fences... Print > statements (if running in a console), or more logging messages (you > might want to make a method out of that internal logging so all you code > is, say > > self.slog("message") > > and "slog" does that time stamping, and file open/close... > > By logging each main step (accept, send, close) you might find where > it stops. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From http Sun Jan 14 03:59:38 2007 From: http (Paul Rubin) Date: 14 Jan 2007 00:59:38 -0800 Subject: Threaded for loop References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> <7xr6ty8ugv.fsf@ruckus.brouhaha.com> <1168750192.222440.89450@a75g2000cwd.googlegroups.com> Message-ID: <7xzm8m9e6d.fsf@ruckus.brouhaha.com> "John" writes: > Damn! That is bad news. So even if caclulate is independent for > (i,j) and is computable on separate CPUs (parts of it are CPU bound, > parts are IO bound) python cant take advantage of this? Not at the moment, unless you write C extensions that release the global interpreter lock (GIL). One of these days. Meanwhile there are various extension modules that let you use multiple processes, look up POSH and Pyro. From skip at pobox.com Thu Jan 25 19:31:48 2007 From: skip at pobox.com (skip at pobox.com) Date: Thu, 25 Jan 2007 18:31:48 -0600 Subject: The reliability of python threads In-Reply-To: <7xveiu4xis.fsf@ruckus.brouhaha.com> References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> <1169754601.992058.205640@q2g2000cwa.googlegroups.com> <7xsldy7u6f.fsf@ruckus.brouhaha.com> <1169758010.223732.272340@k78g2000cwa.googlegroups.com> <7xveiu4xis.fsf@ruckus.brouhaha.com> Message-ID: <17849.19444.535219.412533@montanaro.dyndns.org> Paul> I dunno about Nick, I'm saying it's best to assume that it's Paul> Poisson and do whatever is necessary to diagnose and fix the bug, Paul> and that the voodoo measure you're proposing is not all that Paul> likely to help and it will take years to find out whether it helps Paul> or not (i.e. restarting after 3 months and going another 3 months Paul> without a failure proves nothing). What makes you think Paddy indicated he wouldn't try to solve the problem? Here's what he wrote: What I'm proposing is that if, for example, a process stops running three times in a year at roughly three to four months intervals , and it should have stayed up; then restart the server sooner, at aa time of your choosing, whilst taking other measures to investicate the error. I see nothing wrong with trying to minimize the chances of a problem rearing its ugly head while at the same time trying to investigate its cause (and presumably solve it). Skip From nagle at animats.com Tue Jan 30 15:05:54 2007 From: nagle at animats.com (John Nagle) Date: Tue, 30 Jan 2007 20:05:54 GMT Subject: Convert raw data to XML In-Reply-To: <1170184059.739808.244660@s48g2000cws.googlegroups.com> References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> <1170184059.739808.244660@s48g2000cws.googlegroups.com> Message-ID: elrondrules at gmail.com wrote: > On Jan 29, 8:54 pm, "Gabriel Genellina" wrote: > >>En Mon, 29 Jan 2007 23:42:07 -0300, escribi?: > the reason I wanted to write it as a file was to parse the file, look > for a specific attribute and execute a set of commands based on the > value of the attribute.. also i needed to display the output of the > http post in a more readable format.. That's straightforward. You confused people by asking the wrong question. You wrote "Convert raw data to XML", but what you want to do is parse XML and extract data from it. This will do what you want: http://www.crummy.com/software/BeautifulSoup/ For starters, try from BeautifulSoup import BeautifulStoneSoup xmlstring = somexml ## get your XML into here as one big string soup = BeautifulStoneSoup(xmlstring) # parse XML into tree print soup.prettify() # print out in indented format "soup" is a tree structure representing the XML, and there are functions to easily find items in the tree by tag name, attribute, and such. Work on the tree, not a file with the text of the indented output. John Nagle From deets at nospam.web.de Tue Jan 30 04:47:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 Jan 2007 10:47:40 +0100 Subject: Explanation about pickle module References: <1170149840.610362.319690@h3g2000cwc.googlegroups.com> Message-ID: <528ihsF1lrmsgU3@mid.uni-berlin.de> raghu wrote: > can any one explain about pickle i read in the book but they have not > provided any example for that so please explain with a simple example Bad google day? Or just to lazy to do it? And what is "the book"? There are quite a few out there, some about python the language, others about snakes of the same name. Which one? http://www.python.org/doc/current/lib/pickle-example.html Diez From danb_83 at yahoo.com Thu Jan 4 20:55:19 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 Jan 2007 17:55:19 -0800 Subject: pow() works but sqrt() not!? In-Reply-To: References: <459d0a1c_6@news.bluewin.ch> Message-ID: <1167962119.206674.256350@11g2000cwr.googlegroups.com> On Jan 4, 10:00 am, "siggi" wrote: > Thanks for that, too! > > Would be interesting to learn how these different algorithms [for pow] influence the > precision of the result!? For an integer (i.e., int or long) x and a nonnegative integer y, x**y is exact: >>> 1000001 ** 12 1000012000066000220000495000792000924000792000495000220000066000012000001L (73 significant digits, correctly ending in "000001") math.pow uses floating-point arithmetic (even if you pass it integers), and so has limited precision: >>> print '%.73f' % math.pow(1000001, 12) 1000012000066000238472777842004463257260700063242258506335663988477526016 (Only the first 17 digits are correct.) For floats, the ** operator does the same thing math.pow does. From gagsl-py at yahoo.com.ar Mon Jan 15 18:38:21 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 20:38:21 -0300 Subject: can't get import to work! In-Reply-To: <8C906E2A183C0C2-B34-FE5@WEBMAIL-RA03.sysops.aol.com> References: <8C906E2A183C0C2-B34-FE5@WEBMAIL-RA03.sysops.aol.com> Message-ID: <7.0.1.0.0.20070115203611.05c7bc98@yahoo.com.ar> At Monday 15/1/2007 14:35, corsairdgr at aol.com wrote: >from just.for.fun import Fubar >This doesn't work. The following error is displayed: > ImportError: No module named for You can't have a module named "for", it's a reserved word. Try using "For" instead (or any other legal name!). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bdesth.quelquechose at free.quelquepart.fr Fri Jan 12 12:18:13 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Jan 2007 18:18:13 +0100 Subject: ArchGenXML please help In-Reply-To: References: Message-ID: <45a7bc70$0$299$426a34cc@news.free.fr> tonydevlin a ?crit : > I am creating a workflow in plone using argouml and archgenxml. I have been > following the steps on the site:- > http://plone.org/documentation/tutorial/anonymously-adding-custom-content-types-with-argouml-and-archgenxml/creating-a-class-and-workflow-with-argouml > > However I am confused at step 9 in creating the class section, where it > says: > "Now, save this file as "ProcessImprovement.zargo". Pull up a command > prompt and navigate to that directory. Make sure that you've added the > ArchGenXML directory to your env path, and type the following: > C:\Sandbox\Plone\Tutorial>ArchGenXML.py ProcessImprovement.zargo" > > I have saved the file in the location > C:\Documents and Settings\Tony\Desktop\Test\ProcessImprovement.zargo > However I dont know what to type in the python command prompt!!! Which *python* command prompt ? The author is talking about a shell, here (you know, this strange stuff that looks like good ole time DOS...). From robert.kern at gmail.com Sat Jan 20 19:32:45 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 20 Jan 2007 18:32:45 -0600 Subject: scipy.optimize.lbfgsb help please!!! In-Reply-To: References: Message-ID: mclaugb wrote: > Just to clarify--this is a multivariate algorithm. Yes. That means that the domain of the objective function is multivariate. The image is still a scalar. RR^n -f-> RR > I changed the function > Permmin to simply take the absolute value of (xmin, ymin) so that it returns > one value. Unfortunately, the error remains--it still returns this error: Let's take this to the scipy-user list. Can you reduce your code down to a small, complete example that demonstrates the problem? Without more information, we can't help you. Also, we'll need to know what version of scipy you are using. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jan 25 10:31:06 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 25 Jan 2007 16:31:06 +0100 Subject: Please have a look at this class In-Reply-To: <1169735908.009109.7460@a75g2000cwd.googlegroups.com> References: <1169735908.009109.7460@a75g2000cwd.googlegroups.com> Message-ID: <45b8cd37$0$25927$426a74cc@news.free.fr> antred a ?crit : > Hello everyone, > > While working on a program I encountered a situation where I'd > construct a largish data structure (a tree) from parsing a host of > files and would end up having to throw away parts of my newly built > tree if a file turned out to contain invalid data. My first thought was > 'Well, you can always make a deep copy of your tree first, then add new > data to the copy and revert to the original if you need to.", but as > this tree can grow very big this is not exactly efficient. > So my second idea was to come up with a class that offers a very > limited degree of database-like behavior, meaning you can make changes > to the object and then decide whether you want to commit those changes > or roll them back to get back to the original. Then you may want to have a look at the zodb (and possibly Durus - it has support for transactions too IIRC) instead of reinventing the square wheel. From cinsky at gmail.com Tue Jan 9 01:39:55 2007 From: cinsky at gmail.com (cinsky at gmail.com) Date: 8 Jan 2007 22:39:55 -0800 Subject: class unbound method and datetime.datetime.today() Message-ID: <1168324795.850400.65150@i15g2000cwa.googlegroups.com> Hi, I got confused when I learned the function datetime.today(). So far I learned, unless an instance is created, it is not possible to call the class method. For example: class Foo: def foo(self): pass Foo.foo() # error: unbound method foo(). What makes me confused is that datetime class? in datetime module provides today() function that returns the datetime object. >>> import datetime >>> datetime.datetime.today() datetime.datetime(2007, 1, 9, 15, 34, 35, 23537) It looks like that datetime class provides today() method that can be callable even if it is unbound method. Do I correct? If it is possible to make that kind of function (looks like static member function in C++), how can I make that? Thanks in advance. From Hieu.D.Hoang at gmail.com Tue Jan 30 23:08:28 2007 From: Hieu.D.Hoang at gmail.com (Hieu.D.Hoang at gmail.com) Date: 30 Jan 2007 20:08:28 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170108446.671609.169400@j27g2000cwj.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170088693.768440.26580@h3g2000cwc.googlegroups.com> <1170090408.495646.85720@v33g2000cwv.googlegroups.com> <1170108446.671609.169400@j27g2000cwj.googlegroups.com> Message-ID: <1170216508.396176.187780@v33g2000cwv.googlegroups.com> On Jan 30, 5:07 am, "NoName" wrote: > WOW! :shock: > > in this case: > > while 1:i=__import__;print > i('binascii').b2a_base64(i('os').urandom(6)),;raw_input() > > > :) raw_input can do the job of print while 1: raw_input(__import__('os').urandom(6).encode('base64')) And can anyone explain why this is so? >>> while 1: input(__import__('os').urandom(6).encode('base64')) ... BgiWdv// Traceback (most recent call last): File "", line 1, in File "", line 0 ^ SyntaxError: unexpected EOF while parsing Thank to all, I learned a lot of new things from this thread. Hieu From harry.g.george at boeing.com Wed Jan 24 13:54:34 2007 From: harry.g.george at boeing.com (George, Harry G) Date: Wed, 24 Jan 2007 10:54:34 -0800 Subject: Python does not play well with others In-Reply-To: <20070124180439.GA18506@hccnet.nl> Message-ID: <8CCB8060D46A7A40BC6AB3DC1DCAFABC03599CD1@XCH-NW-8V2.nw.nos.boeing.com> As always, IMHO... P-code begat JVM, which begat .NET/Mono-CLI, wherein lives C#. Thus it is a deliberately isolated world, much given to reinventing wheels (or rather recoding them) instead of binding to existing libraries. So C# might be a useful tool for anyone forced to live inside that world, but more or less irrelevant for those who have to interact with the real world. At work my tasks include hooking together lots of COTS tools, on lots of platforms. C# doesn't even play the game. At home my hobbies include lots of different subjects, randomly passing from one to another, using strictly Open Source Software, and enjoying the process. .NET/Mono and C# don't pass either the "lots" or the "enjoy" tests. > -----Original Message----- > From: egbert [mailto:egbert.bouwman at hccnet.nl] > Sent: Wednesday, January 24, 2007 10:05 AM > To: George, Harry G > Cc: python-list at python.org > Subject: Re: Python does not play well with others > > On Wed, Jan 24, 2007 at 06:24:37AM +0000, Harry George wrote: > > > > Perl - excellent modules and bindings for just about everything ... > > Java - a world of its own. They reinvent the wheel instead of ... > > PHP - are we talking web scripts or serious programs? Are you ... > > C - the portable assembler. Solid, trusted, tunable ... > > C++ - objects tacked onto C; but that didn't work so invent ... > > Python - it just works. Same scripts run on every platform ... > > What about C# ? > e > -- > Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - > 020 6257991 > ============================================================== > ========== > From wolfgang.grafen at marconi.com Wed Jan 31 03:46:56 2007 From: wolfgang.grafen at marconi.com (Wolfgang Grafen) Date: Wed, 31 Jan 2007 09:46:56 +0100 Subject: Find and replace in a file with regular expression In-Reply-To: <1170186744.322855.253550@j27g2000cwj.googlegroups.com> References: <1170186744.322855.253550@j27g2000cwj.googlegroups.com> Message-ID: Just in case you didn't think about it there is a plain replace method for strings How to quick-search this method with 'dir' >>> dir("") ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> help("".replace) Help on built-in function replace: replace(...) S.replace (old, new[, maxsplit]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument maxsplit is given, only the first maxsplit occurrences are replaced. and now how to apply it: new_text = open(fileName).read().replace("SOURCE", "REPLACE") which is the preferred method for a simple task like this. TOXiC wrote: > Hi everyone, > First I say that I serched and tryed everything but I cannot figure > out how I can do it. > I want to open a a file (not necessary a txt) and find and replace a > string. > I can do it with: > > import fileinput, string, sys > fileQuery = "Text.txt" > sourceText = '''SOURCE''' > replaceText = '''REPLACE''' > def replace(fileName, sourceText, replaceText): Now how to solve it with a simple regular expression: >>> import re >>> re_replace = re.compile("SOURCE").sub >>> >>> txt = " SOURCE SOURCE \n SOURCE " >>> >>> print re_replace("REPLACE", txt) ' REPLACE REPLACE \n REPLACE ' >>> new_text = re_replace("REPLACE", open(fileName).read()) A regular expression for this task is kind of overkill. Mastering regular expression is the efford very worth. Wolfgang Grafen From felipe.lessa at gmail.com Sun Jan 7 16:47:10 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 7 Jan 2007 19:47:10 -0200 Subject: how to find the longst element list of lists In-Reply-To: References: Message-ID: On 1/7/07, Michael M. wrote: > How to find the longst element list of lists? s1 = ["q", "e", "d"] s2 = ["a", "b"] s3 = ["a", "b", "c", "d"] s = [s1, s2, s3] s.sort(key=len, reverse=True) print s[0] is s3 print s[1] is s1 print s[2] is s2 sx1, sx2, sx3 = s print 'sx1:', sx1 print 'sx2:', sx2 print 'sx3:', sx3 -- Felipe. From david at boddie.org.uk Tue Jan 16 18:41:27 2007 From: david at boddie.org.uk (David Boddie) Date: Wed, 17 Jan 2007 00:41:27 +0100 Subject: PyQt: QListviewItemIterator References: Message-ID: <54a5f$45ad62a8$54d1d767$17614@news.chello.no> On Tuesday 16 January 2007 18:57, Tina I wrote: > I have a QListView with a number of columns. In order to filter the > output I iterate using QListViewItemIterator looking for the string > entered by the user (filterString). Currently I do it this way: [Reformatted code for quoting purposes] > it = QListViewItemIterator(self.authListView) > try: > while it: > item = it.current() > if item.text(0).contains(filterString) or \ > item.text(1).contains(filterString) or \ > item.text(2).contains(filterString): > > item.setVisible(1) > else: > item.setVisible(0) > it +=1 > except AttributeError: > pass > > Basically I iterate through the ListView until it goes beyond the list > and raise an exception, which I catch. It works but to be honest it > looks and feels ugly; "Do something until it goes wrong" > > So, question: How can I know I have reached the last item in the > QListView? When it.current() returns None. You can rewrite what you already have like this: it = QListViewItemIterator(self.authListView) while it.current(): item = it.current() if item.text(0).contains(filterString) or \ item.text(1).contains(filterString) or \ item.text(2).contains(filterString): item.setVisible(1) else: item.setVisible(0) it += 1 If you don't like calling item.current() twice for some reason, you could write this: it = QListViewItemIterator(self.authListView) item = it.current() while item: if item.text(0).contains(filterString) or \ item.text(1).contains(filterString) or \ item.text(2).contains(filterString): item.setVisible(1) else: item.setVisible(0) it += 1 item = it.current() David From vertilka at gmail.com Thu Jan 4 07:50:19 2007 From: vertilka at gmail.com (Vertilka) Date: 4 Jan 2007 04:50:19 -0800 Subject: Extending Embedded Python and execute external script Message-ID: <1167915019.940396.322390@s34g2000cwa.googlegroups.com> What i need from my C application to do ? 1) To execute a python script from file. 2) The python script will call functions in my C application. According to the answer from Ravi Teja (topic "C app and Python"), I need to extend embedded python in my C application. I saw several functions: PyRun_AnyFileExFlags, PyRun_SimpleFileExFlags, PyRun_FileExFlags. Questions: 1) Which one should i use in order to achieve what i need ? 2) I couldn't understand the differance betwwen the three ? 3) What is the difference between the "FILE *fp" and "const char *filename" arguments of these functions. If i give a FILE*, why do i need to give the file name ? Tnx, Vertilka From ralf at schoenian-online.de Mon Jan 15 22:59:32 2007 From: ralf at schoenian-online.de (=?ISO-8859-1?Q?Ralf_Sch=F6nian?=) Date: Tue, 16 Jan 2007 04:59:32 +0100 Subject: Python web app. (advice sought) In-Reply-To: References: <45aae51b.0@entanet> Message-ID: <45ac4d95$1@news.arcor-ip.de> Tim Williams schrieb: > On 15 Jan 2007 00:52:33 -0800, Torabisu wrote: > > Don't overlook Karrigell either, with a tiny learning curve its > always worth consideration, especially if you need rapid development > and a web server that will sit on top of your exising .py modules. > > www.karrigell.com > > hth :) I would also like to vote for Karrigell. BTW: Does anyone knows how to avoid stopping/starting of the webserver after changing external libraries? I have some own modules under /opt/local/python/lib and import them by extending the path with sys.path.append() After changing any file here, I have to restart Karrigell. Ralf Schoenian From gagsl-py at yahoo.com.ar Fri Jan 19 14:20:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Jan 2007 16:20:17 -0300 Subject: My first try using logger didn't work. Why? In-Reply-To: <1169233154.076956.231540@q2g2000cwa.googlegroups.com> References: <1169221734.071338.107190@11g2000cwr.googlegroups.com> <1169224835.820468.316040@v45g2000cwv.googlegroups.com> <1169233154.076956.231540@q2g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070119160825.01da8b80@yahoo.com.ar> At Friday 19/1/2007 15:59, CedricCicada at gmail.com wrote: >One of the problems I was laboring under was that I did not know where >to go to find the official documentation. Thanks for that link too! You already have it installed; look into your python install directory, under "doc" From inside the interpreter, you can use help(): py> import logging.handlers py> help(logging.handlers.NTEventLogHandler) Help on class NTEventLogHandler in module logging.handlers: class NTEventLogHandler(logging.Handler) | A handler class which sends events to the NT Event Log. Adds a | registry entry for the specified application name. If no dllname is | provided, win32service.pyd (which contains some basic message [...] Try help("logging"), help("modules logging"), help(any object), help("if") And you can read the documentation online at http://www.python.org/doc/ -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bytter at gmail.com Tue Jan 30 10:05:23 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Tue, 30 Jan 2007 15:05:23 +0000 Subject: Synchronous shutil.copyfile() Message-ID: <4e8efcf50701300705v2b787ec4h1c539cab8068d58c@mail.gmail.com> Hi there, I have a problem. I'm using calling shutil.copyfile() followed by open(). The thing is that most of the times open() is called before the actual file is copied. I don't have this problem when doing a step-by-step debug, since I give enough time for the OS to copy the file, but at run-time, it throws an exception. Is there anyway to force a sync copy of the file (make python wait for the completion)? Thanks in advance! Hugo Ferreira From bruno.desthuilliers at websiteburo.com Wed Jan 24 09:40:27 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Wed, 24 Jan 2007 15:40:27 +0100 Subject: Thoughts on using isinstance In-Reply-To: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> Message-ID: <45b76f9b$0$16806$426a74cc@news.free.fr> abcd a ?crit : > In my code I am debating whether or not to validate the types of data > being passed to my functions. For example > > def sayHello(self, name): > if not name: > rasie "name can't be null" > if not isinstance(name, str): > raise "name must be a string" > print "Hello " + name > > Is the use of isinstance a "bad" way of doing things? Mostly, yes. Python is dynamically typed (well, it's dynamic all the way...), and fighting against the language is a bad idea. Also, since the use of an object of non-compatible type would usually raise an exception (and while we're at it, avoid using strings as exceptions - better to use some Exception class), you don't actually gain anything. > just curious how you might handle this type of situation (other than > not validating at all). There are mostly 2 cases : 1/ you're getting data from the outside world. Here, you have to be *very* careful, and you usually need more than simple validation. Good news is that we have modules like FormEncode designed to handle this case. 2/ you're getting 'data' from within your Python program. If you correctly applied 1/, whatever comes in should be ok - that is, unless you have a programmer error !-). But then, you'll usually have a nice exception and traceback (or better unit tests failures), so you can fix the problem immediatly. Now there are *a few* corner cases where it makes sens to check what has been passed to a function - either because there are very strict and stable requirements here, or because the function can accept different kinds of objects, but needs to handle them in distinct ways. MVHO is that the less code the better. As a matter of fact, trying to 'protect' your function, you introduced a syntax error, that would not have been here if you had just wrote the simplest thing: def say_hello(who): print "Hello", who My 2 cents... From martin at v.loewis.de Thu Jan 25 01:29:05 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 25 Jan 2007 07:29:05 +0100 Subject: raise UnicodeError, "label too long" In-Reply-To: <1169684719.607504.307310@l53g2000cwa.googlegroups.com> References: <1169672223.231030.262610@l53g2000cwa.googlegroups.com> <1169675004.099912.79520@v33g2000cwv.googlegroups.com> <45B7D4F7.9020308@v.loewis.de> <1169684719.607504.307310@l53g2000cwa.googlegroups.com> Message-ID: <45B84E31.4090605@v.loewis.de> Flavio schrieb: > something like this, for instance: > http://.wikipedia.org/wiki/Copper%28II%29_hydroxide > > but even url with any non-ascii characters such as this > > http://.wikipedia.org/wiki/Ammonia > > also fail when passed to urlopen : > File "/usr/lib/python2.4/encodings/idna.py", line 72, in ToASCII > raise UnicodeError, "label too long" > UnicodeError: label too long > > very strange, because I tried other unicode urls from the python > console like this It's the host name that starts with a dot that makes it fails: py> u".wikipedia.org".encode("idna") Traceback (most recent call last): File "", line 1, in ? File "encodings/idna.py", line 163, in encode File "encodings/idna.py", line 72, in ToASCII UnicodeError: label too long py> u"wikipedia.org".encode("idna") 'wikipedia.org' The exception is certainly misleading; I'll have to find out whether there is a bug beyond that (i.e. whether host names with empty labels should be accepted). Regards, martin From webraviteja at gmail.com Tue Jan 2 13:18:45 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 2 Jan 2007 10:18:45 -0800 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: <1167761925.552432.305350@k21g2000cwa.googlegroups.com> > > > > How about invoking scripts with SUID root set? > > Linux seems to ignore SUID bit on scripts: Yes. My bad. The work around was to use native launchers. I don't remember the details. Perhaps with the interpreter embedded to launch it in-process and to hard code the script paths (or at least a config file/script pointing to them) for security. > Anyway, you should definitely think about security issues. Not all > people out there are friendly... I agree. SUID is often risky. Web applications such as webmin that do administrative functions through a web interface require extra precautions for security such as restricting access to specific IPs. From bjourne at gmail.com Thu Jan 25 04:08:01 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 25 Jan 2007 10:08:01 +0100 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <740c3aec0701250108m48d80ef7k743cb5e13dc92bba@mail.gmail.com> On 1/24/07, Harry George wrote: > Python - it just works. Same scripts run on every platform. Bindings > available to every C/C++/FORTRAN library I've needed so far. Often > the bindings are not complete, but oddly enough the binding developers > have chosen to do just the functions I need, so who cares. A clean > architecture for adding more function bindings if I'm so inclined. Although that is true on Linux, it is often not the case on Windows. Sometimes the binding lacks a binary for the minor version of Python you use or it depends on something which depends on something which sometimes is only available in source form. Still, I would rather take Python's approach than Java's. -- mvh Bj?rn From Jeff.Demel at JavelinDirect.com Thu Jan 11 17:42:34 2007 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Thu, 11 Jan 2007 16:42:34 -0600 Subject: Learning Python book, new edition? Message-ID: <136ED738BD4F1545B97E4AC06FF6370734C195@DMSP-MSG-EVS01.mail.pvt> John wrote: >So what happens with google bots etc... Information provided >in the email could be helpful to others that are NOT the original > recipient. And what happens to the archive stuff? I will forward your response to our crack legal department. Perhaps they can help you with your very astute questions. -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From half.italian at gmail.com Thu Jan 25 04:46:06 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 25 Jan 2007 01:46:06 -0800 Subject: Fast Imaging for Webserver In-Reply-To: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> References: <1169707586.701908.32860@v45g2000cwv.googlegroups.com> Message-ID: <1169718365.937350.79270@13g2000cwe.googlegroups.com> On Jan 24, 10:46 pm, "Prateek" wrote: > Hi. I'm creating a web-application using CherryPy 2.2.1. My application > needs to process images (JPG/PNG files) to > > 1) create thumbnails (resize them) > 2) overlay them on a custom background (a simple frame) > 3) Overlay 'badges' (small 16x16 images) on top of the final thumbnail > > I am using PIL 1.1.5 which I have custom compiled on my development > machine (MacBook Pro 2.33Ghz Core Duo).. > I am using im.thumbnail for step 1 and im.paste for steps 2 and 3. > > The problem is that this thing is just way too slow. > For ab -n 1000 -C session_id=2f55ae2dfefa896f67a80f73045aadfa4b4269f1http://localhost:8080/imaging/icon/def/128/255(where def is the name > of the image - default in this case - 128 is the size in pixels and 255 > is the background color), I am getting: > > Document Path: /imaging/icon/def/128/255 > Document Length: 14417 bytes > > Concurrency Level: 1 > Time taken for tests: 18.664 seconds > Complete requests: 1000 > Failed requests: 0 > Broken pipe errors: 0 > Total transferred: 14680000 bytes > HTML transferred: 14417000 bytes > Requests per second: 53.58 [#/sec] (mean) > Time per request: 18.66 [ms] (mean) > Time per request: 18.66 [ms] (mean, across all concurrent > requests) > Transfer rate: 786.54 [Kbytes/sec] received > > FYI: This request returns a PNG image (image/png) and not html > > My understanding is that the problem is either with the CherryPy setup > (which is likely because even in other cases, i don't get much more > than 65 requests per second) or PIL itself (even though I'm caching the > background images and source images) > > Does anyone have a better solution? Is there a faster replacement for > PIL? > > Thanks in advance. > Prateek Check out the mac CoreGraphics bindings. Not sure if it will be any faster, but it can do what you want. http://www.macdevcenter.com/pub/a/mac/2004/03/19/core_graphics.html ~Sean DiZazzo From bborcic at gmail.com Wed Jan 24 06:29:09 2007 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 24 Jan 2007 12:29:09 +0100 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> Message-ID: Chris Mellon wrote: > On 1/23/07, Boris Borcic wrote: >> ...A simple - >> with Tkinter or otherwise - way to wrap access to the MS Windows UI text >> rendering engine, as a function that would return a picture of rendered text, >> given a string, a font, a size and colors ? ... > > There are actually several different text rendering methods (and 2 or > more totally different engines) and they will give different results, > so if you want a fully generic solution that could be quite difficult. > However, it sounds like this is for a specific purpose. Indeed. > > ...You could also use > wxPython, which uses what will probably be the right API and will take > less code than win32 will. I'd suggest this if you aren't familiar > with the win32 API. Thanks for your guidance and quick code, I am going to try that. Boris Borcic From thn at mail.utexas.edu Mon Jan 8 13:59:23 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 8 Jan 2007 10:59:23 -0800 Subject: newbieee In-Reply-To: <1168280831.323496.277020@38g2000cwa.googlegroups.com> References: <1168280831.323496.277020@38g2000cwa.googlegroups.com> Message-ID: <1168282763.275854.145430@v33g2000cwv.googlegroups.com> lee wrote: > I getting familiarised with python...can any one suggest me a good > editor available for python which runs on windows xp....one more > request guys...can nyone tell me a good reference manual for python.. I think vim is a very good editor for python, and it's certainly available for windows xp. O'reilly has a book called Programming Python that covers much of the standard library and how to use it for complex tasks. It may be out of date by now, though. Truthfully the only python references I use regularly are the online docs and this list. hth, THN From mkeller.dci at gmail.com Thu Jan 25 07:37:34 2007 From: mkeller.dci at gmail.com (mukappa) Date: 25 Jan 2007 04:37:34 -0800 Subject: Subclassing cElementTree.XMLTreeBuilder In-Reply-To: References: <1169695233.737016.95950@a75g2000cwd.googlegroups.com> Message-ID: <1169728653.989858.218650@a75g2000cwd.googlegroups.com> On Jan 25, 4:32 am, "Fredrik Lundh" wrote: > "mukappa" wrote: > > Is it possible to subclass cElementTree.XMLTreeBuilder?no, it's a factory function. if you need to extend it, you'll have to wrap it. but > I'm not sure I see the use case; what is it you're trying to do here? > > I'm trying to parse xmpp stanzas coming in over a socket. Since cElementTree is more efficient, I would like to use it when available. Here is what I have now: import logging from elementtree import ElementTree class StanzaTreeBuilder(ElementTree.XMLTreeBuilder): """Capture stanza elements ( children) from parser events. Private methods are lifted from the old elementtree.XMLTreeBuilder.FancyTreeBuilder """ def __init__(self, html=0): """Initialize state variables.""" ElementTree.XMLTreeBuilder.__init__(self, html) self._parser.StartNamespaceDeclHandler = self._start_ns self._parser.EndNamespaceDeclHandler = self._end_ns self.namespaces = [] self.level = 0 self.stanza = None self.streamelem = None def _start(self, tag, attrib_in): elem = ElementTree.XMLTreeBuilder._start(self, tag, attrib_in) self.start(elem) def _start_list(self, tag, attrib_in): elem = ElementTree.XMLTreeBuilder._start_list(self, tag, attrib_in) self.start(elem) def _end(self, tag): elem = ElementTree.XMLTreeBuilder._end(self, tag) self.end(elem) def _start_ns(self, prefix, value): self.namespaces.insert(0, (prefix, value)) def _end_ns(self, prefix): assert self.namespaces.pop(0)[0] == prefix, "implementation confused" def start(self, element): """Track nesting level (capture open on first call).""" logging.debug("start(%s): %s" % (self.level, ElementTree.tostring(element))) if self.streamelem is None: assert element.tag == "http://etherx.jabber.org/streams" self.streamelem = element self.stanza = element self.level += 1 def end(self, element): """Capture stanza when nesting level is 1.""" self.level -= 1 if self.level == 1: self.stanza = element self.streamelem.clear() logging.debug("end(%s): %s" % (self.level, ElementTree.tostring(element))) def stanzagen(socket): """Yield open on first call, then complete stanzas. Caller needs 'id' from the opening , then he needs stanzas, one per call. Works by parsing the socket one byte at a time, and yielding complete stanza at earliest opportunity (or None if none waiting), exits on EOF. Stanzas are returned as ElementTree Elements to give them a natural pythonic feel. see http://online.effbot.org/2004_12_01_archive.htm#element-generator""" p = StanzaTreeBuilder() data = None while 1: try: data = socket.recv(1) if not data: logging.info("EOF from peer") p.close() break p.feed(data) if p.stanza is not None: yield p.stanza p.stanza = None data = None except: if data is not None: logging.error("error reading: %s" % (data)) raise else: yield None From mail at microcorp.co.za Sat Jan 13 00:38:39 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 13 Jan 2007 07:38:39 +0200 Subject: General Question About Python References: <1168254451.098796.144790@42g2000cwt.googlegroups.com><1168336603.962731.5470@11g2000cwr.googlegroups.com><1168337298.574881.121470@i15g2000cwa.googlegroups.com> <1168586849.047301.301680@s34g2000cwa.googlegroups.com> Message-ID: <008001c736db$0ca49980$03000080@hendrik> "Torabisu" wrote: > > billie wrote: > > Torabisu wrote: > > > > > Its quite weird, we're looking for Python skills but are battling to > > > find at the moment... Normally Python on its own will probably not > > > land you a job, but the last two companies I've worked for are doing > > > indepth Python development, so hopefully the tables are turning a bit. > > > > I can tell the same for Italy. > > Where are you from? > > Cape Town, South Africa. There is a strong Unix following here, but > more on the System Administration side, not really the software > development side with regards to Python. Python more being used for > task automation and shell scripting. What do you want done? - I am only a thousand miles away... - Hendrik From stou.sandalski at gmail.com Thu Jan 18 19:12:19 2007 From: stou.sandalski at gmail.com (Stou Sandalski) Date: 18 Jan 2007 16:12:19 -0800 Subject: Pass 'this' to a python script in an extended application Message-ID: <1169165539.529443.289120@v45g2000cwv.googlegroups.com> Hi, I have an application consisting of a main C++ class (and other classes) stored inside a DLL. The application uses a small main executable that links against the main DLL, then initializes and runs the core class. The python bindings are inside a .pyd module that also links against the core DLL file. I was able to generate the python bindings against the core class using SWIG. The application can now be run either by the bootstrap executable or through the python console like: import foo s = foo.MainClass() s.run(); This is awesome, however I want to be able to launch python scripts from within the application itself (no matter how it was started) and supply these scripts with a "pointer" to the already initialized main Class something like: import foo s = foo.GetMainClass() s.someMethod(). I found this: http://docs.python.org/ext/extending-with-embedding.html but the problem is that I don't know how to "give" the python interpreter a "pointer" to my class that will be compatible with the already defined bindings that SWIG generated. I am trying to keep the core application dll from knowing about the .pyd extension module. I apologize if this post belongs in a group dedicated to SWIG. Stou From guettli.usenet at thomas-guettler.de Tue Jan 30 10:44:30 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 30 Jan 2007 15:44:30 GMT Subject: thread and processes with python/GTK References: <1170151634.019690.320310@k78g2000cwa.googlegroups.com> Message-ID: <5297euF1ndifjU1@mid.individual.net> Hi, how do you start the python app? Goes stdout to a terminal or a pipe? "python script.py" and "python script.py | cat" behave different. Maybe "sys.stdout.flush()" helps you. BTW, I switched from threads to idle_add for pygtk applications. awalter1 wrote: > Hello, > > I'm developping an application with python, pyGTK and GTK+. > I've performed many tests by using methods as Popen, popen2, > os.system ... to communicate with Unix (HPUX), > The last attempt is this code written in a thread : > fin,fout = popen2.popen2('ps -def') > line = fin.readline() > while 1 : > if not line : break > print "line=",line > line = fin.readline() > fin.close() > In that case, lines are printed only when I exit my application. > Usually the behavior is not as expected and I cannot understand why. I > am wondering that it could be a constraint from the use of GTK > (mainloop() existence ???). > Is somebody aware about conflict between GTK use and unix mechanism. > > Thanks for you help -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From m.elston at advantest-ard.com Fri Jan 5 16:05:02 2007 From: m.elston at advantest-ard.com (Mark Elston) Date: Fri, 05 Jan 2007 13:05:02 -0800 Subject: strange for loop construct In-Reply-To: References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> Message-ID: <12ptf5bl21f2teb@corp.supernews.com> * Gabriel Genellina wrote (on 1/5/2007 12:49 PM): > At Friday 5/1/2007 17:39, Sardaukary at gmail.com wrote: > >> wordfreq = [wordlist.count(p) for p in wordlist] >> >> I would expect >> >> for p in wordlist: >> wordfreq.append(wordlist.count(p)) >> >> >> I didn't know you could have an expression in the same line. > > That's known as a "list comprehension" and is roughly equivalent to your > code. Section 5 of the tutorial covers them. > http://docs.python.org/tut/node7.html > > If you have a Python installation you should be able to find the "Whats New" section of the docs. List comprehensions are described pretty well in the "What's new in Python 2.0?" section. This gives some simple examples as well as the rationale behind them. Mark From gagsl-py at yahoo.com.ar Thu Jan 25 02:00:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 04:00:36 -0300 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <7.0.1.0.0.20070125035706.044d1b50@yahoo.com.ar> At Thursday 25/1/2007 03:39, Dennis Lee Bieber wrote: >On Wed, 24 Jan 2007 19:04:39 +0100, egbert >declaimed the following in comp.lang.python: > > > On Wed, Jan 24, 2007 at 06:24:37AM +0000, Harry George wrote: > > > > > > Perl - excellent modules and bindings for just about everything ... > > > Java - a world of its own. They reinvent the wheel instead of ... > > > PHP - are we talking web scripts or serious programs? Are you ... > > > C - the portable assembler. Solid, trusted, tunable ... > > > C++ - objects tacked onto C; but that didn't work so invent ... > > > Python - it just works. Same scripts run on every platform ... > > > > What about C# ? > > Uhm... Unless something has happened that I don't know about, isn't >C# a M$ specific product? Not exactly. It's defined by an ISO standard; there are several implementations apart from MS, like Borland C# Builder and the Mono project. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tomas at fancy.org Wed Jan 3 03:08:58 2007 From: tomas at fancy.org (Tom Plunket) Date: Wed, 03 Jan 2007 00:08:58 -0800 Subject: list/dictionary as case statement ? References: Message-ID: <71pmp2tq1klma5urhkfiv8bpq6u8sgtj06@4ax.com> Hendrik van Rooyen wrote: > It works well - and it is surprisingly fast too... > And its easy if the opcodes are all say one byte, > else you need an opcode length field too, and fancier > parsing. Often (always?) RISC architectures' instruction+operand lengths are fixed to the word size of the machine. E.g. the MIPS 3000 and 4000 were 32 bits for every instruction, and PC was always a multiple of four. ...which means the parsing is pretty straight forward, but as you say, simulating the rest of the machine is the hard part. -tom! -- From S.Mientki-nospam at mailbox.kun.nl Sun Jan 28 14:44:51 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 28 Jan 2007 20:44:51 +0100 Subject: howto redirect and extend help content ? In-Reply-To: References: <1fc1a$45bcc7f4$d443bb3a$8806@news.speedlinq.nl> Message-ID: >> I'm making special versions of existing functions, >> and now I want the help-text of the newly created function to exists of > > Don't you think your users can follow this easy reference theirselves? My public consist of physicians with some knowledge of MatLab. I'm trying to give them a system (based on Python) for which no knowledge of Python is needed. When they put the cursor on the name of a function (in some pre-processing language, preferably something like LabView), the help text will be shown automatically in a separate window, without typing any commands. cheers, Stef Mientki From nagle at animats.com Thu Jan 18 02:41:59 2007 From: nagle at animats.com (John Nagle) Date: Thu, 18 Jan 2007 07:41:59 GMT Subject: More M2Crypto issues Message-ID: I've been running M2Crypto successfully using Python 2.4 on Windows 2000, and now I'm trying to get it to work on Python 2.3.4 on Linux. Attempting to initialize a context results in Traceback (most recent call last): File "/www/htdocs/sitetruth.com/cgi/ratingdetails.cgi", line 46, in ? DetailsPageBuilder.detailspage(kdbfile,ktemplatefile,url) # check and display domain or URL as web page File "./sitetruth/DetailsPageBuilder.py", line 70, in detailspage sitecert = InfoSSL2.Certificate(siteinfo, kverifylocations, verbose) File "./sitetruth/InfoSSL2.py", line 147, in __init__ self.ctx = createsslcontext(trustedcafile, verbose) # Generate general SSL context File "./sitetruth/InfoSSL2.py", line 40, in createsslcontext ctx = SSL.Context('sslv3') # Create context with SSL params File "/home/sitetruth/lib/python/M2Crypto/SSL/Context.py", line 43, in __init__ map()[long(self.ctx)] = self ValueError: invalid literal for long(): _480e1008_p_SSL_CTX which, when I look at the code and try some test cases, seems legitimate. The cacheing code is trying to convert a reference to an object (a C object, in fact) into a "long". Python 2.4 on Windows will do that. Python 2.3.4 on Linux converts it to a string first, gets "_480e1008_p_SSL_CTX", and then tries to convert that to an integer, which fails. M2Crypto is supposed to work with Python 2.3, so this should work. John Nagle From sjmachin at lexicon.net Sat Jan 27 01:04:06 2007 From: sjmachin at lexicon.net (John Machin) Date: 26 Jan 2007 22:04:06 -0800 Subject: strip question In-Reply-To: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> References: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> Message-ID: <1169877846.370135.181110@q2g2000cwa.googlegroups.com> On Jan 27, 4:33 pm, eight02645... at yahoo.com wrote: > hi > can someone explain strip() for these : > [code]>>> x='www.example.com' > >>> x.strip('cmowz.')'example' > [/code] According to the documentation (with emphasis added): """Return a copy of the string with the *leading* and *trailing* characters removed.""" Looking at the leading edge: "w" is in the set to strip, so it is removed. Same applies to another 2 "w"s and a dot. "e" is not in the strip set so it stops. At the trailing edge: "m", "o", "c" and dot are removed, then it stops because there's another "e". > when i did this: > [code]>>> x = 'abcd,words.words' > >>> x.strip(',.')'abcd,words.words' > [/code] > > it does not strip off "," and "." .Why is this so? The comma and dot in your example are neither leading nor trailing. The leading "a" is not in the set to strip, so nothing happens at the front door. The trailing "s" is not in the set to strip, so there's no back door action either. HTH, John From nmm1 at cus.cam.ac.uk Mon Jan 8 12:59:26 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 8 Jan 2007 17:59:26 GMT Subject: Bizarre floating-point output References: <50f5snF1fb5uqU2@mid.individual.net> <1168277798.302236.184180@s34g2000cwa.googlegroups.com> Message-ID: In article <1168277798.302236.184180 at s34g2000cwa.googlegroups.com>, "Ziga Seilnacht" writes: |> |> > I think that you should. Where does it say that tuple's __str__ is |> > the same as its __repr__? |> > |> > The obvious interpretation of the documentation is that a sequence |> > type's __str__ would call __str__ on each sub-object, and its __repr__ |> > would call __repr__. |> |> How would you distinguish ['3', '2', '1'] from [3, 2, 1] in that case? Well, it's not felt necessary to distinguish those at top level, so why should it be when they are in a sequence? print "3", 3 3 3 But this whole thing is getting ridiculous. The current implementation is a bizarre interpretation of the specification, but clearly not an incorrect one. It isn't important enough to get involved in a religious war over - I was merely puzzled as to the odd behaviour, because I have to teach it, and it is the sort of thing that can confuse naive users. Regards, Nick Maclaren. From bearophileHUGS at lycos.com Wed Jan 3 15:10:55 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 Jan 2007 12:10:55 -0800 Subject: Sorting on multiple values, some ascending, some descending In-Reply-To: <1167852652.416990.158610@k21g2000cwa.googlegroups.com> References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> <1167852652.416990.158610@k21g2000cwa.googlegroups.com> Message-ID: <1167855055.615746.105410@48g2000cwx.googlegroups.com> Raymond Hettinger: > The simplest way is to take advantage of sort-stability and do > successive sorts. For example, to sort by a primary key ascending and > a secondary key decending: > L.sort(key=lambda r: r.secondary, reverse=True) > L.sort(key=lambda r: r.primary) That's probably the faster and simpler way. The following solution is probably slow, memory-hungry, and it's not tested much so it may be buggy too, but it shows my idea, and bugs can be fixed: class Inverter: def __init__(self, item, reversed=False): self.item = item self.reversed = reversed def __cmp__(self, other): if self.reversed: return cmp(other.item, self.item) else: return cmp(self.item, other.item) data = [[1, "a", "b"], [1, "b", "d"], [1, "d", "a"]] reverses = [True, False, False] print sorted(data, key=lambda subseq: map(Inverter, subseq, reverses)) Bye, bearophile From grante at visi.com Thu Jan 4 23:17:38 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 05 Jan 2007 04:17:38 -0000 Subject: What is proper way to require a method to be overridden? References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <7.0.1.0.0.20070105004837.05b36d98@yahoo.com.ar> Message-ID: <12prkb29em82cac@corp.supernews.com> On 2007-01-05, Thomas Ploch wrote: >>> I am writing a class that is intended to be subclassed. What >>> is the proper way to indicate that a sub class must override a >>> method? >> >> If any subclass *must* override a method, raise >> NotImplementedError in the base class (apart from documenting >> how your class is supposed to be used). > > I learn so much from this list. I didn't even know this error existed. And remember: even if it didn't, you could have created your own: ------------------------------foo.py------------------------------ class NotImplementedError(Exception): pass def foo(): print "hi there" msg = "there's a penguin on the telly!" raise NotImplementedError(msg) print "how are you?" foo() ------------------------------------------------------------------ $ python foo.py hi there Traceback (most recent call last): File "foo.py", line 10, in ? foo() File "foo.py", line 7, in foo raise NotImplementedError(msg) __main__.NotImplementedError: there's a penguin on the telly! A few carefully thought-out exceptions can often eliminate the need for a lot of messy code. -- Grant Edwards grante Yow! I'll show you MY at telex number if you show visi.com me YOURS... From zaz600 at gmail.com Mon Jan 29 17:07:26 2007 From: zaz600 at gmail.com (NoName) Date: 29 Jan 2007 14:07:26 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170090408.495646.85720@v33g2000cwv.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170088693.768440.26580@h3g2000cwc.googlegroups.com> <1170090408.495646.85720@v33g2000cwv.googlegroups.com> Message-ID: <1170108446.671609.169400@j27g2000cwj.googlegroups.com> WOW! :shock: in this case: while 1:i=__import__;print i('binascii').b2a_base64(i('os').urandom(6)),;raw_input() On 30 ???., 04:06, "Szabolcs Nagy" wrote: > > while > > 1:i=__import__;print''.join(i('random').choice(i('string').letters > > +'1234567890')for x in range(8)),;raw_input()while > 1:i=__import__;r='random';print''.join(i(r).choice(i('string').letters > +'1234567890')for x in`r`),;raw_input() > > even shorter: > range -> `'random'` > > :) From kylotan at gmail.com Fri Jan 12 05:01:00 2007 From: kylotan at gmail.com (Ben Sizer) Date: 12 Jan 2007 02:01:00 -0800 Subject: pygame and python 2.5 In-Reply-To: References: Message-ID: <1168596060.101670.66250@a75g2000cwd.googlegroups.com> siggi wrote: > when I rtry to install pygame (pygame-1.7.1release.win32-py2.4.exe, the most > ciurrent version I found) it requires Python 2.4! Will I really have to > uninstall my Python 2.5 and install the old Python 2.4 in order to use > pygame? For now, yes. This is a long-standing problem with Python really, requiring extensions to always be recompiled for newer versions. I usually have to wait about 6 months to a year after any new release before I can actually install it, due to the extension lag. -- Ben Sizer From fumanchu at amor.org Thu Jan 25 20:32:00 2007 From: fumanchu at amor.org (fumanchu) Date: 25 Jan 2007 17:32:00 -0800 Subject: ANN: Dejavu 1.5.0RC1 In-Reply-To: <1169748635.912754.191720@j27g2000cwj.googlegroups.com> References: <1169748635.912754.191720@j27g2000cwj.googlegroups.com> Message-ID: <1169775119.966414.141350@l53g2000cwa.googlegroups.com> On Jan 25, 10:10 am, "olive" wrote: > Do you consider a StorageManagers for Oracle ? Yes, and in fact, I already have a ticket for it: http://projects.amor.org/dejavu/ticket/59. I've downloaded Oracle 10.2g XE and played with it a little, but hit some snags right away due to its different interface. I think now that I've done a Firebird backend, I'll be a little better able to tackle an Oracle adapter. But I don't use Oracle every day, so any help is most welcome. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From aahz at pythoncraft.com Wed Jan 17 00:16:52 2007 From: aahz at pythoncraft.com (Aahz) Date: 16 Jan 2007 21:16:52 -0800 Subject: Learning Python book, new edition? References: <1168547177.121582.320840@k58g2000hse.googlegroups.com> <1168831013.218729.243020@l53g2000cwa.googlegroups.com> Message-ID: In article <1168831013.218729.243020 at l53g2000cwa.googlegroups.com>, wesley chun wrote: > >more on topic, here's a summary of Python books which are rev'd up to >2.5, categorized but not in any particular order: > >Python learning: >- Python for Dummies, Maruch, Sep 2006 That should be "Maruch & Maruch" -- my primary partner (Stef) did most of the writing, but I supplied most of the Python knowledge. It was really a joint effort, and I heartily recommend writing a book to anyone who wants to test their marriage. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Plus ca change, plus c'est la meme chose." From webraviteja at gmail.com Sat Jan 20 01:59:19 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 19 Jan 2007 22:59:19 -0800 Subject: confused on python rpc with apache, is it possible? In-Reply-To: References: <51ce8uF1k0tl5U1@mid.uni-berlin.de> Message-ID: <1169276359.477277.17930@q2g2000cwa.googlegroups.com> krishnakant Mane wrote: > On 19/01/07, Diez B. Roggisch wrote: > > > > I'm unclear why you want the apache in there in the first place. Why don't > > you just create an e.g. twisted-based XMLRPC-server, and simply let that > > run? What is the apache intended for? > > > twisted-based? what is that? what is that. > I am very new to xml-rpc so my questions may sound very basic. All you have to do is Google when you have very basic questions For example: twisted python xmlrpc > any ways apache is doing nothing in there but I thought that if some > thing needs to be done in php in the future then apache better be > there but as I said that is no need if pythone can do it on a stand > alone basis. Use mod_python with some xmlrpc handler. There is more than one around. Google for them. That way you can keep Apache for both Python and PHP. Ravi Teja. From mohan.us2010 at gmail.com Tue Jan 9 08:10:24 2007 From: mohan.us2010 at gmail.com (mohan) Date: 9 Jan 2007 05:10:24 -0800 Subject: Using with CSV library in Python 2.2!!! Message-ID: <1168348224.843657.27330@42g2000cwt.googlegroups.com> Hi Guys, I'm back one more basic question, this time on using CSV (Comma Seperated Value) library with Python 2.2. At my workplace I have Python 2.2 installed and am using PythonWin 2.2.1 IDE from Mark Hammond. I want to use the CSV library module for reading data from the .csv files and when I try to import the module, I get the error "CSV module is not found". The reason, CSV module is missing from the Python root directories. Now my first question is, 1. Does Python 2.2 come with CSV library module or not? If yes, have I lost it somewhere?? 2. If Python 2.2 does not come with CSV module, is it possible to add the CSV module to the Python root and start working?? 3. If yes, where do I get this module from?? Would be glad to have an answer for these questions. Thanks in advance. Cheers, Mohan. From anand at soe.ucsc.edu Tue Jan 30 13:55:09 2007 From: anand at soe.ucsc.edu (Anand Patil) Date: Tue, 30 Jan 2007 10:55:09 -0800 Subject: C extension module causes bus error on Python exit In-Reply-To: <1170175431.34.2844@mint-julep.mondoinfo.com> References: <45BE9B6D.5060407@cse.ucsc.edu> <1170175431.34.2844@mint-julep.mondoinfo.com> Message-ID: <45BF948D.7040702@cse.ucsc.edu> Hi all, I was referred to this list from python-help. I've written an extension module in C which contains several new types. The types can be instantiated, used, and deleted under Python 2.4.3 on OS X 10.4 without problems. However, whenever I import the module Python tries to dereference a NULL pointer and crashes *at exit*, whether or not I've instantiated any of the types. I've searched for memory leaks with gc.get_objects and Mac OS's MallocDebug utility, but haven't found any evidence. Has anyone run into a problem like this? Any help is greatly appreciated. Thank you, Anand Patil From imageguy1206 at gmail.com Tue Jan 23 15:06:35 2007 From: imageguy1206 at gmail.com (imageguy) Date: 23 Jan 2007 12:06:35 -0800 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <45b6231b$1_2@news.bluewin.ch> References: <45b6231b$1_2@news.bluewin.ch> Message-ID: <1169582795.882496.209750@a75g2000cwd.googlegroups.com> > I am trying to use UI Automation to drive an MS Windows app (with pywinauto). > > I need to scrape the app's window contents and use some form of OCR to get at > the texts (pywinauto can't get at them). > > As an alternative to integrating an OCR engine, and since I know the fonts and > sizes used to write on the app's windows, I reasoned that I could base a simple > text recognition module on the capability to drive MSWindows text rendering - eg > to generate pixmaps of texts I expect to find in the driven app's windows, exact > to the pixel. > > The advantage of that approach would be exactitude and self-containment. > > I've verified manually inside an Idle window, that indeed I could produce > pixmaps of expected app texts, exact to the pixel (with Tkinter+screen capture > at least). > > I could use help to turn this into a programmable capability, ie : A simple - > with Tkinter or otherwise - way to wrap access to the MS Windows UI text > rendering engine, as a function that would return a picture of rendered text, > given a string, a font, a size and colors ? > > And ideally, without interfering with screen contents ? > > Thanks in advance for any guidance, > > Boris Borcic I was looking for ( and still am searching for) similiar functionality. Specifically I would like to be able to capture a small area of the screen (a number or a code) and convert this to text that can be used in my application. When I asked my question, I was directed to the Microsoft Accessibility tool kit. Serach on this list for the post titled; "Reading text labels from a Win32 window" I work with wxPython and Win32 applications exclusively. So if I can be of any help or assistance, please let me know. Geoff. From steve at REMOVE.THIS.cybersource.com.au Sun Jan 7 17:10:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Jan 2007 09:10:38 +1100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 07 Jan 2007 04:09:13 -0800, Paul Rubin wrote: > "Felipe Almeida Lessa" writes: >> What is the chance of having to inherit from two classes from >> different modules but with exactly the same name *and* the same >> instance variable name? >> >> Of course you're being very pessimistic or extremely unlucky. > > If you want to write bug-free code, pessimism is the name of the game. I wonder whether Paul uses snow chains all year round, even in the blazing summer? After all, "if you want to drive safely, pessimism is the name of the game". In the last couple of weeks comp.lang.python has had (at least) two practical examples of the pros and cons of private attributes. The pro: there was discussion about replacing the optparse module's implementation with argparse, leaving the interface the same. This was complicated by the fact that optparse exposes its internal variables, making the job of duplicating the interface significantly harder. However this was surely a design choice, not an accident. Having private attributes won't save you if you choose not to make your attributes private. The con: there was a fellow who (for some reason) actually needed to access a class' private attributes. To the best of my knowledge, he was over 18 and, while new to Python, an experienced programmer, so I believe him when he said he had eliminated all other alternatives. (And if he were wrong, if he was incompetent -- Not My Problem. It isn't for me to take a hammer off him so he doesn't hit his thumb with it.) In his case, Python's name mangling of private attributes was an inconvenience, not a help. Compared to all the "what-ifs" and "maybes" and hypotheticals in this thread, there were two practical cases that revolved around private variables. In one, we see that they aren't a panacea: data hiding doesn't help when the data isn't hidden. In the other, we see that one developer's private attribute is just what another developer needs to solve a problem. -- Steven. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 15 13:44:17 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 15 Jan 2007 19:44:17 +0100 Subject: compile your python programs with rpython References: <1168886140.256596.101250@v45g2000cwv.googlegroups.com> Message-ID: <5120c1F1hccevU1@mid.individual.net> Simon Burton wrote: > The pypy'ers have written a brief description on > using rpython to create standalone executables: > > http://codespeak.net/pypy/dist/pypy/doc/standalone-howto.html > > This is definately worth playing around with, it's very nice > writing (r)python code that gets executed as if it were c code. Needless to say, RPython code has some restrictions over normal Python code. Regards, Bj?rn -- BOFH excuse #317: Internet exceeded Luser level, please wait until a luser logs off before attempting to log back on. From johnzenger at gmail.com Fri Jan 19 13:43:53 2007 From: johnzenger at gmail.com (John Zenger) Date: 19 Jan 2007 10:43:53 -0800 Subject: when format strings attack In-Reply-To: References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> Message-ID: <1169232233.469572.298320@a75g2000cwd.googlegroups.com> Perhaps it is not as severe a security risk, but pure Python programs can run into similar problems if they don't check user input for % codes. Example: >>> k = raw_input("Try to trick me: ") Try to trick me: How about %s this? >>> j = "User %s just entered: " + k >>> print j % "John" Traceback (most recent call last): File "", line 1, in ? print j % "John" TypeError: not enough arguments for format string On Jan 19, 10:44 am, "Gabriel Genellina" wrote: > escribi? en el mensajenews:1169207467.989977.162940 at q2g2000cwa.googlegroups.com... > > >http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN > > > I saw a warning from homeland security about this. I only comment on > > the because I am trying to use os.system('command1 arg') and it doesn't > > work but I do see examples with % that is borrowed from the c language. > > Seems like if I can write a batch file that does something the same > > behavior should happen in the os module..Pure Python programs are not affected, but a review of the C implementation > should be made to see if any (variant of) printf is used without a proper > format. Anyway I doubt you could find something, because the vulnerability > is so well known for ages. > > -- > Gabriel Genellina From evan at binarymanipulations.com Tue Jan 2 05:50:18 2007 From: evan at binarymanipulations.com (Evan Carmi) Date: Tue, 2 Jan 2007 10:50:18 +0000 (UTC) Subject: Unexpected output while walking dirs References: <1167314477.668406.324830@a3g2000cwd.googlegroups.com> Message-ID: wittempj hotmail.com gmail.com> writes: > > If I do get this correct - you have files like \test\Mail\somename.msf > and \test\Mail\somedirectory\someothername.msf, these files you want to > move to \test\backup\timestamp\somename.msf and > \test\backup\timestamp\somedirectory\someothername.msf. > > In your code you start with collecting allfiles, and then you remove > all except *,msf files. You can do this in one step to, by collecting > only the wanted files in a listby applying the glob command from module > glob : > > allfiles = [] > for root, dirs, files in os.walk(top, topdown=False): > targetfiles = glob.glob(os.path.join(root,'*.msf')) > allfiles += targetfiles > > Now allfiles contains the list of .msf files down from directory > specified in variable top. From here I would create a list of 2-tuples, > with as first element the full original filename, and as second element > the desired backupname. Note that in your code you call the clock in a > for loop, this might result in more directories. > > backuproot = os.path.join(os.path.dirname(top), 'backup-msf', > time.strftime('%Y%m%d%H%M%S')) > backupfilenames = [] > for f in allfiles: > backupfilenames.append((f, os.path.join(backuproot, > os.path.basename(f)))) > > >From here it is easy to do the move. > Thanks so much for your help, you got me started and I finished it with some help from others as well. For anyone interested the working code is: -- #!/usr/bin/python #Author: Evan Carmi #Date: 20060102 #Purpose: To uncorrupt Mozilla Thunderbird mail index files. #Version: 1.00 import os, time, glob srcRoot = 'f:\\test\\mail' backupRoot = os.path.join(os.path.dirname(srcRoot), 'backup-msf', time.strftime('%Y%m%d%H%M%S')) for root, dirs, files in os.walk(srcRoot, topdown=False): sources = glob.glob(os.path.join(root,'*.msf')) pairs = [] for source in sources: # If srcRoot is /foo/bar and source is /foo/bar/baz, let relativeSource equal /baz #let relativeSource be equal to the remainder of source when you take away len(srcRoot) idx = len(srcRoot) relativeSource = source[idx:] # Then let destination equal /quux/baz if backupRoot is /quux destination = backupRoot + relativeSource # relativeSource begins with a path separator, so os.path.join will misinterpret it. pair = (source, destination) pairs.append(pair) for pair in pairs: os.renames(*pair) # This is functionally equivalent to os.renames(pair[0], pair[1]) -- Thanks, Evan From ptwobrussell at gmail.com Sun Jan 14 12:05:46 2007 From: ptwobrussell at gmail.com (MR) Date: 14 Jan 2007 09:05:46 -0800 Subject: Decorators inside of class and decorator parameters In-Reply-To: References: <1168728983.541526.202320@l53g2000cwa.googlegroups.com> Message-ID: <1168794346.511854.315470@s34g2000cwa.googlegroups.com> Thanks so much for your reply. You've definitely helped me a great deal on this. Your comment about the difference between define time and instantiation time cleared things up more than anything, and that also helped clear up the confusion I was having about "self". I think the places I've seen decorators called like fooDecorator() must be using some default arguments in the function signature...so that part makes a lot more sense now too. Thanks again! Gabriel Genellina wrote: > "MR" escribi? en el mensaje > news:1168728983.541526.202320 at l53g2000cwa.googlegroups.com... > > > I have a question about decorators, and I think an illustration would > > be helpful. Consider the following simple class: > > > > #begin code > > class Foo: > > def fooDecorator(f): > > print "fooDecorator" > > > > def _f(self, *args, **kw): > > return f(self, *args, **kw) > > > > return _f > > > > @fooDecorator > > def fooMethod(self): > > print "fooMethod" > > > > f = Foo() > > f.fooMethod() > > #end of code > > > > This code runs, and actually serves my purpose. However, I'm a little > > confused about three things and wanted to try and work through them > > while I had the time to do so. I believe all of my confusion is related > > to the parameters related to the fooDecorator: > > [I reordered your questions to make the answer a bit more clear] > > > -why does this code even work, because the first argument to > > fooDecorator isn't self > > fooDecorator is called when the class is *defined*, not when it's > instantiated. `self` has no meaning inside it, neither the class to which it > belongs (Foo does not even exist yet). > At this time, fooDecorator is just a simple function, being collected inside > a namespace in order to construct the Foo class at the end. So, you get > *exactly* the same effect if you move fooDecorator outside the class. > > > -how I would pass arguments into the fooDecorator if I wanted to (my > > various attempts have failed) > > Once you move fooDecorator outside the class, and forget about `self` and > such irrelevant stuff, it's just a decorator with arguments. > If you want to use something like this: > @fooDecorator(3) > def fooMethod(self): > that is translated to: > fooMethod = fooDecorator(3)(fooMethod) > That is, fooDecorator will be called with one argument, and the result must > be a normal decorator - a function accepting a function an an argument and > returning another function. > > def outerDecorator(param): > def fooDecorator(f): > print "fooDecorator" > > def _f(self, *args, **kw): > print "decorated self=%s args=%s kw=%s param=%s" % (self, args, kw, > param) > kw['newparam']=param > return f(self, *args, **kw) > > return _f > return fooDecorator > > This is the most direct way of doing this without any help from other > modules - see this article by M. Simoniato > http://www.phyast.pitt.edu/~micheles/python/documentation.html for a better > way using its decorator factory. > > > -what the difference is between decorating with @fooDecorator versus > > @fooDecorator() > Easy: the second way doesn't work :) > (I hope reading the previous item you can answer this yourself) > > > I'm searched the net and read the PEPs that seemed relevant, but I > > didn't see much about decorators inside of a class like this. Can > > anyone comment on any of these three things? > As said in the beginning, there is no use for decorators as methods (perhaps > someone can find a use case?) > If you move the example above inside the class, you get exactly the same > results. > > HTH, > > -- > Gabriel Genellina From joshua at eeinternet.com Tue Jan 23 19:45:00 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 23 Jan 2007 15:45:00 -0900 Subject: My python programs need a GUI, wxPython or PyQt4? References: Message-ID: <45b69f63$0$24463$88260bb3@free.teranews.com> Daniel wrote: > I've downloaded both the wxPython and the PyQt4 package, and by the > first impression I must say that the PyQt4 system had a very > compelling presentation. From what I can understand from the feedback > I've gotten so far is that the wxPython is a better choice when it > comes to compability (with linux), and it's free even if I want to > create applications and sell them. > So, from what I understand I will have to go with PyQt4 since (from > my understanding): > 1. I will not sell the applications I'm working with since they will > only be used by the internal QA at a computer game company. Even that is getting on shaky ground, at least according to Troll Tech. See: http://www.trolltech.com/developer/knowledgebase/190/ So, write it for internal use, and put up for distribution on your personal web site (pending company approval, of course). j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From cvanarsdall at mvista.com Mon Jan 29 16:18:30 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Mon, 29 Jan 2007 13:18:30 -0800 Subject: The reliability of python threads In-Reply-To: <014501c741fa$64dbbbe0$03000080@hendrik> References: <45B90118.5010408@mvista.com><01b001c7411d$17e52a20$03000080@hendrik> <45BA39D3.7020400@mvista.com> <014501c741fa$64dbbbe0$03000080@hendrik> Message-ID: <45BE64A6.7010809@mvista.com> Hendrik van Rooyen wrote: > [snip] >> could definitely do more of them. The thing will be >> > > When I read this - I thought - probably your stuff is working > perfectly - on your test cases - you could try to send it some > random data and to see what happens - seeing as you have a test > server, throw the kitchen sink at it. > > Possibly "random" here means something that "looks like" data > but that is malformed in some way. Kind of try to "trick" the > system to get it to break reliably. > > I'm sorry I can't be more specific - it sounds so weak, and you > probably already have test cases that "must fail" but I don't > know how to put it any better... > Well, sometimes a weak analogy is the best thing because it allows me to fill in the blanks "How can I throw a kitchen sink at it in a way I never have before" And away my mind goes, so thank you. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From hg at nospam.org Wed Jan 3 03:23:52 2007 From: hg at nospam.org (hg) Date: Wed, 03 Jan 2007 09:23:52 +0100 Subject: array of class / code optimization References: Message-ID: <6UPmh.6785$hr3.92@newsfe24.lga> mm wrote: > > Yes, it was the (), equivalent to thiks like new() create new object > from class xy. >> s1.append(Word) > s1.append(Word()) > > But I was looking for a "struct" equivalent like in c/c++. > And/or "union". I can't find it. > > Maybe you know a source (URL) "Python for c/c++ programmers" or things > like that. > > > Yes, I konw whats an object is... A struct in C is unrelated to a struct in C++ as a struct in C++ _is_ a class. hg From aahz at pythoncraft.com Wed Jan 24 15:52:30 2007 From: aahz at pythoncraft.com (Aahz) Date: 24 Jan 2007 12:52:30 -0800 Subject: The reliability of python threads References: Message-ID: In article , Carl J. Van Arsdall wrote: > >Hey everyone, I have a question about python threads. Before anyone >goes further, this is not a debate about threads vs. processes, just a >question. > >With that, are python threads reliable? Or rather, are they safe? I've >had some strange errors in the past, I use threading.lock for my >critical sections, but I wonder if that is really good enough. > >Does anyone have any conclusive evidence that python threads/locks are >safe or unsafe? My response is that you're asking the wrong questions here. Our database server locked up hard Sunday morning, and we still have no idea why (the machine itself, not just the database app). I think it's more important to focus on whether you have done all that is reasonable to make your application reliable -- and then put your efforts into making your app recoverable. I'm particularly making this comment in the context of your later point about the bug showing up only every three or four months. Side note: without knowing what error messages you're getting, there's not much anybody can say about your programs or the reliability of threads for your application. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From bearophileHUGS at lycos.com Sun Jan 7 08:20:35 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Jan 2007 05:20:35 -0800 Subject: Why less emphasis on private data? In-Reply-To: <7x7ivz88af.fsf@ruckus.brouhaha.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> Message-ID: <1168176034.993117.127130@42g2000cwt.googlegroups.com> Paul Rubin: > Python certainly makes you spend more of your attention worrying > about possible attribute name collisions between classes and their > superclasses. And Python's name mangling scheme is leaky and > bug-prone if you ever re-use class names. > Trouble with this is you can have two classes with the same name, > perhaps because they were defined in different modules, and then the > name mangling fails to tell them apart. Without changing Python syntax at all I think this situation may be improved. Instead of Python applying name mangling to names with __ before them, it can manage them as private, a higher level kind of management. And then if it's useful a new built-in function may be invented to access such private attributes anyway. I think this may solve your problem. (This is for Py3.0). Maybe a metaclass can be invented to simulate such behavior to test and try it before modifying the language itself. Bye, bearophile From gagsl-py at yahoo.com.ar Sat Jan 20 01:13:27 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Jan 2007 03:13:27 -0300 Subject: regexp qns References: <1169268024.164643.71320@l53g2000cwa.googlegroups.com> Message-ID: escribi? en el mensaje news:1169268024.164643.71320 at l53g2000cwa.googlegroups.com... > hi > suppose i have a string like > > test1?test2t-test3*test4*test5$test6#test7*test8 > > how can i construct the regexp to get test3*test4*test5 and > test7*test8, ie, i want to match * and the words before and after? > thanks I suppose this is just an example and you mean "any word" instead of test1, test2, etc. So your pattern would be: word*word*word*word, that is, word* repeated many times, followed by another word. To match a word we'll use "\w+", to match an * we have to use "\*" (it's a special character) So the regexp would be: "(\w+\*)+\w+" Since we are not interested in the () as a group by itself -it was just to describe the repeating pattern- we change it into a non-grouping parenthesis. Final version: "(?:\w+\*)+\w+" import re rexp = re.compile(r"(?:\w+\*)+\w+") lines = [ 'test1?test2t-test3*test4*test5$test6#test7*test8', 'test1?test2t-test3*test4$test6#test7_test8', 'test1?nada-que-ver$esto.no.matchea', 'test1?test2t-test3*test4*', 'test1?test2t-test3*test4', 'test1?test2t-test3*', ] for line in lines: print line for txt in rexp.findall(line): print '->', txt Test it with some corner cases and see if it does what you expect: no "*", starting with "*", ending with "*", embedded whitespace before and after the "*", whitespace inside a word, the very definition of "word"... -- Gabriel Genellina From mccredie at gmail.com Wed Jan 3 19:54:37 2007 From: mccredie at gmail.com (Matimus) Date: 3 Jan 2007 16:54:37 -0800 Subject: code optimization (calc PI) In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> Message-ID: <1167872076.937415.250340@11g2000cwr.googlegroups.com> > If someone is really interested in speed optimization, I can publish my > PI-calc code. I wouldn't mind seeing it. Chances are you will get much better help if you post your code anyway. -Matt From hg at nospam.org Fri Jan 5 04:29:17 2007 From: hg at nospam.org (hg) Date: Fri, 05 Jan 2007 10:29:17 +0100 Subject: importing / loading a module / class dynamically Message-ID: Hi, I have the following problem. I find in a directory hierarchy some files following a certain sets of rules: .../.../../plugin/name1/name1.py .... .../.../../plugin/namen/namen.py each file will in turn have a class with the same name as the filename (minus .py) I fetch those names in a list of string and want to import the files / instantiate the classes. I block at the beginning and tried this (test.py is a real file) >>> s = 'test.py' >>> eval ('import ' + s) and get Traceback (most recent call last): File "", line 1, in -toplevel- eval ('import ' + s) File "", line 1 import test.py Any clue ? Thanks hg From mc at uga.edu Tue Jan 9 16:30:01 2007 From: mc at uga.edu (mc) Date: 9 Jan 2007 13:30:01 -0800 Subject: Python - C# interoperability Message-ID: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> Is there an easy way to compile a Python class (or set of classes) into a .DLL that a C# program can call? Or otherwise to use an existing library of Python classes from a C# program as seamlessly as possible? From jarausch at skynet.be Tue Jan 2 12:16:28 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 02 Jan 2007 18:16:28 +0100 Subject: python2.5 frameobject - how to upgrade? In-Reply-To: References: <459a6894$0$9322$ba620e4c@news.skynet.be> Message-ID: <459A936C.4090609@skynet.be> skip at pobox.com wrote: > Helmut> I'd like to install a package ('rekall') which uses > Helmut> frame->f_nlocals which is no longer contained in frameobject.h. > > Helmut> What's the recommended way to upgrade such an application? > > I suspect PySequence_Length(frame->f_locals) will do the trick. Yes, thanks, that fixed it, Happy New Year to you. A personal question: Have you converted from Perl to Python, as well? -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From theller at ctypes.org Mon Jan 8 10:37:43 2007 From: theller at ctypes.org (Thomas Heller) Date: Mon, 08 Jan 2007 16:37:43 +0100 Subject: help: code formatter? In-Reply-To: References: Message-ID: <45A26547.9040606@ctypes.org> siggi schrieb: > Hi all, > > as a newbie I have problems with formatting code of downloaded programs, > because IDLE's reformatting capabilities are limited . Incorrect > indentation, mixing of TAB with BLANKs or eol are often very nasty to > correct. > Is there a simple code formatter that first removes all indentations and > then refomats correctly? > > Please help! Tools\scripts\reindent.py in your Python distribution. Thomas From bytter at gmail.com Tue Jan 16 08:08:35 2007 From: bytter at gmail.com (Hugo Ferreira) Date: Tue, 16 Jan 2007 13:08:35 +0000 Subject: re.sub and empty groups Message-ID: <4e8efcf50701160508j24ceedf4l415df47063876319@mail.gmail.com> Hi! I'm trying to do a search-replace in places where some groups are optional... Here's an example: >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola").groups() ('ola', None) >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|").groups() ('ola', '') >> re.match(r"Image:([^\|]+)(?:\|(.*))?", "Image:ola|ole").groups() ('ola', 'ole') The second and third results are right, but not the first one, where it should be equal to the second (i.e., it should be an empty string instead of None). This is because I want to use re.sub() and when the group is None, it blows up with a stack trace... Maybe I'm not getting the essence of groups and non-grouping groups. Someone care to explain (and, give the correct solution :)) ? Thanks in advance, Hugo Ferreira -- GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 From nocl123 at gmail.com Thu Jan 11 04:42:33 2007 From: nocl123 at gmail.com (nic) Date: 11 Jan 2007 01:42:33 -0800 Subject: os.popen() not executing command on windows xp Message-ID: <1168508553.151827.261420@k58g2000hse.googlegroups.com> On my system (WinXP) typing the following line into command prompt(cmd.exe) successfully scans the file test1.txt: "c:\Program Files\Grisoft\AVG Free\avgscan.exe" "c:\program files\temp1\test1.txt" Yet the python script: import os a = os.popen('"c:\Program Files\Grisoft\AVG Free\avgscan.exe" "c:\program files\temp1\test1.txt"') print a.read() Returns a blank line, and I doesn't scan the file. (Note I've used os.popen() successfully on my system in other situations like: os.popen('taskkill /F /IM taskname.exe')). I have a feeling my avgscan example shown above not working has something to do with calling a 3rd party software program (avgscan.exe) through popen, but I don't know why this won't work, when manually typing it in the command line does? From nmm1 at cus.cam.ac.uk Thu Jan 18 08:41:49 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 18 Jan 2007 13:41:49 GMT Subject: what can be used in a signal handler References: <3zKrh.30692$sE7.26486@newsfe21.lga> Message-ID: In article <3zKrh.30692$sE7.26486 at newsfe21.lga>, hg writes: |> |> I posted an equivalent question earlier ... but am still not sure: |> |> I currently (under Linux) have a program that uses Queue.put (raw_input('')) |> in a signal handler and Queue.get() in the main/only thread. |> |> It works but I want to know if it is legal / what type of synchro API I have |> the right to use in a signal handler. Strictly, no and none. C and POSIX's specifications of signal handling is a complete mess. ALL handling of ALL real signals is undefined behaviour, though few programmers realise that and POSIX depends on it. As that would make all Unices (and Microsoft systems) unusable, you can reasonably assume that there is some signal handling that will work. But what? Which is where you came in. The situation is that most things that seem to work do actually work, in some environments and under some circumstances. You can never be sure when they will stop working, however, and all bets are off when you port signal handling code to a new system. And, really but REALLY, do not mix it with very high levels of optimisation or rely on it being in any way thread safe. I can't tell you whether the code of Queue is intended to work if an active Queue.get is interrupted by a signal which then does a Queue.put, but that is the sort of circumstance where things get very hairy. Even if Python has code to enable that case, it won't be 100% reliable on all systems. Sorry. But that is the situation :-( Regards, Nick Maclaren. From tjgolden at gmail.com Tue Jan 16 12:09:34 2007 From: tjgolden at gmail.com (Tim Golden) Date: 16 Jan 2007 09:09:34 -0800 Subject: Check a windows service In-Reply-To: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> Message-ID: <1168967374.568967.173690@11g2000cwr.googlegroups.com> awel wrote: > I'm new in python and I would like to know if it's possible to check if > a specific windows service is present and if it's possible how can I > do? This is one way: http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services You'd have to change that example slightly, but I hope the principal is clear enough. If not, ask again. TJG From pwatson at redlinepy.com Fri Jan 5 23:36:24 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 05 Jan 2007 22:36:24 -0600 Subject: Learning to program in Python In-Reply-To: <1168028517.005902.172880@11g2000cwr.googlegroups.com> References: <1168028517.005902.172880@11g2000cwr.googlegroups.com> Message-ID: <508na9F1d6c9nU1@mid.individual.net> jbchua wrote: > Hello everybody. > > I am an Electrical Engineering major and have dabbled in several > languages such as Python, C, and Java in my spare time because of my > interest in programming. However, I have not done any practical > programming because I have no idea where to get started. I taught > myself these languages basically by e-tutorials and books. This makes > me feel as if I don't really know how to implement these languages. > Does anybody have any advice on where to start applying my limited > knowledge practically in order to advance my learning? This would be a good site to investigate. http://diveintopython.org/ From steven.bethard at gmail.com Thu Jan 18 17:08:05 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 18 Jan 2007 15:08:05 -0700 Subject: A note on heapq module In-Reply-To: <1169117876.063858.56570@s34g2000cwa.googlegroups.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> <1169117876.063858.56570@s34g2000cwa.googlegroups.com> Message-ID: <8NSdnf38_otYcjLYnZ2dnUVZ_tadnZ2d@comcast.com> bearophileHUGS at lycos.com wrote: > Steven Bethard: >> Antoon Pardon: >>> For me, your class has the same drawback as the heappush, heappop >>> procedurers: no way to specify a comparision function. >> Agreed. I'd love to see something like ``Heap(key=my_key_func)``. > > It can be done, but the code becomes more complex and hairy: > http://rafb.net/p/iCCmDz16.html Cool! The current code fails when using unbound methods however:: >>> heap = Heap() >>> Heap.push(heap, 1) Traceback (most recent call last): File "", line 1, in AttributeError: type object 'Heap' has no attribute 'push' I would have written the code like:: def smallest(self): result = self._heap[0] if self._key is not None: result = result[2] return result def push(self, item): if self._key is not None: item = self._key(item), self._itemid, item self._itemid += 1 heappush(self._heap, item) def pop(self): result = heappop(self._heap) if self._key is not None: result = result[2] return result def popn(self, n): result = [heappop(self._heap) for _ in xrange(n)] if self._key is not None: result = [item[2] for item in result] return result def replace(self, item): if self._key is not None: item = self._key(item), self._itemid, item self._itemid += 1 result = heapreplace(self._heap, item) if self._key is not None: result = result[2] return result This allows unbound methods to work, and substantially lowers the code duplication. It does add a few extra if statements, but since they're ``is`` tests, they should be pretty fast. STeVe From inq1ltd at verizon.net Mon Jan 15 18:12:42 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Mon, 15 Jan 2007 18:12:42 -0500 Subject: download win32file In-Reply-To: <501e09e0701151502x352e4b42hb353a44d0319fd54@mail.gmail.com> References: <200701151805.19483.inq1ltd@verizon.net> <501e09e0701151502x352e4b42hb353a44d0319fd54@mail.gmail.com> Message-ID: <200701151812.42241.inq1ltd@verizon.net> On Monday 15 January 2007 18:02, Bill Tydeman wrote: > > ?? Do I have to download pywin32 to get > > win32ui, or win32file, or win32api > > Yes Got it. Thank you. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 12 11:58:05 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 12 Jan 2007 17:58:05 +0100 Subject: context managers and generators References: <1168611420.448058.163860@11g2000cwr.googlegroups.com> <1168614604.273032.173650@51g2000cwl.googlegroups.com> Message-ID: <50pt0tF1h5hj5U2@mid.individual.net> Laszlo Nagy wrote: >> I'm still thinking there is a better way to do it, and would >> appreciate any ideas. > > Everything can be implemented with goto and arrays. But is that really better? Regards, Bj?rn -- BOFH excuse #174: Backbone adjustment From zhouchengly at gmail.com Wed Jan 17 01:36:55 2007 From: zhouchengly at gmail.com (shellon) Date: 16 Jan 2007 22:36:55 -0800 Subject: How to convert float to sortable integer in Python In-Reply-To: References: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> Message-ID: <1169015814.960023.40310@a75g2000cwd.googlegroups.com> I'm sorry I mistake the function name, the function is floatToRawIntBits(), it convert ieee 754 floating point number to integer, e.g. if f1>f2 then floatToRawBits(f1) > floatToRawBits(f1) I want convert floating point number to sortable string to index in Lucene, so I want first to conver the floating point number to integer first, and than convert the integer to sortable string? so How to convert a ieee 754 floating point to raw bits like the java api floatToRawBits do? Appreciate your help! Steven D'Aprano wrote: > On Tue, 16 Jan 2007 01:21:52 -0800, shellon wrote: > > > Hi all: > > I want to convert the float number to sortable integer, like the > > function float2rawInt() in java, but I don't know the internal > > expression of float, appreciate your help! > > Google says: > > Your search - float2rawInt - did not match any documents. > > Are you sure about that function? What's a sortable integer? > > > -- > Steven. From seandavi at gmail.com Thu Jan 11 07:49:21 2007 From: seandavi at gmail.com (Sean Davis) Date: 11 Jan 2007 04:49:21 -0800 Subject: Read from database, write to another database, simultaneously In-Reply-To: References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> Message-ID: <1168519760.894380.303990@i39g2000hsf.googlegroups.com> On Jan 11, 3:20 am, Laurent Pointal wrote: > Bjoern Schliessmann a ?crit : > > > Sean Davis wrote: > > >> The author of one of the python database clients mentioned that > >> using one thread to retrieve the data from the oracle database and > >> another to insert the data into postgresql with something like a > >> pipe between the two threads might make sense, keeping both IO > >> streams busy. > > > IMHO he's wrong. Network interaction is quite slow compared with CPU > > performance, so there's no gain (maybe even overhead due to thread > > management and locking stuff). That's true even on multiprocessor > > machines, not only because there's almost nothing to compute but > > only IO traffic. CMIIW.Not so sure, there is low CPU in the Python script, but there may be > CPU+disk activity on the database sides [with cache management and other > optimizations on disk access]. > So, with a reader thread and a writer thread, he can have a select on a > database performed in parallel with an insert on the other database. > After, he must know if the two databases use same disks, same > controller, same host... or not. Some more detail: The machine running the script is distinct from the Oracle machine which is distinct from the Postgresql machine. So, CPU usage is low and because of the independent machines for the database end, it is definitely possible to read from one database while writing to the other. That is the solution that I am looking for, and Dennis's post seems pretty close to what I need. I will have to use some kind of buffer. A Queue isn't quite right as it stands, as the data is coming in as records, but for postgres loading, a file-like stream is what I need, so there will need to be either a wrapper around the Queue on the get() side. Or is there a better way to go about this detail? What seems to make sense to me is to stringify the incoming oracle data into some kind of buffer and then read on the postgresql side. Thanks, Sean From itoakya at gmail.com Thu Jan 4 06:16:22 2007 From: itoakya at gmail.com (itoakya at gmail.com) Date: 4 Jan 2007 03:16:22 -0800 Subject: Convert Perl to Python References: Message-ID: <1167909381.460119.277400@42g2000cwt.googlegroups.com> pyperl - Perl for Python ------------------------ "This is a Python extension module that makes it possible to embed Perl interpreter(s) in any Python program. It can be used to invoke arbitrary Perl code, load any Perl modules and make calls directly into Perl functions. The Perl code invoked can call back into Python as it see fit." http://wiki.python.org/moin/PyPerl At least, a pacific coexistence between Python and Perl. From gagsl-py at yahoo.com.ar Tue Jan 2 10:24:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Jan 2007 12:24:30 -0300 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167526509.471697.320750@v33g2000cwv.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <4595B214.3070405@v.loewis.de> <1167526509.471697.320750@v33g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070102121201.0324ed78@yahoo.com.ar> At Saturday 30/12/2006 21:55, Ben Sizer wrote: >python setup.py install > >On Unix, you'd run this command from a shell prompt; on Windows, you >have to open a command prompt window (``DOS box'') and do it there; " > >Pretty much none of the instructions in that part of the docs will work >without you altering your path beforehand. Python's cross-platform >nature means people rightly expect the same instructions to work on >Linux and Windows from a standard installation. Right now, they don't. Notice that there is NO need to alter the system path. You just have to tell Windows where python.exe resides; there is a per-application path located at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths. In order to launch Python just writing "python" at the command prompt, the installer should -instead of playing with the system path- create a new key below App Paths, named "python.exe", and set its default value to the full path of the installed python executable. See http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/fileassociations/fa_perceived_types.asp -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tomerfiliba at gmail.com Tue Jan 23 09:46:20 2007 From: tomerfiliba at gmail.com (gangesmaster) Date: 23 Jan 2007 06:46:20 -0800 Subject: free variables /cell objects question In-Reply-To: References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> Message-ID: <1169563580.634000.122540@v45g2000cwv.googlegroups.com> ugliness :) so this is why [lambda: i for i in range(10)] will always return 9. imho that's a bug, not a feature. thanks. -tomer Duncan Booth wrote: > "gangesmaster" wrote: > > > what problem does the cell object solve? > > The closure represents the variable, not the object. So if x is rebound to > a different object your inner function g() will now access the new object. > If the object itself was passed to MAKE_CLOSURE then g would only ever see > the value of x from the instant when g was defined. > > >>> def f(x): > def g(): > print "x is", x > g() > x += 1 > g() > > > >>> f(1) > x is 1 > x is 2 From roopesh.raj at gmail.com Tue Jan 16 11:09:01 2007 From: roopesh.raj at gmail.com (Roopesh) Date: 16 Jan 2007 08:09:01 -0800 Subject: sslerror: (8, 'EOF occurred in violation of protocol') Message-ID: <1168963738.710991.238580@a75g2000cwd.googlegroups.com> I am getting an SSL error while fetching mails from Gmail over SSL on Port 995. This problem occurs occasionally only, otherwise it works file. Any idea why it happens. Exception in thread Thread-1: Traceback (most recent call last): File "c:\python24\lib\threading.py", line 442, in __bootstrap self.run() File "C:\The_email_archive_system\email_archiver\pensive\mail_source.py", line 425, in run self.download_mails () File "C:\The_email_archive_system\email_archiver\pensive\mail_source.py", line 403, in download_mails mymsg = M.retr(msg_no) File "c:\python24\lib\poplib.py", line 237, in retr return self._longcmd('RETR %s' % which) File "c:\python24\lib\poplib.py", line 172, in _longcmd return self._getlongresp() File "c:\python24\lib\poplib.py", line 157, in _getlongresp line, o = self._getline() File "c:\python24\lib\poplib.py", line 374, in _getline self._fillBuffer() File "c:\python24\lib\poplib.py", line 364, in _fillBuffer localbuf = self.sslobj.read() sslerror: (8, 'EOF occurred in violation of protocol') Regards Roopesh From ruan at jcmills.com Wed Jan 31 11:49:53 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Wed, 31 Jan 2007 11:49:53 -0500 Subject: What is the dummy statement that do nothing in Python? Message-ID: I remember that in python there is some kind of dummy statement that just holds space and does nothing. I want it to hold the place after a something like if a>b: do nothing I can't just leave the space blank after if statement because there will be error message. Does anybody know what to insert there? Thanks! From steve at REMOVEME.cybersource.com.au Wed Jan 24 00:34:13 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 24 Jan 2007 16:34:13 +1100 Subject: Overloading assignment operator References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> <1169604475.177104.40330@s48g2000cws.googlegroups.com> Message-ID: On Tue, 23 Jan 2007 18:07:55 -0800, Russ wrote: > Achim Domma wrote: >> Hi, >> >> I want to use Python to script some formulas in my application. The user >> should be able to write something like >> >> A = B * C >> >> where A,B,C are instances of some wrapper classes. Overloading * is no >> problem but I cannot overload the assignment of A. I understand that >> this is due to the nature of Python, but is there a trick to work around >> this? >> All I'm interested in is a clean syntax to script my app. Any ideas are >> very welcome. >> >> regards, >> Achim > > Why do you need to overload assignment anyway? If you overloaded "*" > properly, it should return > the result you want, which you then "assign" to A as usual. Maybe I'm > missing something. One common reason for overriding assignment is so the left-hand-side of the assignment can choose the result type. E.g. if Cheddar, Swiss and Wensleydale are three custom classes, mutually compatible for multiplication: B = Cheddar() # B is type Cheddar C = Swiss() # C is type Swiss # without overloading assignment A = B * C # A is (possibly) Cheddar since B.__mul__ is called first A = C * B # A is (possibly) Swiss since C.__mul__ is called first # with (hypothetical) assignment overloading A = B * C # A is type Wensleydale since A.__assign__ is called Except, of course, there is no assignment overloading in Python. There can't be, because A may not exist when the assignment is performed, and if it does exist it might be a complete different type. Instead, you can do something like this: A = Wensleydale(B) * Wensleydale(C) or A = Wensleydale(B * C) -- Steven D'Aprano From hg at nospam.org Mon Jan 15 10:37:47 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 16:37:47 +0100 Subject: download win32file References: Message-ID: <_mTqh.49191$kn7.39312@newsfe23.lga> jim-on-linux wrote: > > > Where can I download win32file / win32ui? > > The links below are broken. Mark Hammond should > be made aware of this. > > > URL below has two links that send you no place > http://mail.python.org/pipermail/python-list/2002-October/167638.html > > > Links: > http://starship.python.net/crew/mhammond/win32/Downloads.html > > http://starship.python.net/crew/mhammond/downloads/win32all-148.exe > > > Produce; > > The requested URL was not found on this server. > The link on the referring page seems to be wrong > or outdated. Please inform the author of that > page about the error. > > jim-on-linux Do you mean PyWin32 ? http://sourceforge.net/projects/pywin32/ From sean at seanodonnell.com Fri Jan 5 03:53:42 2007 From: sean at seanodonnell.com (Sean O'Donnell) Date: Fri, 05 Jan 2007 00:53:42 -0800 Subject: Problem installing MySQLdb/1.2.1_p2 with Python/2.4.1 and MySQL/5.0.18 In-Reply-To: <506hbbF1eqkd8U1@mid.uni-berlin.de> References: <459e0752$0$17009$4c368faf@roadrunner.com> <506hbbF1eqkd8U1@mid.uni-berlin.de> Message-ID: <459e148d$0$8975$4c368faf@roadrunner.com> Diez B. Roggisch wrote: > Sean O'Donnell schrieb: >> Hi, >> >> I can't seem to get MySQLdb/1.2.1p2 to install on Slackware/10.2, with >> Python/2.4.1, and MySQL/5.0.18. >> >> The following command: >> >> $ python setup.py build 2> setup.err >> >> returns the following errors: >> >> http://pastebin.com/851624 >> >> Any suggestions? > > Install the mysql developer package that contains the needed includefiles. > > Diez doh... I forgot that I installed MySQL/5.0.18 from the binary distribution, not the source (as I thought I had done back when). Thanks! From steve at REMOVEME.cybersource.com.au Sun Jan 14 23:17:59 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 15 Jan 2007 15:17:59 +1100 Subject: How naive is Python? References: Message-ID: On Mon, 15 Jan 2007 03:25:01 +0000, John Nagle wrote: > How naive (in the sense that compiler people use the term) > is the current Python system? For example: > > def foo() : > s = "This is a test" > return(s) > > s2 = foo() > > How many times does the string get copied? Let's find out. Results below for Python 2.3 -- other versions may vary. >>> def foo(): ... s = "This is a test" ... return s ... >>> def foo2(): ... return "This is a test" ... >>> import dis >>> dis.dis(foo) 2 0 LOAD_CONST 1 ('This is a test') 3 STORE_FAST 0 (s) 3 6 LOAD_FAST 0 (s) 9 RETURN_VALUE 10 LOAD_CONST 0 (None) 13 RETURN_VALUE >>> dis.dis(foo2) 2 0 LOAD_CONST 1 ('This is a test') 3 RETURN_VALUE 4 LOAD_CONST 0 (None) 7 RETURN_VALUE foo and foo2 functions compile to different byte-code. foo does a little more work than foo2, but it is likely to be a trivial difference. >>> s1 = foo() >>> s2 = foo() >>> s1 == s2, s1 is s2 (True, True) So the string "This is a test" within foo is not copied each time the function is called. However, the string "This is a test" is duplicated between foo and foo2 (the two functions don't share the same string instance): >>> s3 = foo2() >>> s3 == s1, s3 is s1 (True, False) > Or, for example: > > s1 = "Test1" > s2 = "Test2" > s3 = "Test3" > s = s1 + s2 + s3 > > Any redundant copies performed, or is that case optimized? I don't believe it is optimized. I believe that in Python 2.5 simple numeric optimizations are performed, so that "x = 1 + 3" would compile to "x = 4", but I don't think that holds for strings. If you are running 2.5, you could find out with dis.dis. > How about this? > > kcount = 1000 > s = '' > for i in range(kcount) : > s += str(i) + ' ' > > Is this O(N) or O(N^2) because of recopying of "s"? That will be O(N**2), except that CPython version 2.4 (or is it 2.5?) can, sometimes, optimize it. Note that this is an implementation detail, and doesn't hold for other Pythons like Jython, IronPython or PyPy. -- Steven D'Aprano From felipe.lessa at gmail.com Mon Jan 8 11:01:08 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 8 Jan 2007 14:01:08 -0200 Subject: Suitability for long-running text processing? In-Reply-To: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> Message-ID: On 1/8/07, tsuraan wrote: [snip] > The loop is deep enough that I always interrupt it once python's size is > around 250 MB. Once the gc.collect() call is finished, python's size has > not changed a bit. [snip] > This has been tried under python 2.4.3 in gentoo linux and python 2.3 under > OS X.3. Any suggestions/work arounds would be much appreciated. I just tried on my system (Python is using 2.9 MiB) >>> a = ['a' * (1 << 20) for i in xrange(300)] (Python is using 304.1 MiB) >>> del a (Python is using 2.9 MiB -- as before) And I didn't even need to tell the garbage collector to do its job. Some info: $ cat /etc/issue Ubuntu 6.10 \n \l $ uname -r 2.6.19-ck2 $ python -V Python 2.4.4c1 -- Felipe. From aboudouvas at panafonet.gr Wed Jan 31 09:27:46 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 31 Jan 2007 06:27:46 -0800 Subject: "Correct" db adapter Message-ID: <1170253666.826691.276800@s48g2000cws.googlegroups.com> Hi to all, i have started a month ago to seriously studying Python. I am now looking at the databases stuff and i want the opinion of more experienced Python programmers (than me) at the following : I see that there are a lot of databases adapters on the net, some following the DB-API 2.0 and some others do not. I want to use a db- module that do not tie me down to a specific database and that fully supports DB-API 2.0 Now i am using Sql Server but who knows about tomorrow. I started using pyodbc and looking how i can e.x. call stored procedure with arguments and all that stuff. This is using ODBC syntac and i found enough info on the net. Is the approach i took the "correct" one or is there a better db- module so i can use ? Thanks in advance From osv at javad.com Thu Jan 11 05:21:38 2007 From: osv at javad.com (Sergei Organov) Date: Thu, 11 Jan 2007 13:21:38 +0300 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Message-ID: nmm1 at cus.cam.ac.uk (Nick Maclaren) writes: > In article , > Sergei Organov writes: > |> > |> Do you mean that POSIX threads are inherently designed and implemented > |> to stay idle most of the time?! If so, I'm afraid those guys that > |> designed POSIX threads won't agree with you. In particular, as far as I > |> remember, David R. Butenhof said a few times in comp.programming.threads > |> that POSIX threads were primarily designed to meet parallel programming > |> needs on SMP, or at least that was how I understood him. > > I do mean that, and I know that they don't agree. However, the word > "designed" doesn't really make a lot of sense for POSIX threads - the > one I tend to use is "perpetrated". OK, then I don't think the POSIX threads were "perpetrated" to be idle most of time. > The people who put the specification together were either unaware of > most of the experience of the previous 30 years, or chose to ignore it. > In particular, in this context, the importance of being able to control > the scheduling was well-known, as was the fact that it is NOT possible > to mix processes with different scheduling models on the same set of > CPUs. POSIX's facilities are completely hopeless for that purpose, and > most of the systems I have used effectively ignore them. I won't argue that. On the other hand, POSIX threads capabilities in the field of I/O-bound and real-time threads are also limited, and that's where "threads that are idle most of time" idiom comes from, I think. What I argue, is that POSIX were "perpetrated" to support I/O-bound or real-time apps any more than to support parallel calculations apps. Besides, pthreads real-time extensions came later than pthreads themselves. What I do see, is that Microsoft designed their system so that it's almost impossible to implement an interactive application without using threads, and that fact leads to the current situation where threads are considered to be beasts that are sleeping most of time. > I could go on at great length, and the performance aspects are not even > the worst aspect of POSIX threads. The fact that there is no usable > memory model, and the synchronisation depends on C to handle the > low-level consistency, but there are no CONCEPTS in common between > POSIX and C's memory consistency 'specifications' is perhaps the worst. I won't argue that either. However, I don't see how does it make POSIX threads to be "perpetrated" to be idle most of time. > That is why many POSIX threads programs work until the genuinely > shared memory accesses become frequent enough that you get some to the > same location in a single machine cycle. Sorry, I don't understand. Are you saying that it's inherently impossible to write an application that uses POSIX threads and that doesn't have bugs accessing shared state? I thought that pthreads mutexes guarantee sequential access to shared data. Or do you mean something entirely different? Lock-free algorithms maybe? -- Sergei. From steve at holdenweb.com Mon Jan 29 08:08:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Jan 2007 13:08:59 +0000 Subject: Data structure and algorithms In-Reply-To: References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> Message-ID: Terry Reedy wrote: > "azrael" wrote in message [...] > | > | but this was not dinamicly enough for me (or my prof.) so > > dynamic? I have no idea what you mean by 'not dynamic enough'. > > Python is not C or C++. It does not have pointers. Trying to program in C > in Python does not work too well. > Mostly because Python variables are precisely pointers to object values allocated from a heap. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 From nmm1 at cus.cam.ac.uk Thu Jan 25 14:36:39 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 25 Jan 2007 19:36:39 GMT Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169675599.502726.5070@a34g2000cwb.googlegroups.com> <1169751828.986583.47200@j27g2000cwj.googlegroups.com> Message-ID: In article <1169751828.986583.47200 at j27g2000cwj.googlegroups.com>, "Paddy" writes: |> |> > |> Three to four months before `strange errors`? I'd spend some time |> > |> correlating logs; not just for your program, but for everything running |> > |> on the server. Then I'd expect to cut my losses and arrange to safely |> > |> re-start the program every TWO months. |> > |> (I'd arrange the re-start after collecting logs but before their |> > |> analysis. Life is too short). |> > |> > Forget it. That strategy is fine in general, but is a waste of time |> > where threading issues are involved (or signal handling, or some types |> > of communication problem, for that matter). |> |> Nah, Its a great strategy. it keeps you up and running when all you |> know for sure is that you will most likely be able to keep things |> together for three months normally. |> |> The OP only thinks its a threading problem - it doesn't matter what the |> true fix will be, as long as arranging to re-start the server well ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |> before its likely to go down doesn't take too long, compared to your ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |> exploration of the problem, and, of course, you have to be able to |> afford the glitch in availability. Consider the marked phrase in the context of a Poisson process failure model, and laugh. If you don't understand why I say that, I suggest finding out the properties of the Poisson process! Regards, Nick Maclaren. From ziga.seilnacht at gmail.com Sun Jan 21 10:19:00 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 21 Jan 2007 07:19:00 -0800 Subject: Number methods References: Message-ID: <1169392740.130549.174200@38g2000cwa.googlegroups.com> Nick Maclaren wrote: > I can't find any description of these. Most are obvious, but some > are not. Note that this is from the point of view of IMPLEMENTING > them, not USING them. Specifically: The Python equivalents of these methods are described in the reference manual: http://docs.python.org/ref/numeric-types.html More details can be founf in various PEPs: http://www.python.org/dev/peps/ > Does Python use classic division (nb_divide) and inversion (nb_invert) > or are they entirely historical? Note that I can very easily provide > the latter. Python uses classic divison by default. True divison is used only when the division __future__ directive is in effect. See PEP 238 for details: http://www.python.org/dev/peps/pep-0238/ The nb_invert method is used for the implementation of the bitwise inverse unary operator (~). I don't think that it is deprecated. See: http://docs.python.org/lib/bitstring-ops.html for details. > Is there any documentation on the coercion function (nb_coerce)? It > seems to have unusual properties. It is used for old style Python classes and extension types that don't have Py_TPFLAGS_CHECKTYPES in their tp_flags. See: http://docs.python.org/ref/coercion-rules.html and http://www.python.org/dev/peps/pep-0208/ for details. Ziga From chris at wavestore.com Tue Jan 30 11:40:52 2007 From: chris at wavestore.com (Christopher Mocock) Date: Tue, 30 Jan 2007 16:40:52 +0000 Subject: Please take me off the list In-Reply-To: <1170174428.224923.5500@p10g2000cwp.googlegroups.com> References: <1170174428.224923.5500@p10g2000cwp.googlegroups.com> Message-ID: <45BF7514.50109@wavestore.com> Paul Boddie wrote: > See also the Tutor mailing list, which might be a bit better for > starting to learn Python, should you (Daniel) decide to change your > mind. Here's the mailing list's Web page: > > http://mail.python.org/mailman/listinfo/tutor > > If you haven't seen much information for beginners, take a look at > these pages for some references: > > http://www.python.org/about/gettingstarted/ > http://wiki.python.org/moin/BeginnersGuide > > Paul I was expecting to see a barrage of joke emails after reading the OP but that's really useful information for me too as a bit of a beginner. Thanks. Chris. From jUrner at arcor.de Wed Jan 3 15:40:40 2007 From: jUrner at arcor.de (jUrner at arcor.de) Date: 3 Jan 2007 12:40:40 -0800 Subject: M. Hammonds python panel Message-ID: <1167856840.117284.78420@k21g2000cwa.googlegroups.com> Hello all I am a great fan of Mark Hammonds python pannel. But since starship went down it didn't come up again ...with the link in my favs to http://starship.python.net/crew/mhammond/mozilla/pythonpanel.xul still pointing nowhere. Maybe Mark is around here somewhere... J?rgen From gagsl-py at yahoo.com.ar Mon Jan 29 23:54:58 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 01:54:58 -0300 Subject: Convert raw data to XML References: <1170124927.718200.225080@m58g2000cwm.googlegroups.com> Message-ID: En Mon, 29 Jan 2007 23:42:07 -0300, escribi?: > For example the raw data is as follows > > SomeText Description>PassorFail > > without spaces or new lines. I need this to be written into an XML > file as > [same content but nicely indented] Is the file supposed to be processed by humans? If not, just write it as you receive it. Spaces and newlines and indentation are mostly irrelevant on an xml file. -- Gabriel Genellina From sturlamolden at yahoo.no Sun Jan 14 01:37:04 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 13 Jan 2007 22:37:04 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168735174.140171.74930@v45g2000cwv.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168715634.695961.14710@l53g2000cwa.googlegroups.com> <1168728465.178605.218850@q2g2000cwa.googlegroups.com> <1168735174.140171.74930@v45g2000cwv.googlegroups.com> Message-ID: <1168756624.569930.168990@51g2000cwl.googlegroups.com> oyekomova wrote: > Thanks for your note. I have 1Gig of RAM. Also, Matlab has no problem > in reading the file into memory. I am just running Istvan's code that > was posted earlier. You have a CSV file of about 520 MiB, which is read into memory. Then you have a list of list of floats, created by list comprehension, which is larger than 274 MiB. Additionally you try to allocate a NumPy array slightly larger than 274 MiB. Now your process is already exceeding 1 GiB, and you are probably running other processes too. That is why you run out of memory. So you have three options: 1. Buy more RAM. 2. Low-level code a csv-reader in C. 3. Read the data in chunks. That would mean something like this: import time, csv, random import numpy def make_data(rows=6E6, cols=6): fp = open('data.txt', 'wt') counter = range(cols) for row in xrange( int(rows) ): vals = map(str, [ random.random() for x in counter ] ) fp.write( '%s\n' % ','.join( vals ) ) fp.close() def read_test(): start = time.clock() arrlist = None r = 0 CHUNK_SIZE_HINT = 4096 * 4 # seems to be good fid = file('data.txt') while 1: chunk = fid.readlines(CHUNK_SIZE_HINT) if not chunk: break reader = csv.reader(chunk) data = [ map(float, row) for row in reader ] arrlist = [ numpy.array(data,dtype=float), arrlist ] r += arrlist[0].shape[0] del data del reader del chunk print 'Created list of chunks, elapsed time so far: ', time.clock() - start print 'Joining list...' data = numpy.empty((r,arrlist[0].shape[1]),dtype=float) r1 = r while arrlist: r0 = r1 - arrlist[0].shape[0] data[r0:r1,:] = arrlist[0] r1 = r0 del arrlist[0] arrlist = arrlist[0] print 'Elapsed time:', time.clock() - start make_data() read_test() This can process a CSV file of 6 million rows in about 150 seconds on my laptop. A CSV file of 1 million rows takes about 25 seconds. Just reading the 6 million row CSV file ( using fid.readlines() ) takes about 40 seconds on my laptop. Python lists are not particularly efficient. You can probably reduce the time to ~60 seconds by writing a new CSV reader for NumPy arrays in a C extension. From michael at mustun.ch Thu Jan 4 10:41:56 2007 From: michael at mustun.ch (Michael M.) Date: Thu, 04 Jan 2007 16:41:56 +0100 Subject: code optimization (calc PI) / New Algorithme for PI In-Reply-To: References: Message-ID: Mainly, it was fload-div. Changed to int-div (python //) runs faster. Yes, this "gmpy" sounds good for calc things like that. But not available on my machine. ImportError: No module named gmpy Anyway, thanks for posting. This gmpy module can be very intersting. But right now, the focus was, if it's possible to translate a strange C code into Python. And it is. Sure ;-) Maybe, someone can also translate a very simple algorithm for calc a range of PI in Python. (Available Code for C.) http://crd.lbl.gov/~dhbailey/ http://crd.lbl.gov/~dhbailey/bbp-codes/piqpr8.c But seems to be removed? It was working last days. (Maybe removed from server.) An other well known is: (but someone implemented this already in Python, slow, and, depends on the previouse calc values, like most other algorithmes.) pi 01 01 01 01 01 01 01 01 01 01 __ = __ - __ + __ - __ + __-__+__-__+__-__ 04 01 03 05 07 09 11 13 15 17 19 ... pi/4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 ... Or things like that: http://numbers.computation.free.fr/Constants/PiProgram/pifast.html > There is more than one way to skin this cat. A better algorithm helps > a lot. > > If I really wanted lots of digits of pi from python I'd do it like > this. This is an example of the right tool for the job. 0.5ms looks > pretty good to me! > > >>> import math, gmpy > >>> bits = int(800/math.log10(2)) > >>> start = time(); pi=gmpy.pi(bits); dt = time()-start > >>> print "That took",dt,"seconds" > That took 0.00055193901062 seconds > >>> pi > mpf('3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455e0',2657) > >>> > From bdesth.quelquechose at free.quelquepart.fr Thu Jan 18 15:36:14 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 18 Jan 2007 21:36:14 +0100 Subject: Traversing the properties of a Class In-Reply-To: <1169141253.332211.12790@38g2000cwa.googlegroups.com> References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> Message-ID: <45afd3ad$0$23680$426a74cc@news.free.fr> EdG a ?crit : > I'm using Python version 2.4 and I created a class with some properties > like: > > def GetCallAmount(self): > return somedata The recommended naming convention is all_lower,ie: def get_call_amount(self): And FWIW, there are idioms to avoid polluting the class namespace, like: class Account(object): @apply def amount(): def fget(self): return something def fset(self, value): do_something_with(value) return property(**locals()) > For debugging purposes, I would like to traverse the class listing out > all the properties. cf Neil's answer. From S.Mientki-nospam at mailbox.kun.nl Thu Jan 11 14:47:26 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 11 Jan 2007 20:47:26 +0100 Subject: Need better run/edit method. I have to restart the shell after every script change. In-Reply-To: <1168544475.849070.92160@77g2000hsv.googlegroups.com> References: <1168544475.849070.92160@77g2000hsv.googlegroups.com> Message-ID: > As you can see, I'm wasting a lot of time with this method. Maybe > there is some better sofware available, or maybe I'm just not utilizing > the tools at my disposal. Either way I would greatly appreciate any > insight into this problem. > why not try a more advanced IDE, like PyScripter ? cheers, Stef Mientki From gonzlobo at gmail.com Thu Jan 25 11:17:40 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Thu, 25 Jan 2007 09:17:40 -0700 Subject: Two dimensional lists Message-ID: I might get an answer since I didn't call them arrays. :^) Ok, I have 2 lists that I need to process individually, then merge them into a 2x list and fill with data. arinc429 = ['ab', '2b', '0b', '21', 'c1', '61', '11', 'db', '9b', '5b', 'eb', '6b', '1b', '6e', '3e'] iPIDs = [300, 301, 320, 321] merged[arinc429, iPIDs] # PID & a429 are defined elsewhere a_idx = iPIDs.index[PID] p_idx = [arinc429.index[a429] # shouldn't I be able to fill the lists simply by pointing to a location? matrix[a_idx, p_idx] = 0x219 # and so on? tia From gagsl-py at yahoo.com.ar Wed Jan 3 18:15:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Jan 2007 20:15:43 -0300 Subject: pythoncom module In-Reply-To: <4594D800.9040308@riddergarn.dk> References: <4594D800.9040308@riddergarn.dk> Message-ID: <7.0.1.0.0.20070103201308.03695500@yahoo.com.ar> At Friday 29/12/2006 05:55, Scripter47 wrote: >I need a module called "pythoncom" anyone that knows where a can find >that module??? It's part of the pywin32 package https://sourceforge.net/project/showfiles.php?group_id=78018 -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ziga.seilnacht at gmail.com Wed Jan 31 11:50:57 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 31 Jan 2007 08:50:57 -0800 Subject: Conditional expressions - PEP 308 In-Reply-To: References: Message-ID: <1170262257.491270.237240@j27g2000cwj.googlegroups.com> Colin J. Williams wrote: > It would be helpful if the rules of the game were spelled out more clearly. > > The conditional expression is defined as X if C else Y. > We don't know the precedence of the "if" operator. From the little test > below, it seem to have a lower precedence than "or". The rules are specified in the Python Reference Manual: http://docs.python.org/ref/Booleans.html Ziga From shuanyu at gmail.com Sat Jan 6 21:57:06 2007 From: shuanyu at gmail.com (many_years_after) Date: 6 Jan 2007 18:57:06 -0800 Subject: How to invoke parent's method? Message-ID: <1168138626.574514.102060@i15g2000cwa.googlegroups.com> Hi, pythoners: My wxPython program includes a panel whose parent is a frame. The panel has a button. When I click the button , I want to let the frame destroy. How to implement it? Could the panel invoke the frame's method? Thanks. From PengYu.UT at gmail.com Wed Jan 3 11:11:48 2007 From: PengYu.UT at gmail.com (PengYu.UT at gmail.com) Date: 3 Jan 2007 08:11:48 -0800 Subject: When argparse will be in the python standard installation Message-ID: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> Hi, I feel argparse has some useful things that optparse doesn't have. But I can't find it argparse in python library reference. I'm wondering when it will be available in the python standard installation. Thanks, Peng From mpeters42 at gmail.com Mon Jan 8 03:40:04 2007 From: mpeters42 at gmail.com (Mark Peters) Date: 8 Jan 2007 00:40:04 -0800 Subject: regex question In-Reply-To: <1168244922.620428.273260@38g2000cwa.googlegroups.com> References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> <1168243020.304940.212700@42g2000cwt.googlegroups.com> <1168244922.620428.273260@38g2000cwa.googlegroups.com> Message-ID: <1168245604.911965.248360@11g2000cwr.googlegroups.com> > is there any way i would be successful then, in using raw string inside > my makeRE() function? Why do you think you even need a raw string? Just build and return the string 'a|b|c' (NOTE: DON'T add the quotes to the string) From konrad.hinsen at laposte.net Fri Jan 12 12:13:28 2007 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Fri, 12 Jan 2007 18:13:28 +0100 Subject: Parallel Python In-Reply-To: <1168610918.587465.197740@51g2000cwl.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> <1168610918.587465.197740@51g2000cwl.googlegroups.com> Message-ID: <2543B387-D3A2-46C0-AE39-3B78A60A7F3F@laposte.net> On Jan 12, 2007, at 15:08, Paul Boddie wrote: > It seems to me that a more useful first step would be to create an > overview of the different modules and put it on the python.org Wiki: > > http://wiki.python.org/moin/FrontPage > http://wiki.python.org/moin/UsefulModules (a reasonable entry point) > > If no-one beats me to it, I may write something up over the weekend. That sounds like a good idea. I won't beat you to it, but I'll have a look next week and perhaps add information that I have. Konrad. -- --------------------------------------------------------------------- Konrad Hinsen Centre de Biophysique Mol?culaire, CNRS Orl?ans Synchrotron Soleil - Division Exp?riences Saint Aubin - BP 48 91192 Gif sur Yvette Cedex, France Tel. +33-1 69 35 97 15 E-Mail: hinsen at cnrs-orleans.fr --------------------------------------------------------------------- From arkanes at gmail.com Fri Jan 5 14:51:13 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 5 Jan 2007 13:51:13 -0600 Subject: MySQLdb windows binaries for Python 2.5?? Yes, but from a World of Warcraft guild. In-Reply-To: References: <1162408100.985370.148650@m7g2000cwm.googlegroups.com> <1163238145.257490.144410@b28g2000cwb.googlegroups.com> <1166144355.616642.127080@n67g2000cwd.googlegroups.com> <1168019043.523288.50770@38g2000cwa.googlegroups.com> Message-ID: <4866bea60701051151v4f7942bj2921b2143a18a092@mail.gmail.com> On 1/5/07, John Nagle wrote: > msj at infoserv.dk wrote: > > Anyone have a binary they want to share? > > > > /Martin > > > Somebody has an untested one. See > > http://sourceforge.net/forum/forum.php?thread_id=1571110&forum_id=70461 > > You have to ask for a copy; they don't want to distribute it and > be blamed for problems. > > There hasn't been a new release of MySQLdb since April 2006, and > there's no official support for either Python 2.5 or Windows. > Realistically, you have to run Python 2.4 or earlier if you > need database access. We dropped back to Python 2.4, > with good results. > > John Nagle > -- I guess this is your opportunity, as someone who thinks that MySQL support for Python is important, to assist in maintaining and updating those wrappers, right? From tpawley at gmail.com Mon Jan 15 05:10:31 2007 From: tpawley at gmail.com (Torabisu) Date: 15 Jan 2007 02:10:31 -0800 Subject: Python web app. (advice sought) In-Reply-To: References: <45aae51b.0@entanet> Message-ID: <1168855828.324888.31610@38g2000cwa.googlegroups.com> Tim Williams wrote: > On 15 Jan 2007 00:52:33 -0800, Torabisu wrote: > > > > Duncan Smith wrote: > > > Hello, > > > I find myself in the, for me, unusual (and at the moment unique) > > > position of having to write a web application. I have quite a lot of > > > existing Python code that will form part of the business logic. This > > > relies on 3rd party libraries (such as numpy) which would make porting > > > to e.g. IronPython difficult (I would imagine). I was thinking LAMP > > > (the P standing for Python, of course), particularly as I was originally > > > encouraged to go for open source solutions. > > > > > > The application will provide some basic statistical analyses of data > > > contained in database tables and associated plots (R / matplotlib / > > > graphviz). There will also be some heavier duty Monte Carlo simulation > > > and graphical modelling / MCMC. The user(s) will need to be able to set > > > model parameters; maybe even tinker with model structure, so it will be > > > very interactive (AJAX?). > > > > > > I've had a look at Django, Turbogears and Plone, and at the moment I am > > > torn between Turbogears and Plone. I get the impression that Turbogears > > > will require me to write more non-Python code, but maybe Plone is more > > > than I need (steeper learning curve?). Maybe Turbogears will lead to a > > > more loosely coupled app. than Plone? > > > > > > The disconcerting thing is that others on the project (who won't be > > > developing) have started to talk about a LAMP back end with an IIS front > > > end, .NET, and the benefits of sharepoint. The emphasis is supposed to > > > be on rapid development, and these technologies are supposed to help. > > > But I have no real familiarity with them at all; just Python, C and SQL > > > to any realistic level of competence. > > > > > > Any advice would be greatly appreciated. I have to do much of the > > > statistical work too, so I need to make good choices (and hopefully be > > > able to justify them so nobody else on the project makes inappropriate > > > choices for me). e.g. I don't mind learning Javascript if it doesn't > > > take too long. The physical server will initially be a multiprocessor > > > machine with several GB of RAM. But we also have a cluster (I have no > > > details, I only started the project a week ago). So any advice > > > regarding parallelisation would also be appreciated (or, in fact, any > > > useful advice / pointers at all). Thanks. > > > > > > Duncan > > > > I was in a similar boat a while back, needing to make a decision on > > what to use for our web development. I had worked with Plone > > previously and found that for our needs it wasn't going to work. Our > > web development was quite specific and didn't fit ideally into the > > standard content management realm. I also looked at Django and > > TurboGears, installing and working with each. I eventually went with > > Django, and I've really enjoyed working with it. Was a personal choice > > and I'm sure our development would have been as successful if I'd > > chosen TurboGears. > > > > If you want the strength of persistent layers, MVC, templating etc etc > > but want to stay away from the heavier frameworks, another possibility > > is http://webpy.org/. Very simple to implement, lightweight yet still > > fairly full of features. > > > > Don't overlook Karrigell either, with a tiny learning curve its > always worth consideration, especially if you need rapid development > and a web server that will sit on top of your exising .py modules. > > www.karrigell.com > > hth :) Hmm, thanks for the link on Karrigell. Never heard of it till now, quite nice... From nagle at animats.com Thu Jan 11 14:29:59 2007 From: nagle at animats.com (nagle at animats.com) Date: 11 Jan 2007 11:29:59 -0800 Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error References: Message-ID: <1168543799.097737.127930@i56g2000hsf.googlegroups.com> That's a problem for me. I need short timeouts; I'm accessing sites that might or might not have SSL support, and I need to quickly time out when there's no SSL server. PyOpenSSL handles timeout correctly, but M2Crypto does not. On the other hand, M2Crypto actually checks certificates, which PyOpenSSL does not. So we have two broken implementations. Python needs a merge here. Read Guido van Rossum's rant on M2Crypto: http://www.artima.com/weblogs/viewpost.jsp?thread=95863 Both of these packages contain wrappers for OpenSSL, but both wrappers are incompatible and buggy. M2Crypto also has some Python components. The PyOpenSSL wrapper, which ships with Python, doesn't expose enough of the OpenSSL API. M2Crypto exposes more of the API, but doesn't work as well. What's probably needed is to implement the additional API functions of the M2Crypto wrapper in the PyOpenSSL wrapper, so that the M2Crypto components written in Python could be used with it. Then we'd have one good implementation instead of two broken ones. John Nagle nagle at animats.com (News feed broken, using Google Groups as backup.) From Dieter_Deyke at CoCreate.com Thu Jan 25 17:54:54 2007 From: Dieter_Deyke at CoCreate.com (Dieter Deyke) Date: Thu, 25 Jan 2007 15:54:54 -0700 Subject: pdf to text References: <86714$45b9254c$54d1d767$3741@news.chello.no> Message-ID: tubby writes: > David Boddie wrote: > >> The pdftotext tool may do what you want: >> >> http://www.foolabs.com/xpdf/download.html >> >> Let us know how you get on with it. >> >> David > > Perhaps I'm just using pdftotext wrong? Here's how I was using it: > > f = filename > > try: > sout = os.popen('pdftotext "%s" - ' %f) > data = sout.read().strip() > print data > sout.close() > > except Exception, e: > print e I am using pdftotext on Windows with cygwin on a regular basis without any problem. Your program above should read: sout = os.popen('pdftotext "%s" - ' % (f,)) -- Dieter Deyke A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing on usenet and in e-mail? From nmm1 at cus.cam.ac.uk Fri Jan 12 10:05:23 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 12 Jan 2007 15:05:23 GMT Subject: Rational Numbers References: Message-ID: In article , Carsten Haese writes: |> On Thu, 2007-01-11 at 23:47 +0000, Nick Maclaren wrote: |> > In article , |> > Facundo Batista writes: |> > |> Noud Aldenhoven wrote: |> > |> |> > |> > When I was programming in a mathematical project I began to wonder if python |> > |> > supports rational numbers[1]. In a language like magma[2] it's not such a |> > |> > problem. Does python supports something simular? |> > |> |> > |> Python does not have rational numbers. |> > |> |> > |> There's a (rejected) PEP about this, PEP-239: |> > |> |> > |> http://www.python.org/dev/peps/pep-0239/ |> > |> |> > |> Maybe you also want to read the section "Why not rational?" of |> > |> PEP-327... |> > |> |> > |> http://www.python.org/dev/peps/pep-0327/#why-not-rational |> > |> > Oh, God. Decimal delusions again :-( |> > |> > There are good arguments for not having a rational type, but the idea |> > that decimal floating-point is in any way a replacement is cuckoo. |> |> You're putting words in Facundo's mouth. Facundo didn't say why we |> should read that section of PEP 327. I think he merely pointed to the |> slow performance of rational numbers that's explained in that section. |> (Facundo is the author of PEP 327, so I find it unlikely that he has |> delusions about what decimals can and can't do.) You're putting words in MY mouth! I didn't say that he did. But I agree that my words could easily be read that way, so I apologise for any misunderstanding. |> It is true that decimal arithmetic is not a replacement for rational |> arithmetic, but I don't see anybody on this thread or in PEP 327 stating |> that it is. Read them again, more carefully :-( The BDFL Pronouncement rejecting PEP 239 does, even if it does qualify it by saying "to some extent". And it was that PEP that I was primarily referring to in that remark. The "Why not rational?" section of PEP 327 quotes Alex Martelli as saying that Rational are not worth doing without Decimal, which makes no sense at all. All it does is to plug Decimal for a purpose for which it is completely unsuited; not all rational numbers have denumerators that are powers of 10. Regards, Nick Maclaren. From has.temp3 at virgin.net Fri Jan 19 10:49:35 2007 From: has.temp3 at virgin.net (has) Date: 19 Jan 2007 07:49:35 -0800 Subject: [ann] Appscript Installer 1.5 released Message-ID: <1169221775.151715.199600@l53g2000cwa.googlegroups.com> Announcing the release of Appscript Installer 1.5, containing all the latest appscript-related modules, documentation and tools: http://appscript.sourceforge.net/download.html Appscript enhances the Python scripting language (http://www.python.org) with robust, easy-to-use OS X application scripting support, making Python a serious alternative to AppleScript for automating your Mac. This release contains several significant API changes, along with various bugfixes and other internal improvements, and is recommended for all users. In addition, the bundled osadict command line tool has been overhauled to create a powerful interactive dictionary browser and HTML exporter with support for py-appscript, rb-appscript and AppleScript formatting styles. (Existing appscript users: please read the 'API CHANGES' file included with the appscript package before upgrading from older versions.) For Python 2.3+ on Mac OS X 10.3 and later. Enjoy, has -- http://appscript.sourceforge.net http://rb-appscript.rubyforge.org From scott at crybabymaternity.com Fri Jan 5 22:30:26 2007 From: scott at crybabymaternity.com (scott at crybabymaternity.com) Date: 5 Jan 2007 19:30:26 -0800 Subject: Newbie XML SAX Parsing: How do I ignore an invalid token? In-Reply-To: References: <1168033818.692201.183790@11g2000cwr.googlegroups.com> Message-ID: <1168054226.290465.325910@s34g2000cwa.googlegroups.com> My original posting has a funky line break character (it appears as an ascii square) that blows up my program, but it may or may not show up when you view my message. I was afraid to use element tree, since my xml files can be very long, and I was concerned about using memory structures to hold all the data. It is my understanding that SAX reads the file line by line? Is there a way to account for the invalid token in the error handler? I don't mind parsing out the bad characters on a case-by-case basis. The weather data I am ingesting only seems to have this line break character that the parser doesn't like. Thanks! Scott Chris Lambacher wrote: > What exactly is invalid about the XML fragment you provided? > It seems to parse correctly with ElementTree: > >>> from xml.etree import ElementTree as ET > >>> e = ET.fromstring(""" > ... > ... > ... Tampa > ... A great city ^^ and place to live > ... > ... > ... Clearwater > ... Beautiful beaches > ... > ... > ... """) > >>> print ET.tostring(e) > > > Tampa > A great city ^^ and place to live > > > Clearwater > Beautiful beaches > > > >>> > > Do you have invalid characters? unclosed tags? The solution to each of these > problems is different. More info will solicit better solutions. > > -Chris > > On Fri, Jan 05, 2007 at 01:50:18PM -0800, scott at crybabymaternity.com wrote: > > I've got an XML feed from a vendor that is not well-formed, and having > > them change it is not an option. I'm trying to figure out how to > > create an error-handler that will ignore the invalid token and continue > > on. > > > > The file is large, so I'd prefer not to put it all in memory or save it > > off and strip out the bad characters before I parse it. > > > > I've included one of the problematic characters in a small XML snippet > > below. > > > > I'm new to Python, and I don't know how to accomplish this. Any help is > > greatly appreciated! > > > > ----------------------------------------------------------------- > > > > Here is my code: > > > > from xml.sax import make_parser > > from xml.sax.handler import ContentHandler > > import StringIO > > > > class ErrorHandler: > > def __init__(self, parser): > > self.parser = parser > > def warning(self, msg): > > print '*** (ErrorHandler.warning) msg:', msg > > def error(self, msg): > > print '*** (ErrorHandler.error) msg:', msg > > def fatalError(self, msg): > > print msg > > > > class ContentHandler(ContentHandler): > > def __init__ (self): > > pass > > def startElement(self, name, attrs): > > pass > > def characters (self, ch): > > pass > > def endElement(self, name): > > pass > > > > xmlstr = """ > > > > > > Tampa > > A great city  and place to live > > > > > > Clearwater > > Beautiful beaches > > > > > > """ > > parser = make_parser() > > curHandler = ContentHandler() > > errorHandler = ErrorHandler(parser) > > parser.setContentHandler(curHandler) > > parser.setErrorHandler(errorHandler) > > parser.parse(StringIO.StringIO(xmlstr)) > > > > -- > > http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Sun Jan 7 04:21:22 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 07 Jan 2007 10:21:22 +0100 Subject: where is python on linux? References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> Message-ID: Frank Potter wrote: > I installed fedora core 6 and it has python installed. > But the question is, where is the executable python file? Find out yourself with $ which python Peter From jura.grozni at gmail.com Sun Jan 28 17:56:05 2007 From: jura.grozni at gmail.com (azrael) Date: 28 Jan 2007 14:56:05 -0800 Subject: Data structure and algorithms Message-ID: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> Hy, i am a student and in 2 days I am writing a test in data structures and algorithms. I've done my homework and understood all the implementations and structures. My profesor was so kind to allow us to use any programing language we want, and I'd like to use pythhon. At the first look it looked great, but we are not allowed to use the built in functions like append(), so i have to write my own. I tried it like this: class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) then >>> node1 = Node(1) >>> node2 = Node(2) >>> node3 = Node(3) >>> node1.next = node2 >>> node2.next = node3 but this was not dinamicly enough for me (or my prof.) so i did the following: >>> list=[] >>> list.append(Node(1)) >>> list.append(Node(2)) >>> list[0].next=list[1] >>> list.append(Node(3)) >>> list[1].next=list[2] but deleting the list[1] willl automaticly make the list[2] become list[1] and list[0] will "point" new to list[1]= 3 For my prof i should be doing something like deleting movig the pointer from pointing to list[1] to list[2]. If I would do this in C then the old list[1] would be lost, but not in python. If i just redirect the "pointer" then the old value is still there. I think that my concept is wrong by using a list to create a list. Is it possible to manage the insertation of new object like in C by allocating new memory space. any sugestions how to make the implementation more like in C. I never managed the syntax of C so I stoped when structs crossed my way. Please help. I dont want to learn C. And especialy not in 2 days. From pkyoung at gmail.com Wed Jan 24 03:19:32 2007 From: pkyoung at gmail.com (auditory) Date: Wed, 24 Jan 2007 17:19:32 +0900 Subject: numpy or _numpy or Numeric? In-Reply-To: References: Message-ID: Travis E. Oliphant ? ?: > auditory wrote: >> I am a newbie here >> >> I am trying to read "space separated floating point data" from file >> >> I read about csv module by searching this group, >> but I couldn't read space separated values with csv. >> (which may be matter of course..) >> >> I also read about numpy.fromfile(file, sep=' ') which i can use. >> but on my machine(ubuntu linux) numpy is unknown module, >> which I didn't install by myself. > > You will need to install NumPy. > >> >> While trying to install numpy accroding to its homepage. >> (http://numpy.scipy.org/numpydoc/numdoc.htm). >> i am quite confused. > > You are reading old documentation for Numeric and so any installation > description is how to install the Numeric module (not its newer > replacement which is called NumPy). > > > So: > > 1) Yes, you need NumPy > 2) This *is different* from Numeric > 3) You get it by either installing a pre-built package for your system > or by > > a) downloading the source tar-file from > http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 > > (get the numpy-.tar.gz file > b) tar zxvf numpy-.tar.gz > c) cd numpy- > d) sudo python setup.py install > > e) If you want to link against high-performance libraries on your > system, then either put them in standard locations or edit the site.cfg > file appropriately (Optional). > >> >> 4. Or what is general way to read 'space separated values' from file? > > You can easily read space-separated values from a file by reading in a > line at a time and using the split method of strings: > > fid = open('filename') > linedata = fid.readlines() > new = [[float(x) for x in line.split()] for line in linedata] > > new will be a nested sequence of floats. You can convert it to an array > (if you want to do math on it) using > > anew = numpy.array(new) > > -Travis > Thank you for quick answer.. I found the above website from googling with "numpy" keyword, and supprised at that the top matching page is old one. In addition to your method and below one, I found csv moudule can do this with "delimiter" paramter. I made mistake not to read manual first. My apology on that. From danb_83 at yahoo.com Mon Jan 29 00:43:12 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 28 Jan 2007 21:43:12 -0800 Subject: import from future In-Reply-To: <1169969100.946843.111770@p10g2000cwp.googlegroups.com> References: <1169969100.946843.111770@p10g2000cwp.googlegroups.com> Message-ID: <1170049392.204148.54430@a34g2000cwb.googlegroups.com> On Jan 28, 1:25 am, "lee" wrote: > what are the things that we can do with import from future usage.....i > heard its very interesting......thanks Now that nested_scopes and generators are no longer optional, the only thing left is "from __future__ import division", which makes the "/" operator on integers give the same result as for floats. From vmalloc at gmail.com Thu Jan 25 04:31:26 2007 From: vmalloc at gmail.com (Rotem) Date: 25 Jan 2007 01:31:26 -0800 Subject: pdb in python2.5 Message-ID: <1169717486.230356.79730@l53g2000cwa.googlegroups.com> Hi, Maybe I'm repeating a previous post (please correct me if I am). I've tried the following code in python 2.5 (r25:51908, Oct 6 2006, 15:22:41) example: from __future__ import with_statement import threading def f(): l = threading.Lock() with l: print "hello" raise Exception("error") print "world" try: f() except: import pdb pdb.pm() This fails because pdb.pm() attempts to access sys.last_traceback which is not assigned. Trying: pdb.post_mortem(sys.exc_traceback) Yields the following: > test.py(9)f() -> print "world" (Pdb) the 'w' command yields a similar output, which implies that the exception was thrown from the wrong line. the traceback module is better, yielding correct results (displays line 8 instead of 9). Has anyone encountered this behavior? is pdb broken? I get similar results for larger/more complex pieces of code. Thanks in advance, Rotem From fredrik at pythonware.com Thu Jan 4 13:57:22 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Jan 2007 19:57:22 +0100 Subject: Set type? In-Reply-To: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> References: <1167936480.882357.277320@v33g2000cwv.googlegroups.com> Message-ID: _ wrote: > How do you check to see if a variable is a set? I would like to use > > if type(var) is types.SetType: > blah > > but that is not available in types module. I am using 2.4 # set or subclass of set if isinstance(var, set): ... # exact match if type(var) is set: ... also see http://preview.tinyurl.com/yjnoc5 From paddy3118 at netscape.net Wed Jan 31 02:35:29 2007 From: paddy3118 at netscape.net (Paddy) Date: 30 Jan 2007 23:35:29 -0800 Subject: Conditional expressions - PEP 308 In-Reply-To: References: Message-ID: <1170228929.612844.153730@p10g2000cwp.googlegroups.com> On Jan 30, 9:51 pm, "Colin J. Williams" wrote: > It would be helpful if the rules of the game were spelled out more clearly. > > The conditional expression is defined as X if C else Y. > We don't know the precedence of the "if" operator. From the little test > below, it seem to have a lower precedence than "or". > > Thus, it is desirable for the user to put the conditional expression in > parentheses. > > Colin W. > > # condExpr.py > # PEP 308 defines a conditional expression as X if C else Y > # but we don't know exactly what X is supposed to be. > # It doesn't seem to be spelled out in the syntax. > > def main(): > names= ['abc', 'def', '_ghi', 'jkl', '_mno', 'pqrs'] > res= '' > for w in names: > res= res + w if w[0] != '_' else '' > z= 1 > print 'res1:', res > > res= '' > for w in names: > res= res + (w if w[0] != '_' else '') > z= 1 > print 'res2:', res > > if __name__ == '__main__': > main() > > Result: > [Dbg]>>> > res1: pqrs > res2: abcdefjklpqrs But to give them credit though, in Whats new in Python 2.5: PEP 308, they do mention that as a matter of style you should parenthesise the if-expression, and the example given consistes of just a simple assignment of the if-expr to a name. - Paddy. From heikki at osafoundation.org Fri Jan 12 20:06:47 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 12 Jan 2007 17:06:47 -0800 Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error In-Reply-To: References: <1168543799.097737.127930@i56g2000hsf.googlegroups.com> Message-ID: John Nagle wrote: > def connect(self, addr): > self.socket.connect(addr) > self.addr = addr > self.socket.settimeout(None) # Back to normal timeout (NEW) I am not sure if this is always appropriate. In fact, doesn't this just eliminate the timeout completely from this connection? In your case you could achieve what you want by calling connection_object.socket.settimeout(4.0) method just before calling connect, without needing to edit M2Crypto itself. setdefaulttimeout, socket.settimeout and socket.setblocking are pretty confusing... -- Heikki Toivonen From me at privacy.net Sun Jan 7 20:55:19 2007 From: me at privacy.net (Dan Sommers) Date: Sun, 07 Jan 2007 20:55:19 -0500 Subject: how to find the longst element list of lists References: Message-ID: On Sun, 07 Jan 2007 22:23:22 +0100, "Michael M." wrote: > How to find the longst element list of lists? > I think, there should be an easier way then this: > s1 = ["q", "e", "d"] > s2 = ["a", "b"] > s3 = ["a", "b", "c", "d"] [ snip ] One more thing to think about: if your list of lists grows (i.e., if you end up with thousands of lists instead of just three), then sorting may not be the way to go. Assuming that list_of_lists is your list of lists, then something like this: longest_list, longest_length = list_of_lists[ 0 ], len( longest_list ) for a_list in list_of_lists[ 1 : ]: a_length = len( a_list ) if a_length > longest_length: longest_list, longest_length = a_list, a_length will run faster than sorting the list just to pick off one element (O(n) vs. O(n log n) for all of you Big-Oh notation fans out there; you know who you are!). Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From S.Mientki-nospam at mailbox.kun.nl Tue Jan 2 05:46:52 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 02 Jan 2007 11:46:52 +0100 Subject: Difference between __init__ (again) and nothing ... Message-ID: What's the difference between using __init__ and using nothing, as the examples below. class cpu: PC = 4 class cpu: def __init__: self.PC = 4 thanks, Stef Mientki From siqingdu at gmail.com Mon Jan 29 18:19:05 2007 From: siqingdu at gmail.com (Siqing Du) Date: Mon, 29 Jan 2007 18:19:05 -0500 Subject: select windows Message-ID: Hi, Is there is a way to write a program to select and switch between windows? For instance, if I have three windows: Firefox, Thunderbird, and emacs, can I run a program to bring up the desired windows, instead of click on the windows use mouse. Thanks, Du From ivoras at fer.hr Wed Jan 3 11:01:03 2007 From: ivoras at fer.hr (Ivan Voras) Date: Wed, 03 Jan 2007 17:01:03 +0100 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: Sebastian 'lunar' Wiesner wrote: > Carsten Haese typed >> I don't think that that has anything to do with Linux or not. The >> script is not the actual executable, hence its suid bit is irrelevant. > > I don't think so. From what I know, the script is passed as executable > to the kernel loader, which interprets the shebang and feeds the script > through the correct interpreter. So the kernel loader sees the script > itself as executable instead of the interpreter binary. I've heard of > other Unix systems, which handle this differently (meaning that the > SUID bit on scripts has an effect), but I may be wrong. Yes, the kernel parses #! but the suid-ness is still controlled by the target interpreter (i.e. python executable). At least BSD systems also behave this way. From duncan.booth at invalid.invalid Wed Jan 3 06:09:00 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jan 2007 11:09:00 GMT Subject: Synchronization methodology References: Message-ID: Marc 'BlackJack' Rintsch wrote: > You may want to make sure the lock will be released in case of an > exception: > > def foo(self): > self.lock.aquire() > try: > pass # code > finally: > self.lock.release() > In Python 2.5 this can also be written more succintly using the with statement so foo becomes: from __future__ import with_statement ... def foo(self): with self.lock: pass # insert your code here or write a decorator. From 12cc104 at gmail.com Mon Jan 8 03:51:26 2007 From: 12cc104 at gmail.com (proctor) Date: 8 Jan 2007 00:51:26 -0800 Subject: regex question In-Reply-To: <45a20464$0$9644$4c368faf@roadrunner.com> References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> <1168243020.304940.212700@42g2000cwt.googlegroups.com> <45a20464$0$9644$4c368faf@roadrunner.com> Message-ID: <1168246286.569315.46270@51g2000cwl.googlegroups.com> Paul McGuire wrote: > "proctor" <12cc104 at gmail.com> wrote in message > news:1168243020.304940.212700 at 42g2000cwt.googlegroups.com... > > > > > > it does work now...however, one more question: when i type: > > > > rx_a = re.compile(r'a|b|c') > > it works correctly! > > > > Do you see the difference between: > > rx_a = re.compile(r'a|b|c') > > and > > rx_a = re.compile("r'a|b|c'") > > There is no difference in the variable datatype between "string" and "raw > string". Raw strings are just a notational helper when creating string > literals that have lots of backslashes in them (as happens a lot with > regexps). > > r'a|b|c' is the same as 'a|b|c' > r'\d' is the same as '\\d' > > There is no reason to "add raw strings" to your makeRE method, since you > don't have a single backslash anywhere. And even if there were a backslash > in the 'w' argument, it is just a string - no need to treat it differently. > > -- Paul thanks paul. this helps. proctor. From gagsl-py at yahoo.com.ar Wed Jan 31 03:06:50 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 31 Jan 2007 05:06:50 -0300 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170088693.768440.26580@h3g2000cwc.googlegroups.com> <1170090408.495646.85720@v33g2000cwv.googlegroups.com> <1170108446.671609.169400@j27g2000cwj.googlegroups.com> <1170216508.396176.187780@v33g2000cwv.googlegroups.com> Message-ID: En Wed, 31 Jan 2007 01:08:28 -0300, Hieu.D.Hoang at gmail.com escribi?: > raw_input can do the job of print > while 1: raw_input(__import__('os').urandom(6).encode('base64')) > > And can anyone explain why this is so? >>>> while 1: input(__import__('os').urandom(6).encode('base64')) > ^ > SyntaxError: unexpected EOF while parsing input and raw_input are not the same, see the docs. -- Gabriel Genellina From http Wed Jan 3 06:01:10 2007 From: http (Paul Rubin) Date: 03 Jan 2007 03:01:10 -0800 Subject: Synchronization methodology References: Message-ID: <7x64boml1l.fsf@ruckus.brouhaha.com> Chris Ashurst writes: > Hi, I'm coming in from a despised Java background, and I'm having some > trouble wrapping my head around sharing an object between multiple > instances of a single class (in simpler terms, I would say imagine a > simple chat server that has to share a list of connected users to each > instance of a connected user). If you're doing this with threads, one common Pythonic style is generally to have the threads communicate through queues (see docs for the Queue module). This is sort of a cheap version of the CSP (communicating sequential processes) approach. You might have a service thread that takes care of those shared objects, reading requests from a queue (untested): # All client threads write their requests to this queue, and # the service loop reads from it service_queue = Queue() # make one of these in each client thread class Request(Queue.Queue): def __call__(self, reply_queue, func, *args, **kwargs): service_queue.put((self, func, args, kwargs)) return self.get() def service_loop(): while True: client, func, args, kwargs = service_queue.get() client.put (func(*args, **kwargs)) Threading.Thread(target=service_loop).start() Then in your connected user thread you could say: # set up a reply queue for this user's thread request = Request() ... # add the user to the connected user list, with timestamp and remote IP status = request(user_list.append, self, time(), remote_ip=whatever) The last line would drop a request on the service queue to perform the function call user_list.append(time(), remote_ip=whatever) The service queue thread would retrieve the request, call the function, and pass the result back through the reply queue. The idea is you'd handle all operations on user_list in the service thread, so access is completely serialized using the queues. You can see that you can easily construct any function call that then gets executed in the other thread, without having to use a bunch of boilerplate at each request. You have to be a bit careful to not use long-running requests that could block other threads from getting their requests serviced. Use additional threads if you need such requests. You sometimes end up creating more threads than necessary this way but you tend to not have many synchronization problems if you stick with this style. From george.sakkis at gmail.com Sun Jan 21 18:29:27 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Jan 2007 15:29:27 -0800 Subject: mmap caching References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <45B3DD4D.3010009@v.loewis.de> Message-ID: <1169422167.683707.264180@a75g2000cwd.googlegroups.com> Martin v. L?wis wrote: > George Sakkis schrieb: > > I've been trying to track down a memory leak (which I initially > > attributed erroneously to numpy) and it turns out to be caused by a > > memory mapped file. It seems that mmap caches without limit the chunks > > it reads, as the memory usage grows to several hundreds MBs according > > to the Windows task manager before it dies with a MemoryError. > > You must be misinterpreting what you are seeing. It's the operating > system that decides what part of a memory-mapped file are held in > memory, and that is certainly not without limits. Sure; what I meant was that that whatever the limit is, it's high enough that a MemoryError is raised before the limit is reached. > Notice that there are several values that can be called "memory > usage" (such as the size of the committed address space, the working > set size, etc); you don't mention which of these values grows several > hundreds MB. It's the one in the 'Processes' tab of the Windows task manager (XP proffesional). By the way, I ran the same program on a box with more physical memory and the mem. usage stops growing at around 430MB, by which time the whole file is most likely cached. I'd be interested in any suggestions other than "buy more RAM" :) (these are not my machines anyway). Thanks, George From skip at pobox.com Tue Jan 23 21:19:11 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Jan 2007 20:19:11 -0600 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <17846.49695.213309.406485@montanaro.dyndns.org> John> MySQLdb has version and platform compatibility problems. Got specific examples? I've successfully used MySQLdb on Linux, Mac and Solaris with no compatibility problems at all. John> Even basic sockets don't quite work right; the socket module John> encapsulates the timeout mechanism but doesn't get it right. As has been reported here a number of times, this simply awaits someone with the time and inclination to do the work. If it itches you then scratch the itch. John> In the Perl, Java, PHP, and C/C++ worlds, the equivalent functions John> just work. That's because, in those worlds, either the John> development team for the language or the development team for the John> subsystem takes responsibility for making them work. Only Python John> doesn't do that. You seem to be expecting something for free from the volunteer development team. If these things are important enough you can always pay someone to do the work and contribute it back to the community. The work didn't happen for free in any of the communities you mentioned. Someone (Sun, AT&T, whoever) paid for it in either time or money. Skip From nagle at animats.com Thu Jan 25 11:35:13 2007 From: nagle at animats.com (John Nagle) Date: Thu, 25 Jan 2007 16:35:13 GMT Subject: Do I need Python to run Blender correctly? In-Reply-To: References: Message-ID: <5%4uh.75582$wP1.6882@newssvr14.news.prodigy.net> AKA gray asphalt wrote: > I downloaded Blender but there was no link for python. Am I on the right > track? Blender doesn't require Python, but if you have Python, you can write plug-ins for Blender. Get "The Blender Book"; otherwise you'll never figure Blender out. John Nagle From huayang.xia at gmail.com Thu Jan 18 13:11:06 2007 From: huayang.xia at gmail.com (Huayang Xia) Date: 18 Jan 2007 10:11:06 -0800 Subject: Memory Management in Embedded Python Message-ID: <1169143866.351663.316890@l53g2000cwa.googlegroups.com> Hi there, I have a piece of code like this: void funct(PyObject* pyobj) { char str[128]; strncpy(str, "just a test string", sizeof(str)); PyObject* pydata = PyObject_CallMethod(pyobj, "method_x", "s", str); Py_DECREF(pydata); } After the function is exited, the str is not there anymore. Will this affect python operation. How does python use the str? It's copied or it just uses the pointer? Thanks in advance. From van.lindberg at gmail.com Thu Jan 11 18:48:09 2007 From: van.lindberg at gmail.com (VanL) Date: Thu, 11 Jan 2007 17:48:09 -0600 Subject: Intellectual Property Talk at PyCon In-Reply-To: References: Message-ID: Robert Kern wrote: > I don't have any suggestions for other material to cover, but I'd like to > express my interest in keeping this in your agenda. This is an issue that crops > up again and again with ill-informed opinions all around. Thanks for the feedback. +1 for discussing GPL incorporation. > Of course, it would be nice if what you say agrees with my opinions on the > subject, but I'll let you slide if you at least say something sensible. ;-) I will try :) Van From wescpy at gmail.com Sun Jan 14 22:16:53 2007 From: wescpy at gmail.com (wesley chun) Date: 14 Jan 2007 19:16:53 -0800 Subject: Learning Python book, new edition? References: <1168547177.121582.320840@k58g2000hse.googlegroups.com> Message-ID: <1168831013.218729.243020@l53g2000cwa.googlegroups.com> Robert Hicks wrote: > I would get "Core Python Programming" by Wesley Chun. It covers just > about everything under the sun and includes version 2.5. Robert, thanks for the plug. if the OP wants to learn more about my book and its philosophy, feel free to check out my comments on the Amazon product page and/or the book's website at http://corepython.com to see if it's right for you. more on topic, here's a summary of Python books which are rev'd up to 2.5, categorized but not in any particular order: Python learning: - Python for Dummies, Maruch, Sep 2006 - Core Python Programming, Chun, Sep 2006 Python pure reference: - Python Essential Reference, Beazley, Feb 2006 - Python in a Nutshell, Martelli, Jul 2006 Python case study reference: - Programming Python, Lutz, Aug 2006 Enjoy! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dickinsm at gmail.com Mon Jan 15 11:35:37 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 15 Jan 2007 08:35:37 -0800 Subject: Conflicting needs for __init__ method In-Reply-To: References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <1168878934.345455.209810@m58g2000cwm.googlegroups.com> On Jan 14, 10:43 pm, Steven D'Aprano wrote: > On Sun, 14 Jan 2007 15:32:35 -0800, dickinsm wrote: > > (You could include the normalization in __init__, but that's wasteful > Is it really? Have you measured it or are you guessing? Is it more or less > wasteful than any other solution? Just guessing :). But when summing the reciprocals of the first 2000 positive integers, for example, with: sum((Rational(1, n) for n in range(1, 2001)), Rational(0)) the profile module tells me that the whole calculation takes 8.537 seconds, 8.142 of which are spent in my gcd() function. So it seemed sensible to eliminate unnecessary calls to gcd() when there's an easy way to do so. > def __copy__(self): > cls = self.__class__ > obj = cls.__new__(cls) > obj.numerator = self.numerator > obj.denominator = self.denominator > return obj Thank you for this. Mark From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jan 26 10:20:39 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 26 Jan 2007 16:20:39 +0100 Subject: Thoughts on using isinstance In-Reply-To: References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> <45b7b73b$0$391$426a74cc@news.free.fr> Message-ID: <45ba1c39$1$2308$426a74cc@news.free.fr> Matthew Woodcraft a ?crit : > Bruno Desthuilliers wrote: >> Matthew Woodcraft a ?crit : > >>> Adding the validation code can make your code more readable, in that >>> it can be clearer to the readers what kind of values are being >>> handled. > >> This is better expressed in the docstring. And if it's in the >> docstring, you can't be blamed for misuse. > > I certainly agree that the description of the function's requirements on > its parameters is best placed in the docstring. > > This is another place where the "don't validate, just try running the > code anyway" approach can cause problems: what should you put in the > docstring? > > I don't think anyone would like to be fully explicit about the > requirements: you'd end up having to write things like "A string, or at > least anything that's iterable and hashable and whose elements are > single character strings, or at least objects which have an upper() > method which ...". > > So in practice you end up writing "a string", and leave the rest of the > 'contract' implicit. Python's doc (and third-part modules too) are full of 'string-like', 'dict-like', 'file-like' etc... > But that can lead to difficulties if people working > on the code have different ideas of what that implicit contract is -- is > it "a string, or anything else which works with the current > implementation", or perhaps "you may pass something other than a string > so long as you take responsibility for making it support all the > necessary operations, even if the implementation changes", or is there > some project-wide convention about how much like a string such things > have to be? > > I think this kind of vagueness can work well within a lump of code which > is maintained as a piece, but it's good to divide up programs into > components with more carefully documented interfaces. And it's at that > level that I think doing explicit parameter validation can be helpful. I'm afraid your strong ADA background shows up here... When I started using Python some 7 years ago, I strongly believed in strong static typing, and spent monthes fighting against the language. >>> If you validate, you can raise an exception from the start of your >>> function with a fairly explicit message. And ? >>> If you don't validate, >>> you're likely to end up with an exception whose message is something >>> like 'iteration over non-sequence', Which is quite explicit >>> and it might be raised from some >>> function nested several levels deeper in. And what's the problem ? You have a full traceback, and since you know which code is yours and which is not, it's usually quite easy to spot where you passed something wrong. >> And what is the stack backtrace for, actually ? > > I'm not sure that you intended that as a serious question, Deadly serious. > but I'll > answer it anyway. > > In an ideal world, the stack backtrace is there to help me work with > code that I'm maintaining. It isn't there to help me grub around in the > source of someone else's code which is giving me an unhelpful error > message. Just as, in an ideal world, I should be able to determine how > to correctly use someone else's code by reading its documentation rather > than its source. The backtrace is here to help understanding what went wrong, and it's usually quite good at it. And remember that Python has an interactive interpreter that let you try out how a module works - which is usually enough. > I think this is a 'quality of implementation' issue. When you start > using Python you pretty rapidly pick up the idea that a message like > 'len() of unsized object' from (say) a standard library function > probably just means that you didn't pass the value you intended to; but > that doesn't mean it's a good error message. These things do add up to > make the daily business of programming less efficient. Strange enough, we see quite a few experimented C/C++/Java programmers explaining how much Python (or Ruby FWIW) improved their productivity... > >>> The latter can be harder for the user of your function to debug (in >>> particular, it may not be easy to see that the problem was an invalid >>> parameter to your function rather than a bug in your function itself, >>> or corrupt data elsewhere in the system). > >> docstrings and unit-tests should make it clear. > > I don't see that either of those things remove the issues I described. > > >> Now if one want to have to declare everything three times and write >> layers and layers of adapters and wrappers, well, he knows where to >> find Java !-) > > Right. But using Python there is a position between 'writing layers and > layers of adapters and wrappers' and 'never validate anything': put > explicit checks in particular functions where they're likely to do most > good. Did I say otherwise ? Now the question is "where will explicit checks do most good ?" !-) > For example, it's often helpful to explicitly validate if you're going ... to use data coming from the outside world. > >>> This might well lead to your program apparently completing >>> successfully but giving the wrong result (which is usually the kind >>> of error you most want to avoid). > >> Compared to what C or C++ can do to your system, this is still a >> pretty minor bug - and probably one of the most likely to be detected >> very early > > I disagree. What C or C++ will do, very often, is produce a segmentation > fault. If that's all you get, then lucky you. What's funny with UBs is that they are, well, undefined !-) > That may well turn out to be hard to debug, but it's considerably > more likely to be detected early than a successful exit status with > incorrect output. Don't you test your programs ? From Thomas.Ploch at gmx.net Fri Jan 5 16:17:53 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 22:17:53 +0100 Subject: PyGreSQL Install In-Reply-To: <1168030553.913612.309020@q40g2000cwq.googlegroups.com> References: <1168030553.913612.309020@q40g2000cwq.googlegroups.com> Message-ID: <459EC081.5060007@gmx.net> goodepic schrieb: > I successfully installed postgresql and pygresql from source on my > MacBook 2ghz Intel core duo running os x 10.4.8. However, pygresql > installed under the defualt python 2.3 installation, while I've been > upgrading and working in 2.5, and have invested too much time to go > back to 2.3. I definitely don't know where every file is, but I know > that the site-packages folder where I need pgdb to be is > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages. > This is where I have pypar, pynum, numeric, etc. PyGreSQL installed > in the default > /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages. > > > Anyone know where I can edit setup.py or what flags I can use to force > the install onto 2.5? > > Thanks! > You should try: $ python2.5 setup.py install Normally it gets installed into the directory of the python version you use when running setup.py. Is python 2.3 still the default on MAC OS X 10.4? I thought they switched to python 2.4. Thomas From kylotan at gmail.com Thu Jan 25 06:01:15 2007 From: kylotan at gmail.com (Ben Sizer) Date: 25 Jan 2007 03:01:15 -0800 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> On Jan 24, 1:50 am, John Nagle wrote: > In the Perl, Java, PHP, and C/C++ worlds, the equivalent > functions just work. That's because, in those worlds, either the > development team for the language or the development team > for the subsystem takes responsibility for making them work. > Only Python doesn't do that. I have much sympathy for your position. I think the problem is that Python is quite capable in many areas, such that the people in the community with the expertise to extend the language and libraries, are usually the ones who've been happily using the polished features for years and have found they need nothing more. And the ones who need those features probably got bored of waiting for progress long ago. You get the responses you do from years of natural selection in the community. I think that is why many of the SIGs are stagnant, why the standard library has so much fluff yet still lacks in key areas such as multimedia and web development, etc. People can say, "if you want it done, why aren't you doing it?", and is a fair question, but it doesn't alter the fact of Python's deficiencies in certain areas when compared with other languages. -- Ben Sizer From lrahuel.notgood at voila.fr Wed Jan 31 10:42:02 2007 From: lrahuel.notgood at voila.fr (Laurent Rahuel) Date: Wed, 31 Jan 2007 16:42:02 +0100 Subject: "Correct" db adapter References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> Message-ID: <45c0b8cd$0$5072$ba4acef3@news.orange.fr> Maybe you should take a look at sqlalchemy king kikapu wrote: > Hi to all, > > i have started a month ago to seriously studying Python. I am now > looking at the databases stuff > and i want the opinion of more experienced Python programmers (than > me) at the following : > > I see that there are a lot of databases adapters on the net, some > following the DB-API 2.0 and some others do not. I want to use a db- > module that do not tie me down to a specific database and that fully > supports DB-API 2.0 > Now i am using Sql Server but who knows about tomorrow. > > I started using pyodbc and looking how i can e.x. call stored > procedure with arguments and all that stuff. > This is using ODBC syntac and i found enough info on the net. > > Is the approach i took the "correct" one or is there a better db- > module so i can use ? > > Thanks in advance From chizzua at gmail.com Fri Jan 5 15:39:59 2007 From: chizzua at gmail.com (jbchua) Date: 5 Jan 2007 12:39:59 -0800 Subject: Learning to program in Python In-Reply-To: <1168029133.866590.43770@i15g2000cwa.googlegroups.com> References: <1168028517.005902.172880@11g2000cwr.googlegroups.com> <1168029133.866590.43770@i15g2000cwa.googlegroups.com> Message-ID: <1168029599.576718.74200@i15g2000cwa.googlegroups.com> John Henry wrote: > jbchua wrote: > > Hello everybody. > > > > I am an Electrical Engineering major and have dabbled in several > > languages such as Python, C, and Java in my spare time because of my > > interest in programming. However, I have not done any practical > > programming because I have no idea where to get started. I taught > > myself these languages basically by e-tutorials and books. This makes > > me feel as if I don't really know how to implement these languages. > > Does anybody have any advice on where to start applying my limited > > knowledge practically in order to advance my learning? > > Which area of EE are you in? Or just starting on that as well? > > If you're just starting, chanllege yourself to build a R mesh and > calculate the Thevenin equivalent looking out from a particular node. > Then you can expand that to an RLC network. > > Besure to use Objects, think in terms of objects, and code in objects. > Don't hard code the data type. You'll be able to see how magical the > Duck Typing is in Python. > > Have fun. I'm a freshman-- I have yet to take any actual EE classes. I am actually thinking of maybe changing my focus towards Computer Science or at least minoring in it. To be perfectly honest, I have no idea what you just asked me to do ;\ From nick at craig-wood.com Mon Jan 22 04:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 22 Jan 2007 03:30:06 -0600 Subject: mmap caching References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <45B3DD4D.3010009@v.loewis.de> <1169422167.683707.264180@a75g2000cwd.googlegroups.com> <45B3FDA7.9030702@v.loewis.de> Message-ID: Martin v. L?wis wrote: > In fact, memory that is read in because of mmap should *never* cause > a MemoryError. Python calls MapViewOfFile when mmap.mmap is invoked, > at which point the operating commits to providing that much address > space to the application, along with backing storage on disk > (typically, from the file being mapped, unless it is an anonymous > map). Later access to the mapped range cannot fail (except for > hardware errors), and if it would, you wouldn't see a MemoryError. So presumably it is python generating a MemoryError. It is asking for a new bit of memory and it is failing so it throws a MemoryError. Could memory allocation under windows be affected by a large chunk of mmap()ed file which is physically swapped in at the time of the allocation? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From deets at nospam.web.de Sat Jan 6 19:41:44 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Jan 2007 01:41:44 +0100 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <50atuaF1bb2k9U1@mid.uni-berlin.de> time.swift at gmail.com schrieb: > Coming from a C++ / C# background, the lack of emphasis on private data > seems weird to me. I've often found wrapping private data useful to > prevent bugs and enforce error checking.. > > It appears to me (perhaps wrongly) that Python prefers to leave class > data public. What is the logic behind that choice? Private data is a convention, not a strict enforcement, for both Java and C++. Depending on your C++ compiler, a simple #define private public will give you access to all data you want. Besides the fact that casting to a void* pointer and just accessing the private parts isn't rocket science. The same applies to java, for whatever reasons (I presume serialization), you can access private fields via reflection. In python, private members are usually declared using a single or double underscore. And the basic idea is: "if you tamper with this, you've been warned". Which is the way coding between consenting adults should be. To be honest: I've stumbled over more cases of unescessary hoops to jump through due to private declarations than bugs caused of me exploiting things I've been told by the compiler not to tamper with it. Summary: not important, forget about it, enjoy python! Diez From nszabolcs at gmail.com Mon Jan 29 11:38:13 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 08:38:13 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: <1170088693.768440.26580@h3g2000cwc.googlegroups.com> > If you really want a hack, here it is: > > while 1:print > ''.join(__import__('random').choice(__import__('string').letters+'1234567890') > for x in xrange(8)),;n=raw_input() > > This is a one-liner (though mail transmission may split it up), no > import statements. If someone can come up with an even smaller version, > feel free to post. :) while 1:i=__import__;print''.join(i('random').choice(i('string').letters +'1234567890')for x in range(8)),;raw_input() same but shorter: i = __import__; xrange -> range (why use xrange? range is faster and simpler for small ranges) n =(not needed) From osv at javad.com Thu Jan 11 07:54:53 2007 From: osv at javad.com (Sergei Organov) Date: Thu, 11 Jan 2007 15:54:53 +0300 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Message-ID: nmm1 at cus.cam.ac.uk (Nick Maclaren) writes: [...] > I mean precisely the first. > > The C99 standard uses a bizarre consistency model, which requires serial > execution, and its consistency is defined in terms of only volatile > objects and external I/O. Any form of memory access, signalling or > whatever is outside that, and is undefined behaviour. > > POSIX uses a different but equally bizarre one, based on some function > calls being "thread-safe" and others forcing "consistency" (which is > not actually defined, and there are many possible, incompatible, > interpretations). It leaves all language aspects (including allowed > code movement) to C. > > There are no concepts in common between C's and POSIX's consistency > specifications (even when they are precise enough to use), and so no > way of mapping the two standards together. Ah, now I see what you mean. Even though I only partly agree with what you've said above, I'll stop arguing as it gets too off-topic for this group. Thank you for explanations. -- Sergei. From jstroud at mbi.ucla.edu Sun Jan 28 19:36:27 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 28 Jan 2007 16:36:27 -0800 Subject: Function to create Tkinter PhotoImages from directory? In-Reply-To: References: Message-ID: Kevin Walzer wrote: > I am trying to create a number of Tk PhotoImages from a single > directory. Currently I am hard-coding file names and image names, like so: > > def makeImages(self): > self.imagedir = (os.getcwd() + '/images/') > self.folder_new=PhotoImage(file=self.imagedir + 'folder_new.gif') > self.save=PhotoImage(file = self.imagedir + 'save.gif') > self.folder=PhotoImage(file=self.imagedir + 'folder.gif') > self.help=PhotoImage(file=self.imagedir + 'help.gif') > self.fontsmall=PhotoImage(file=self.imagedir + 'fontsmall.gif') > self.stop=PhotoImage(file=self.imagedir + 'stop.gif') > > What I'd like to do is glob the directory and create images with the > same name as the gif file, but I can't figure out how to get that to > work. Can anyone help? > This is platform independent (and untested): import glob import os def makeImages(self): import glob import os self.imagedir = os.path.join(os.getcwd(), 'images') pattern = os.path.join(self.imagedir, '*.gif') image_names = glob.glob(pattern) for name in image_names: base = os.path.basename(name).split('.')[0] pathname = os.path.join(self.imagedir, n) self.setattr(base, Photoimage(file=pathname)) James From pythonnews at nospam.jmbc.fr Tue Jan 30 16:47:29 2007 From: pythonnews at nospam.jmbc.fr (jean-michel bain-cornu) Date: Tue, 30 Jan 2007 22:47:29 +0100 Subject: DCOP memory leak? In-Reply-To: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> References: <1170193025.867274.242350@m58g2000cwm.googlegroups.com> Message-ID: <45bfbd10$0$21143$7a628cd7@news.club-internet.fr> > Now, I have to call DCOP very often and I noticed that every time I > make a DCOP call my program keeps growing in memory size. > > To make sure it was DCOP i wrote the small program below: > > from dcopext import DCOPClient, DCOPApp > > while 0==0: > dcop=DCOPClient() > dcop.attach() > AmarokDcopRes = DCOPApp ("amarok", dcop) > ok, Ms = AmarokDcopRes.player.trackCurrentTimeMs() > print Ms > > If you run this script and monitor it's memory use you'll see that it > keeps growing. It's probably silly, but what's about 'del dcop' as the last line of your loop ? From goodepic at gmail.com Thu Jan 4 16:35:14 2007 From: goodepic at gmail.com (goodepic) Date: 4 Jan 2007 13:35:14 -0800 Subject: Problem Running Working Code on Mac Message-ID: <1167946511.531632.41750@11g2000cwr.googlegroups.com> I'm newish to python and just got my first mac, so sorry if this is stupid. I have a little app developed by someone else in wxGlade that implements a complex stats package and language package, all in python. It works fine on my work PC, but not on my laptop. I have a new macbook 2ghz core duo, running os x 10.4.8 with python 2.5 installed (I didn't erase the base 2.3, just put /usr/local/bin at the start of $PATH), along with the latest wxPython, can't remember the version number. I need to add a few more components from the stats package, and I'd like eventually to pretty up the cheap GUI I was given, but that'd be icing. When I try either python or pythonw , I get this error: WARNING:root:Could not import module "PyPar", defining sequential interface WARNING:root:No MySQLdb module available WARNING:root:No pgdb module (PostgreSQL) available Traceback (most recent call last): File "febrlgui.py", line 513, in frame_1 = MyFrame(None, -1, "") File "febrlgui.py", line 198, in __init__ self.__set_properties() File "febrlgui.py", line 355, in __set_properties self.a_box1.SetSelection(-1) File "//Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/wx-2.8-mac-ansi/wx/_core.py", line 11487, in SetSelection return _core_.ItemContainer_SetSelection(*args, **kwargs) wx._core.PyAssertionError: C++ assertion "IsValid(n)" failed at /BUILD/wxPython-src-2.8.0.1/src/mac/carbon/choice.cpp(242) in GetString(): wxChoice::GetString(): invalid index Of course I'm traveling soon and need to be able to work on this on my macbook, so it's down to panic time. Any help is GREATLY appreciated. Thanks, Matt From bruno.desthuilliers at websiteburo.com Thu Jan 25 05:07:59 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Thu, 25 Jan 2007 11:07:59 +0100 Subject: Static variables In-Reply-To: <1169687035.433771.177900@v45g2000cwv.googlegroups.com> References: <45b7cfd4$0$16160$426a74cc@news.free.fr> <1169687035.433771.177900@v45g2000cwv.googlegroups.com> Message-ID: <45b8817f$0$16154$426a74cc@news.free.fr> bearophileHUGS at lycos.com a ?crit : > Bruno Desthuilliers: >> And this let you share state between functions: >> >> def make_counter(start_at=0, step=1): >> count = [start_at] >> def inc(): >> count[0] += step >> return count[0] >> def reset(): >> count[0] = [start_at] >> return count[0] >> def peek(): >> return count[0] >> >> return inc, reset, peek >> >> foo, bar, baaz = make_counter(42, -1) >> print baaz() >> for x in range(5): >> print foo() >> print bar() >> print baaz() > > An interesting solution, I have never created such grouped clorures. It's a common idiom in some functional languages. > I > don't know if this solution is better than a class with some class > attributes plus some class methods... It's somewhat equivalent, but in Python, I'd surely use a class instead !-) From py at th.on Tue Jan 23 18:48:59 2007 From: py at th.on (py) Date: Tue, 23 Jan 2007 23:48:59 GMT Subject: smtplib starttls gmail example Message-ID: Hi, Jean Paul. I read your code with interest. I wonder, does twisted also raise the socket error or does it know about this apparently well-known and often ignored incompatibility between the standard and the implementations? Something else has occurred to me. After starting tls, all the xmitted commands and data are encrypted before they leave the client machine. so obviously they have to be decrypted by the server's socket lib before the smtp daemon can do what it's supposed to do. but i wonder if the encryption of the trailing \n.\n has something to do with the socket error, given that the error msg says something about premature EOF. -dave From martin at v.loewis.de Thu Jan 4 12:08:27 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Jan 2007 18:08:27 +0100 Subject: Best way to implement a timed queue? In-Reply-To: References: Message-ID: <459d348b$0$28356$9b622d9e@news.freenet.de> Thomas Ploch schrieb: > I am having troubles with implementing a timed queue. I am using the > 'Queue' module to manage several queues. But I want a timed access, i.e. > only 2 fetches per second max. I am horribly stuck on even how I > actually could write it. Has somebody done that before? And when yes, > how is the best way to implement it? You could put a wrapper around the queue which synchronizes the get operations, and then delays access until 1s after the last-but-one access. The following code is untested: import threading, time class ThrottledQueue(threading.Queue): def __init__(self): threading.Queue.__init__(self) self.old = self.older = 0 self.get_lock = threading.Lock() def get(self): with self.get_lock: # synchronize get # check whether the next get should be in the future now = time.time() next = self.older + 1 if now < next: time.sleep(next-now) # really fetch one item; this may block result = threading.Queue.get(self) self.older = self.old # set the last get time to the time when the get completed, # not when it started self.old = time.time() return result HTH, Martin From oyekomova at hotmail.com Sat Jan 13 19:39:34 2007 From: oyekomova at hotmail.com (oyekomova) Date: 13 Jan 2007 16:39:34 -0800 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168728465.178605.218850@q2g2000cwa.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168715634.695961.14710@l53g2000cwa.googlegroups.com> <1168728465.178605.218850@q2g2000cwa.googlegroups.com> Message-ID: <1168735174.140171.74930@v45g2000cwv.googlegroups.com> Thanks for your note. I have 1Gig of RAM. Also, Matlab has no problem in reading the file into memory. I am just running Istvan's code that was posted earlier. import time, csv, random from numpy import array def make_data(rows=1E6, cols=6): fp = open('data.txt', 'wt') counter = range(cols) for row in xrange( int(rows) ): vals = map(str, [ random.random() for x in counter ] ) fp.write( '%s\n' % ','.join( vals ) ) fp.close() def read_test(): start = time.clock() reader = csv.reader( file('data.txt') ) data = [ map(float, row) for row in reader ] data = array(data, dtype = float) print 'Data size', len(data) print 'Elapsed', time.clock() - start #make_data() read_test() On Jan 13, 5:47 pm, "sturlamolden" wrote: > oyekomova wrote: > > Thanks to everyone for their excellent suggestions. I was able to > > acheive the following results with all your suggestions. However, I am > > unable to cross file size of 6 million rows. I would appreciate any > > helpful suggestions on avoiding memory errors. None of the solutions > > posted was able to cross this limit.The error message means you are running out of RAM. > > With 6 million rows and 6 columns, the size of the data array is (only) > 274 MiB. I have no problem allocating it on my laptop. How large is the > csv file and how much RAM do you have? > > Also it helps to post the whole code you are trying to run. I don't > care much for guesswork. From david at boddie.org.uk Thu Jan 18 10:59:07 2007 From: david at boddie.org.uk (David Boddie) Date: 18 Jan 2007 07:59:07 -0800 Subject: The proper use of QSignalMapper References: <1169045073.138626.60770@l53g2000cwa.googlegroups.com> <1169049100.393777.269350@v45g2000cwv.googlegroups.com> <1169085859.586698.149400@51g2000cwl.googlegroups.com> Message-ID: <1169135947.039984.108930@51g2000cwl.googlegroups.com> borntonetwork wrote: > Thanks, David, for you help. > > When I change the slot function to what you show in your second > example, I get the same results: nothing. This may be due to something I missed in your code. When you connect the signal from the signal mapper to your class, you need to specify the signal as a C++ signature as well: self.connect(self.signalMapper, QtCore.SIGNAL( "mapped(int)"), self.deleteProductIngredient) The second example should now work. Looking at the first example, which uses SLOT() rather than specifying a Python method, the following might be due to the way you call connect, though it is surprising: > When I change it to what you > have in your first example, I get the following: > > Object::connect: No such slot QApplication::map() > Object::connect: (sender name: 'chkProductIngredientsDelete_1') > Object::connect: (receiver name: 'main.py') [...] It looks like you should try something like this: self.connect(w, QtCore.SIGNAL("stateChanged(int)"), self.signalMapper, QtCore.SLOT("map()")) I can't understand why calling self.app.connect() would cause the connection to be attempted between self.signalMapper and self.app. Maybe someone on the PyQt/PyKDE mailing list would be able to explain the behaviour you're seeing: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde David From tjreedy at udel.edu Tue Jan 23 19:46:46 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Jan 2007 19:46:46 -0500 Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> Message-ID: "gangesmaster" wrote in message news:1169563580.634000.122540 at v45g2000cwv.googlegroups.com... | so this is why [lambda: i for i in range(10)] will always return 9. No, it returns a list of 10 identical functions which each return the current (when executed) global (module) variable i. Except for names, 'lambda:i' abbreviates 'def f(): return i'. >>> a=[lambda: i for i in range(10)] >>> i=42 >>> for j in range(10): print a[j]() 42 42 42 42 42 42 42 42 42 42 >>> for i in range(10): print a[i]() 0 1 2 3 4 5 6 7 8 9 >>> del i >>> for j in range(10): print a[j]() Traceback (most recent call last): File "", line 1, in -toplevel- for j in range(10): print a[j]() File "", line 1, in a=[lambda: i for i in range(10)] NameError: global name 'i' is not defined | imho that's a bug, not a feature. The developers now think it a mistake to let the list comp variable 'leak' into the global scope. It leads to the sort of confusion that you repeated. In Py3, the leak will be plugged, so one will get an exception, as in the last example, unless i (or whatever) is defined outside the list comp. Terry Jan Reedy From __peter__ at web.de Tue Jan 9 07:23:11 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 Jan 2007 13:23:11 +0100 Subject: how to find the longst element list of lists References: Message-ID: Steven D'Aprano wrote: > On Mon, 08 Jan 2007 13:55:40 +0100, Peter Otten wrote: > >>> The precise results depend on the version of Python you're running, the >>> amount of memory you have, other processes running, and the details of >>> what's in the list you are trying to sort. But as my test shows, sort >>> has some overhead that makes it a trivial amount slower for sufficiently >>> small lists, but for everything else you're highly unlikely to beat it. >> >> Try again with tN.timeit(1) and a second list that is random.shuffle()d >> and copied to L before each measurement. list.sort() treats already >> sorted lists specially. > > Or, simply shuffle the list itself. Why copy it? To feed the same data to every algorithm. This is an act of fairness, though with negligable impact on the benchmark results, I suspect :-) > In my tests, sorting still wins, and by roughly the same factor. > One optimization that might shift the balance would be to remove the > list copying in the non-sort code (list_of_lists[1:]). That's going to be > very time consuming for big lists. With the tweak that you suggest above the loop wins for 100 items on my machine... N loop iloop max sort 1 0.000008 0.000019 0.000012 0.000010 10 0.000008 0.000008 0.000009 0.000013 100 0.000095 0.000037 0.000028 0.000088 1000 0.000374 0.000341 0.001304 0.001204 5000 0.001930 0.001719 0.001212 0.007062 if you can trust the timings for small values of N. The script to generate this table has become somewhat baroque :-) import random import timeit timers = [] def bench(f): t = timeit.Timer("getlongest(L)", "from __main__ import %s as getlongest, L, items; L[:] = items" % f.__name__) t.name = f.__name__.split("_")[-1] t.function = f timers.append(t) return f @bench def getlongest_loop(lists): longest_list = lists[0] longest_length = len(longest_list) for a_list in lists[1:]: a_length = len(a_list) if a_length > longest_length: longest_list, longest_length = a_list, a_length return longest_list @bench def getlongest_iloop(lists): lists = iter(lists) longest_list = lists.next() longest_length = len(longest_list) for a_list in lists: a_length = len(a_list) if a_length > longest_length: longest_list, longest_length = a_list, a_length return longest_list @bench def getlongest_max(lists): return max(lists, key=len) @bench def getlongest_sort(lists): lists.sort(key=len) return lists[-1] def make_list_of_lists(length): lol = [[None]*i for i in xrange(length)] random.shuffle(lol) return lol def measure(N): print "%10d" % N, for t in timers: print "%10.6f" % t.timeit(1), print if __name__ == "__main__": import sys if "--test" in sys.argv: L = make_list_of_lists(100) expected = [None]*99 for t in timers: assert t.function(L[:]) == expected raise SystemExit L = [] print "N".rjust(10), print " ".join(t.name.rjust(10) for t in timers) for N in [1, 10, 100, 1000, 5000]: items = make_list_of_lists(N) measure(N) Peter From alec at mihailovs.com Fri Jan 5 04:50:06 2007 From: alec at mihailovs.com (Alec Mihailovs) Date: Fri, 05 Jan 2007 09:50:06 GMT Subject: Memoization in Python Message-ID: Following Antti Karttunen suggestion, I wrote the following simple decorator for creating functions with cache (something like 'option remember' in Maple). Just wanted to share it: def function_with_cache(f): def new_f(*args): if args in new_f.cache: return new_f.cache[args] result=f(*args) new_f.cache[args]=result return result new_f.cache={} new_f.func_name=f.func_name return new_f For example, @function_with_cache def A000045(n): if n<2: return n return A000045(n-1)+A000045(n-2) A000045(3) 2 A000045.cache {(2,): 1, (0,): 0, (3,): 2, (1,): 1} Or, another example, @function_with_cache def binomial(m,n): if m <0 or n >m: return 0 if n==0 or m==n: return 1 return binomial(m-1,n)+binomial(m-1,n-1) binomial(5,3) 10 binomial.cache {(3, 2): 3, (3, 3): 1, (3, 1): 3, (2, 1): 2, (2, 0): 1, (4, 3): 4, (2, 2): 1, (4, 2): 6, (1, 0): 1, (1, 1): 1, (5, 3): 10} Alec Mihailovs http://mihailovs.com/Alec/ From arn.zart at gmail.com Thu Jan 25 11:13:30 2007 From: arn.zart at gmail.com (arn.zart at gmail.com) Date: 25 Jan 2007 08:13:30 -0800 Subject: match nested parenthesis In-Reply-To: <1169521381.814119.27020@11g2000cwr.googlegroups.com> References: <1169521381.814119.27020@11g2000cwr.googlegroups.com> Message-ID: <1169741610.766625.134960@m58g2000cwm.googlegroups.com> s99999999s2003 at yahoo.com wrote: > hi > i wish to find an reg exp for matching nested parenthesis of varying > level like > string = > "somewords1(words(somewords2)-(some(some)words3)somestuff)somestuff" > and be able to evaluate the pair starting from the inner most(the > deepest level) , ie (some) > up till the outer most. What is a good reg exp to do this? or is simple > string manipulations enough? > thanks Evaluation using re.sub() and recursion (3 lines of code): def eval_sub(expr): r"""Evaluate subexpressions in nested paired delimiters. For example, ? single left-pointing angle quotation ‹ ? single right-pointing angle quotation › >>> eval_sub('?3 * ?3 + ??1 + 1? * 2???') '21' >>> eval_sub('?3 * 3 + ??1 + 1? * 2???') # test mismatched delimiters '13\x9b' >>> '\x9b' == '?' # encoding ISO-8859-1 True >>> eval_sub('3 * ??1 + 1? * 2 + 3?') # test absence of outer delimiters '3 * 7' """ val, n = re.subn("?([^??]+)?", lambda m: str(eval(m.group(1))), expr) if n == 0: return val return eval_sub(val) #end This is just a proof of concept. From bdesth.quelquechose at free.quelquepart.fr Fri Jan 5 08:23:36 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Jan 2007 14:23:36 +0100 Subject: checking one's type In-Reply-To: References: Message-ID: <459e4b28$0$289$426a74cc@news.free.fr> belinda thom a ?crit : > Hi, > > I've been using the following hack to determine if a type is acceptable > and I suspect there is a better way to do it: > > e.g. > > if type(s) == type("") : > print "okay, i'm happy you're a string" if isinstance(s, basestring): print """ There are very few cases where it makes sens to do such a test anyway... """ > If anyone knows a better way, I'm all ears. A few special cases excepted (ie your function can accept either a string or a sequence of strings...), the best thing is usually to not check types at all... From bj_666 at gmx.net Mon Jan 22 18:10:11 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 23 Jan 2007 00:10:11 +0100 Subject: beep or sound playing under linux References: Message-ID: In , hg wrote: > Is there a way to do that ? Maybe this helps: http://paste.pocoo.org/show/316/ Ciao, Marc 'BlackJack' Rintsch From ralf at schoenian-online.de Mon Jan 29 15:03:04 2007 From: ralf at schoenian-online.de (=?ISO-8859-1?Q?Ralf_Sch=F6nian?=) Date: Mon, 29 Jan 2007 21:03:04 +0100 Subject: Sourcing Python Developers In-Reply-To: <45BE4348.9020500@gmail.com> References: <45BE4348.9020500@gmail.com> Message-ID: <45be52f5$1@news.arcor-ip.de> Kartic schrieb: > Hello, > > My company has quite a few opening involving python expertise. We are > always looking for python resources (and find it difficult filling these > positions, might I add). Is there any place to find developers' resumes > (like finding jobs from http://python.org/community/jobs/)? If any one > knows of a resume repository (other than Monster, Dice, > Costs-an-arm-and-leg job site) please share. Do not know if you have to give your arm or your leg away, but maybe the following place is of interest for you: http://www.opensourcexperts.com Ralf Schoenian From mail at microcorp.co.za Sat Jan 13 04:00:40 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 13 Jan 2007 11:00:40 +0200 Subject: Is there a way to protect a piece of critical code? References: Message-ID: <000401c73797$3e180760$03000080@hendrik> "robert" wrote: > Hendrik van Rooyen wrote: > > So far I have only used dicts to pass functions around > > in a relatively unimaginative static jump table like way... > > > Probably one has just to see that one can a pass a function object > (or any callable) around as any other object. > Similar to a function address in assembler/C but very comfortable > and with the comfort of closures (which automatically hold the > status of local variables): > > def f(): > print "hello" > > def g(func): > print "I'll do it ..." > func() > print "done." > > > def run(x): > g(f) > a="local variable\n" > def h(): > b="inner local" > print "inner function" > print x,a,b > g(h) > g(lambda:sys.stdout.write(a)) > > run(1) > > From there its just natural to not pass dead objects through an > inter-thread queue, but just code as it or even a "piece of > critical code" ... > A small step in thought, but a big step in effect - soon > eliminating bunches of worries about queues, pop-races/None > objects, protocol, serialization, critical sections, thousands of > locks etc. Thanks - this simplicity takes a bit of getting used to - I am used to passing what are effective entry point pointers around while building state machines that run under interrupt - effectively dynamically changing vectors for ticker based routines. But on the low level, trying to pass data at the same time is a bit of a pain, as you have to look after it yourself, so the temptation is great to only use globals... This passing_the_function_along_with_its_data is neat... *sigh* now if only it were possible to do it over a serial link, in the same way as through a queue (I know about Pyro, but this does not seem quite the same thing ) I suppose its not really possible - because while I suspect only "pointers" get passed through say a queue, you would have to send the actual code along as well over a link - or you need a mirror of the code on both sides, and a way to translate addresses - which I suppose is why Pyro looks like it does. I am working on something similar on a *very* small scale at the moment, in the context of control of physical things. Hence the sigh. - Hendrik From creechm at gmail.com Thu Jan 11 14:41:15 2007 From: creechm at gmail.com (Mark) Date: 11 Jan 2007 11:41:15 -0800 Subject: Need better run/edit method. I have to restart the shell after every script change. Message-ID: <1168544475.849070.92160@77g2000hsv.googlegroups.com> Hello, What I need to know is if there is a better method to run/edit modules on my pc. I'm currently running the IDLE shell under Python 2.5, on Windows XP. Every time I edit my .txt or .py file, I have to restart the IDLE shell for the changes to take effect. It's pretty annoying. Assuming IDLE is already open, here are the steps that I typically take: 1. Open .txt version of module or script using notepad 2. make changes 3. save .txt file as .txt file 4. save .txt file as .py file 5. reset IDLE 6. import module again As you can see, I'm wasting a lot of time with this method. Maybe there is some better sofware available, or maybe I'm just not utilizing the tools at my disposal. Either way I would greatly appreciate any insight into this problem. Thanks in advance, Mark From practicalperl at gmail.com Fri Jan 19 01:51:44 2007 From: practicalperl at gmail.com (Jm lists) Date: Fri, 19 Jan 2007 14:51:44 +0800 Subject: Why this script can work? Message-ID: Please help with this script: class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self,length,atleast): Exception.__init__(self) self.length=length self.atleast=atleast try: s=raw_input('Enter something --> ') if len(s)<3: raise ShortInputException(len(s),3) # Other work can continue as usual here except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException,x: print 'ShortInputException: The input was of length %d, was expecting at least %d' %(x.length,x.atleast) else: print 'No exception was raised.' My questions are: 1) ShortInputException,x: what's the 'x'? where is it coming? 2) The 'if' and 'else' are not in the same indent scope,why this can work? Thanks in advance. From missive at frontiernet.net Thu Jan 25 17:41:09 2007 From: missive at frontiernet.net (Lee Harr) Date: Thu, 25 Jan 2007 22:41:09 GMT Subject: pdf to text References: <86714$45b9254c$54d1d767$3741@news.chello.no> Message-ID: <9mauh.1282$B25.1253@news01.roc.ny> > Perhaps I'm just using pdftotext wrong? Here's how I was using it: > > sout = os.popen('pdftotext "%s" - ' %f) If you are having trouble with popen (not unlikely) how about just writing to a temporary file and reading the text from there? I've used pdftotext several times in the past few weeks (but not on windows). It was a major time saver for me. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 19:03:41 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 09 Jan 2007 01:03:41 +0100 Subject: Execute binary code References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <50fujcF1g1nplU2@mid.individual.net> <1168298153.982394.181090@q40g2000cwq.googlegroups.com> Message-ID: <50g4etF1ff6ceU1@mid.individual.net> citronelu at yahoo.com wrote: > The code I try to execute is Windows specific and it is binary, > not python. Furthermore, it is stored in a variable within the > parent python script, not stored on harddisk as a file. Sure, I just wanted to show that your special application is not specific for trojan horses oder viruses. One could achieve similar replication functionality with python by itself. Regards, Bj?rn -- BOFH excuse #217: The MGs ran out of gas. From gherron at digipen.edu Wed Jan 31 02:28:17 2007 From: gherron at digipen.edu (Gary Herron) Date: Tue, 30 Jan 2007 23:28:17 -0800 Subject: PY Zip In-Reply-To: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> References: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> Message-ID: <45C04511.1090005@digipen.edu> GISDude wrote: > Hi all. > > I am trying to find a module that has a Zip utility that I can use in > Python. I would like to be able to call the module and ZIP up a > directory. I thought there was such a module, but I have not been able > to find it. > > I need this to be able to be used in Python Win. Is there a ZIP utilty > already stored with a basic PYTHON download? > > Thanks all. > > The module you want is called zipfile, and its part of the standard library. See: http://docs.python.org/lib/module-zipfile.html for documentation. Gary Herron From sturlamolden at yahoo.no Sat Jan 20 22:07:47 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 20 Jan 2007 19:07:47 -0800 Subject: A solution to the MSVCRT vs MSVCR71 problem? Message-ID: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> This question has been asked many times, and last time I was accused of spreading FUD. So now I will rather propose a solution. The reason for the problem is as follows: The binary installer for Python built by te python.org team is compiled with Microsoft Visual Studio 2003. It is linked with the C runtime msvcrt71.dll. The copyright to msvcrt71.dll is owned by Microsoft, and it is not an integral part of the Windows operating system. This leads to two distinct problems: Problem 1: You want to use a particular compiler to build a Python extension library, but it links with the wrong CRT. Typical examples are MinGW, Microsoft Visual C++ 6.0 and Microsoft Visual C++ Express. There is a remedy for MinGW, but not for the other two. Problem 2: You want to distribute a program created Py2Exe, but has no license for Visual Studio 2003. You are therefore not allowed to redistribute msvcrt71.dll. But without this DLL your program will not work. As a side note: Visual Studio 2003 is out of sale, so if you don't have it already you may be out of luck. The solution: modify the IAT of to use the correct binary. The process is really simple: Solution to problem 1: Compile with your compiler or choice, never mind which CRT are used. Use a 'dumpbin' program, find all references to msvcrt in the binary DLL file. Create a dll with name "py_crt" that exports these functions but redirects them to msvcrt71. That is, in the file py_crt.def we put something like EXPORTS malloc=msvcr71.malloc free=msvcr71.free etc. Compile the DLL py_crt.dll and then open your pyd file in binary mode. Exchange all occurances of the string "msvcrt" (or any other CRT name) with "py_crt". Now your binary should work just fine. What you need to make sure is just that the name of the proxy has the same number of letters as the CRT your compiler linked. So if it is msvcrt81.dll, e.g. use something like py_crt81.dll instead of py_crt.dll. Solution to problem 2: This would be the opposite, involving modifying Python25.dll and all pyd and dll files gathered by Py2Exe to use msvcrt.dll instead of msvcr71.dll. One could e.g. create a DLL called py_cr71.dll that redirects CRT calls to msvcrt.dll or any other CRT of choice. In py_cr71.def we would then have: EXPORTS malloc=msvcrt.malloc free=msvcrt.free etc. And then it is simply a matter of modifying the binaries to load py_cr71.dll instead of msvcrt71.dll. What we need to make this work: 1. A dumpbin facility similar to the one that ships with Visual Studio that can be freely distributed. 2. A python script that parses the output from dumpbin, creates the proxy and redirects the CRT. (I already have such a script working.) Finally, a setup script (setup.py) could automate this task for "problem 1" above. Another variant of the fake-CRT procedure, which would also work, is to create a fake msvcrt71.dll that redirects to your CRT of choice, and replace the msvcrt71.dll that came with Python with that. That is conceptually simpler, as it involves not binary modifications, but someone might mistake your msvcrt71.dll for the msvcrt71.dll from Microsoft. Also antivirus-software might not like attempts to load such a DLL as it would look like your program is hijacked by a trojan (although it is not). What do you think? From felipe.lessa at gmail.com Tue Jan 9 10:44:45 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 9 Jan 2007 13:44:45 -0200 Subject: Determine an object is a subclass of another In-Reply-To: References: <1168353205.066357.39530@42g2000cwt.googlegroups.com> <1168353975.285391.212350@m30g2000cwm.googlegroups.com> <1168354891.334807.58940@s80g2000cwa.googlegroups.com> Message-ID: On 9 Jan 2007 07:01:31 -0800, abcd wrote: > anyways, is there a way to check without having an instance of the > class? In [1]: class A: ...: pass ...: In [2]: class B(A): ...: pass ...: In [3]: issubclass(B, A) Out[3]: True In [4]: isinstance(B(), B) Out[4]: True In [5]: isinstance(B(), A) Out[5]: True -- Felipe. From gagsl-py at yahoo.com.ar Thu Jan 18 10:01:36 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 12:01:36 -0300 Subject: import vs. subdirectory search References: <45AED511.8090307@animats.com> Message-ID: "John Nagle" escribi? en el mensaje news:45AED511.8090307 at animats.com... > I'm running Python 2.3.4 from a CGI script on a shared hosting Linux > system. > The CGI program is being executed from Apache, as "nobody". I have some > local modules installed in "~myname/lib/python"; these include > "MySQLdb" and "M2Crypto". > > Since this is running as "nobody", I append > > /home/myname/lib/python > > to sys.path. > > Within the CGI programs, > > import MySQLdb # works fine > import M2Crypto # works fine > import SSL # "No module named SSL" > > The problem is that SSL is in a subdirectory of the M2Crypto directory, > and that's not being searched. And should *not* be searched, unless the importing module is itself in the M2Crypto directory. > I can execute "import M2Crypto.SSL", > but that doesn't have the same effect; it puts SSL in a different > place in the namespace. I'm trying to avoid that; it causes obscure > aliasing problems. You *could* do: from M2Crypto import SSL, but I think this is not your problem. > On Python 2.4 under Windows 2000, importing from a subdirectory > appears to work. Is that a Python 2.3.4 thing, or a Linux thing, > or something else? No, it should not work as you describe it. Either you have another SSL module in another place, or sys.path includes the M2Crypto directory. On your 2.4 Windows, try this: import sys import SSL print SSL.__file__ print sys.path and see what happens From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 8 17:20:45 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 08 Jan 2007 23:20:45 +0100 Subject: Maths error References: Message-ID: <50fudtF1g1nplU1@mid.individual.net> Rory Campbell-Lange wrote: > Is using the decimal module the best way around this? (I'm > expecting the first sum to match the second). It seem > anachronistic that decimal takes strings as input, though. What's your problem with the result, or what's your goal? Such precision errors with floating point numbers are normal because the precision is limited technically. For floats a and b, you'd seldom say "if a == b:" (because it's often false as in your case) but rather "if a - b < threshold:" for a reasonable threshold value which depends on your application. Also check the recent thread "bizarre floating point output". Regards, Bj?rn -- BOFH excuse #333: A plumber is needed, the network drain is clogged From bignose+hates-spam at benfinney.id.au Wed Jan 31 22:01:49 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Feb 2007 14:01:49 +1100 Subject: division by 7 efficiently ??? References: <1170297774.859006.29490@a75g2000cwd.googlegroups.com> Message-ID: <87veimtwbm.fsf@benfinney.id.au> krypto.wizard at gmail.com writes: > How to divide a number by 7 efficiently without using - or / > operator. We can use the bit operators. I was thinking about bit > shift operator but I don't know the correct answer. I think you are asking for help on a homework assignment in violation of collusion and plagiarism rules of your educational institution, and I claim my ten zorkmids. Please use the resources made available to you in your course of study; this almost certainly does not include having people on discussion forums answer the homework for you. -- \ "I like to go to art museums and name the untitled paintings. | `\ 'Boy With Pail'. 'Kitten On Fire'." -- Steven Wright | _o__) | Ben Finney From mail at microcorp.co.za Tue Jan 9 03:27:56 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 9 Jan 2007 10:27:56 +0200 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com><7x7ivz88af.fsf@ruckus.brouhaha.com><7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: <021c01c733c8$41d98a40$03000080@hendrik> "Steven D'Aprano" wrote: > On Mon, 08 Jan 2007 13:11:14 +0200, Hendrik van Rooyen wrote: > > > When you hear a programmer use the word "probability" - > > then its time to fire him, as in programming even the lowest > > probability is a certainty when you are doing millions of > > things a second. > > That is total and utter nonsense and displays the most appalling > misunderstanding of probability, not to mention a shocking lack of common > sense. Really? Strong words. If you don't understand you need merely ask, so let me elucidate: If there is some small chance of something occurring at run time that can cause code to fail - a "low probability" in all the accepted senses of the word - and a programmer declaims - "There is such a low probability of that occurring and its so difficult to cater for that I won't bother" - then am I supposed to congratulate him on his wisdom and outstanding common sense? Hardly. - If anything can go wrong, it will. - to paraphrase Murphy's law. To illustrate: If there is one place in any piece of code that is critical and not protected, even if its in a relatively rarely called routine, then because of the high speed of operations, and the fact that time is essentially infinite, it WILL fail, sooner or later, no matter how miniscule the apparent probability of it occurring on any one iteration is. How is this a misunderstanding of probability? - probability applies to any one trial, so in a series of trials, when the number of trials is large enough - in the order of the inverse of the probability, then ones expectation must be that the rare occurrence should occur... There is a very low probability that any one gas molecule will collide with any other one in a container - and "Surprise! Surprise! " there is nevertheless something like the mean free path... That kind of covers the math, albeit in a non algebraic way, so as not to confuse what Newton used to call "Little Smatterers"... Now how does all this show a shocking lack of common sense? - Hendrik From hotfigs at gmail.com Sun Jan 7 14:20:44 2007 From: hotfigs at gmail.com (Geoff) Date: 7 Jan 2007 11:20:44 -0800 Subject: OpenBSD, Apache and Python Message-ID: <1168197644.544400.72180@v33g2000cwv.googlegroups.com> Hi! I'm wanting to use openbsd to run a webserver because of its high security. The website is written in python. Before I was using linux with apache 2 and mod_python and this worked well. My problem is that mod_python 3.x does not work on apache 1 which is what comes with openbsd (and has been hardened buy the openbsd guys). One option is to use mod_python 2.x, but this has not seen any development since 2004. I'm now looking at using fastcgi to run my python. This looks like it's going to work fine, though I will be using a fcgi interface such as http://jonpy.sourceforge.net/. There does not seem to be any official fastcgi module for python. Should I be worried about the stability and security of the python fcgi interfaces? Is there something better (more mature / battle tested)? Are there any other options available to me - considering that security is very important? Thanks for any help, Geoff From kw at codebykevin.com Sun Jan 28 19:03:51 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 28 Jan 2007 19:03:51 -0500 Subject: Function to create Tkinter PhotoImages from directory? Message-ID: I am trying to create a number of Tk PhotoImages from a single directory. Currently I am hard-coding file names and image names, like so: def makeImages(self): self.imagedir = (os.getcwd() + '/images/') self.folder_new=PhotoImage(file=self.imagedir + 'folder_new.gif') self.save=PhotoImage(file = self.imagedir + 'save.gif') self.folder=PhotoImage(file=self.imagedir + 'folder.gif') self.help=PhotoImage(file=self.imagedir + 'help.gif') self.fontsmall=PhotoImage(file=self.imagedir + 'fontsmall.gif') self.stop=PhotoImage(file=self.imagedir + 'stop.gif') What I'd like to do is glob the directory and create images with the same name as the gif file, but I can't figure out how to get that to work. Can anyone help? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bearophileHUGS at lycos.com Tue Jan 16 16:40:56 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Jan 2007 13:40:56 -0800 Subject: How can I create a linked list in Python? In-Reply-To: References: Message-ID: <1168983652.192715.235580@a75g2000cwd.googlegroups.com> Gary Herron: > If you really want a list (as Python defines a list - with all the methods) then you should use Python's lists. They are quite efficient and convenient: In CPython they are dynamic arrays, they aren't lists. Try adding elements at the beginning of a list compared to adding elements at the beginning or in the middle of a python "list" and you will see the efficiency differences. > The concept of a linked list if a figment of languages with pointer data types. You may manage a list with a language without pointers, like *basic* (for students) Scheme. Creating a List data type for Python is possible too, without true pointer like ones found in Pascal. >However, you're much better off if you can use Python's list data structure rather >than try to emulate an outdated concept in a modern language. Simple lists today aren't much efficient because their pointers break cache locality, they may cause cache trashing, so they may be slower than smarter and more localized structures, like short double linked arrays, etc. But I think lists aren't outdated, they are a mathematical concept too, and they are quite used still. If you want to learn some Computer Science, it's positive to know what linked lists are. If you want to implement algorithms that must process LOT of things, you may find pointers and lists quite necessary today too, see for example: http://citeseer.ist.psu.edu/knuth00dancing.html http://en.wikipedia.org/wiki/Dancing_Links Python and its data structures aren't the right solutions for all purposes. Bye, bearophile From edquichan at yahoo.com Thu Jan 18 16:49:38 2007 From: edquichan at yahoo.com (EdG) Date: 18 Jan 2007 13:49:38 -0800 Subject: Traversing the properties of a Class In-Reply-To: <45afe338$0$318$426a74cc@news.free.fr> References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> <1169152688.921153.26150@m58g2000cwm.googlegroups.com> <45afe338$0$318$426a74cc@news.free.fr> Message-ID: <1169156978.883998.242180@51g2000cwl.googlegroups.com> That works perfectly thank you. Bruno Desthuilliers wrote: > EdG a ?crit : > (top-post corrected) > > > > Neil Cerutti wrote: > > > >>On 2007-01-18, EdG wrote: > >> > >>>For debugging purposes, I would like to traverse the class > >>>listing out all the properties. > >> > >>This is the first thing that came to mind. > >> > >>def show_properties(cls): > >> for attr in dir(cls): > >> if isinstance(getattr(cls, attr), property): > >> print attr > >> > > > This works great. I have one more question. Now that I have the name > > of the property, how do I get it's value? > > > > I want to print '%s = %s' % (attr,theattributesvalue) > > > Then you need to have the instance... > > def list_properties(cls): > return [ > name for name in dir(cls) > if isinstance(getattr(cls, name), property) > ] > > def print_properties(obj): > for name in list_properties(obj.__class__): > print "%s : %s" % (name, str(getattr(obj, name))) From gagsl-py at yahoo.com.ar Thu Jan 11 19:11:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 21:11:30 -0300 Subject: os.popen() not executing command on windows xp In-Reply-To: <1168535370.211599.265250@p59g2000hsd.googlegroups.com> References: <1168508553.151827.261420@k58g2000hse.googlegroups.com> <1168509560.119819.78470@o58g2000hsb.googlegroups.com> <1168535370.211599.265250@p59g2000hsd.googlegroups.com> Message-ID: <7.0.1.0.0.20070111210043.01ce28c8@yahoo.com.ar> At Thursday 11/1/2007 14:09, nic wrote: >import os >pstr = r'"c:\Program Files\Grisoft\AVG Free\avgscan.exe" "c:\program >files\temp1\test1.txt"' >a = os.popen(pstr) >print a.read() > >I've confirmed the string I'm inputting to os.popen is EXACTLY the same >as the one I can successfully execute manually in command prompt, so >when I go: >print pstr, it yields: >"c:\Program Files\Grisoft\AVG Free\avgscan.exe" "c:\program >files\temp1\test1.txt" > >The problem remains popen won't execute this line as it does when >inputted manually to command prompt. I have AVG so I tried this example. That's not the problem. popen works ok, avgscan is executed. But the avgscan program does *not* use stdout nor stderr to write to the console, so popen can't capture its output. You can confirm this at the command prompt: "c:\Program Files\Grisoft\AVG Free\avgscan.exe" "c:\program files\temp1\test1.txt" >output.txt 2>&1 You will see the usual progress messages from avgscan *on screen*, and when you type output.txt, it's empty. avgscan appears to write directly to the console. You may use the /REPORT option; avgscan /? for details. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From martin at v.loewis.de Thu Jan 4 11:47:10 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Jan 2007 17:47:10 +0100 Subject: Using External Libraries with python? In-Reply-To: References: Message-ID: <459D2F8E.1080600@v.loewis.de> Ognjen Bezanov schrieb: > I have some external C libraries I would like to use with python. > > I have been searching on the internet and found many such > modules/bindings for libraries (e.g. Py-Lame) but have not yet > come across any information of how to actually go about creating such > bindings, so I was wondering if anybody here could point me in the right > direction? There are several methods. One is to write a Python C module by hand, using the Python C API: http://docs.python.org/ext/ext.html http://docs.python.org/api/api.html Essentially, all you need is a DLL/shared-object with an init function. Other solutions include tools that generate extension modules automatically (such as SWIG or Pyrex), or using libraries on top of the C API (such as Boost.Python). I personally always use the C API directly. Regards, Martin From robert.kern at gmail.com Thu Jan 11 18:16:38 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 Jan 2007 17:16:38 -0600 Subject: globals accros modules In-Reply-To: <38388$45a6b867$d443bb3a$10089@news.speedlinq.nl> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> <45a66cea$0$289$426a34cc@news.free.fr> <3137a$45a6851a$d443bb3a$24085@news.speedlinq.nl> <45a69cca$0$321$426a74cc@news.free.fr> <38388$45a6b867$d443bb3a$10089@news.speedlinq.nl> Message-ID: Stef Mientki wrote: > Bruno Desthuilliers wrote: >> Unless you clearly explain the benefits... Any code relying on the >> existence of a global is: >> 1/ dependent on the existence of this global >> 2/ harder to understand > And you think physicians will believe that ? > And suppose they believe it, are the willing to stop their research to > rethink and rewrite their code ;-) If they give a damn about their research, they will. Sloppy, irreproducible lab technique is not acceptable. Sloppy, impossible-to-verify code shouldn't be, either. I'd say more, but Greg Wilson has said it better, and has provided course materials to teach good programming practices to scientists. http://swc.scipy.org/ Of particular note are his article in the _American Scientist_: http://www.americanscientist.org/template/AssetDetail/assetid/48548 and his slides from his talk at SciPy '06: http://www.third-bit.com/lectures/scipy06.pdf -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From pibizza at gmail.com Sat Jan 13 03:21:54 2007 From: pibizza at gmail.com (PaoloB) Date: 13 Jan 2007 00:21:54 -0800 Subject: Barcode recognition in Python Message-ID: <1168676514.115592.181620@v45g2000cwv.googlegroups.com> Hi everyone, I am searching for a python library for barcode recognition. We have developed a rather complex application for document tracking and document management in python/Zope, called PAFlow (www.paflow.it: sorry, most of the information is in Italian...). As our project is completely free software, we will need a library that is free software too. Is there something like this in python ? Ciao PaoloB From beliavsky at aol.com Sun Jan 21 22:26:17 2007 From: beliavsky at aol.com (Beliavsky) Date: 21 Jan 2007 19:26:17 -0800 Subject: Reading Fortran Data In-Reply-To: <1169433752.130978.133210@a75g2000cwd.googlegroups.com> References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> <1169424273.929396.133880@m58g2000cwm.googlegroups.com> <1169429808.910298.10240@11g2000cwr.googlegroups.com> <1169433752.130978.133210@a75g2000cwd.googlegroups.com> Message-ID: <1169436377.634274.172460@s34g2000cwa.googlegroups.com> Carl Banks wrote: > > A Fortran > > list-directed write can print results in an almost arbitrary format, > > depending on the compiler. Many compilers will separate integers by > > several spaces, not just one, and they could use commas instead of > > spaces if they wanted. > > 1. Hardly any compiler will produce a line of two integers, or reals, > that another compiler couldn't read back. Yes, but for more than three numbers, the statement is wrong. Intel Fortran prints four double precision random n as 0.555891433847495 0.591161642339424 0.888434673900224 0.487293557925127 but g95 prints them on a single line. I advise against using list-directed Fortran writes to create files that other programs will read, and I think most experienced Fortran programmers would agree. From libintr at gmail.com Thu Jan 25 12:28:44 2007 From: libintr at gmail.com (lee) Date: 25 Jan 2007 09:28:44 -0800 Subject: running applications in python Message-ID: <1169746124.376610.139420@13g2000cwe.googlegroups.com> how can i run or open a windows application from the python prompt?for e.g.mediaplayer opening,folder acess etc From jairodsl at gmail.com Sat Jan 13 20:10:56 2007 From: jairodsl at gmail.com (jairodsl) Date: 13 Jan 2007 17:10:56 -0800 Subject: Comparing a matrix (list[][]) ? In-Reply-To: <1168735426.313475.212710@11g2000cwr.googlegroups.com> References: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> <1168735426.313475.212710@11g2000cwr.googlegroups.com> Message-ID: <1168737056.494694.173770@s34g2000cwa.googlegroups.com> Thanks a lot, it was that i need !!! Works very good ! bearophileHUGS at lycos.com wrote: > Roberto Bonvallet: > > What output are you expecting from your example matrix? If you are expecting > > it to be 5 (the smallest positive element), using "min" is the way to do it: > > >>> matrix = [[9, 8, 12, 15], > > ... [0, 11, 15, 18], > > ... [0, 0, 10, 13], > > ... [0, 0, 0, 5]] > > >>> min(min(x for x in row if x > 0) for row in matrix) > > 5 > > This looks a bit like homework... > To find the minimal number > 0 of the matrix this seems better: > > mat = [[9, 8, 12, 15], > [0, 11, 15, 18], > [0, 0, 10, 13], > [0, 0, 0, 5]] > > print min(el for row in mat for el in row if el > 0) > > Note that this raises TypeError is the matrix doesn't have one or more > numbers > 0 > If the OP needs the position he/she can do something like: > > nozeromin = 1e300 # or something similar > pos = None, None > > for nrow, row in enumerate(mat): > for ncol, el in enumerate(row): > if el > 0 and el < nozeromin: > nozeromin = el > pos = nrow, ncol > > print nozeromin, pos > > Bye, > bearophile From redvasily at gmail.com Tue Jan 9 02:10:06 2007 From: redvasily at gmail.com (Vasily Sulatskov) Date: 8 Jan 2007 23:10:06 -0800 Subject: Adding functions to classes after definition In-Reply-To: References: <45A2E61F.2080100@andrew.cmu.edu> Message-ID: <1168326606.264695.97740@s80g2000cwa.googlegroups.com> A nice guide to descriptors http://users.rcn.com/python/download/Descriptor.htm From domma at procoders.net Tue Jan 23 17:45:25 2007 From: domma at procoders.net (Achim Domma) Date: Tue, 23 Jan 2007 23:45:25 +0100 Subject: Overloading assignment operator In-Reply-To: <1169579940.966652.191990@l53g2000cwa.googlegroups.com> References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> <1169579940.966652.191990@l53g2000cwa.googlegroups.com> Message-ID: <45b69009$0$5729$9b4e6d93@newsspool3.arcor-online.net> Paul McGuire wrote: > Simple option: how do you feel about using '<<=' instead of '=' (by > defining __ilshift__)? This gives you: > > A <<= B * C > > (looks sort of like "injecting" the result of B times C into A) Thanks! That is exactly the kind of solution I was looking for! :-) Achim From fhk6431 at gmail.com Mon Jan 15 12:17:12 2007 From: fhk6431 at gmail.com (fhk6431 at gmail.com) Date: 15 Jan 2007 09:17:12 -0800 Subject: Looking for Job Message-ID: <1168881431.411312.98530@51g2000cwl.googlegroups.com> Hi, Any one looking for job.. I need someone good at phyton to do black box and white box testing Contact me at fhk6431 at gmail.com From fd.calabrese at gmail.com Mon Jan 8 12:28:10 2007 From: fd.calabrese at gmail.com (cesco) Date: 8 Jan 2007 09:28:10 -0800 Subject: recursive function References: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> Message-ID: <1168277289.970128.44880@38g2000cwa.googlegroups.com> Neil Cerutti wrote: > On 2007-01-08, cesco wrote: > > Hi, > > > > I have a dictionary of lists of tuples like in the following example: > > dict = {1: [(3, 4), (5, 8)], > > 2: [(5, 4), (21, 3), (19, 2)], > > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]] > > > > In this case I have three lists inside the dict but this number > > is known only at runtime. I have to write a function that > > considers all the possible combinations of tuples belonging to > > the different lists and return a list of tuples of tuples for > > which the sum of the first element of the most inner tuple is > > equal to N. > > > > For example, assuming N = 24, in this case it should return: > > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19, > > 2), (0, 2))] > > What do you mean by "most inner tuple"? > > > A simple list comprehension would be enough if only I knew the > > number of keys/lists beforehand > > len(dict.keys()). What I mean is that the number of keys/lists is not known until runtime and it changes randomly from time to time which means I would have to write every time a different list comprehension (or a different number of nested loops) to accomplish the same thing. In the example the result of the search should be a list containing three tuples each of which contains again three tuple (the most inner tuples). If you consider the first element of each tuple the sum is 24 (like in 3+5+16, or 3+21+0 or 5+19+0). Any other help will be appreciated From gagsl-py at yahoo.com.ar Mon Jan 15 18:33:54 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 20:33:54 -0300 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> Message-ID: <7.0.1.0.0.20070115200412.05c71528@yahoo.com.ar> At Monday 15/1/2007 17:45, Stef Mientki wrote: >Is there some handy/ nice manner to view the properties of some variable ? >As a newbie, I often want to see want all the properties of a var, >and also some corner values (large arrays) etc. You can try dir(x), vars(x). If you want a "nice print", see the pprint module. py> import csv py> x = csv.DictReader('') # a bogus object py> x py> dir(x) ['__doc__', '__init__', '__iter__', '__module__', 'fieldnames', 'next', 'reader' , 'restkey', 'restval'] py> vars(x) {'restkey': None, 'restval': None, 'fieldnames': None, 'reader': <_csv.reader ob ject at 0x00BC98B8>} py> from pprint import pprint py> pprint(vars(x)) {'fieldnames': None, 'reader': <_csv.reader object at 0x00BC98B8>, 'restkey': None, 'restval': None} py> >Probably it's not so difficult, >but I don't see how to distinguish for example between a string and an >array. An array has a shape, a string not etc. Yes, strings share a lot of functionality with other sequence types: [], len, in, etc. You can test if an object is a string using isinstance(obj, str). If you want to include unicode objects too, use isinstance(obj, basestring). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From stargaming at gmail.com Sun Jan 28 06:43:22 2007 From: stargaming at gmail.com (Stargaming) Date: Sun, 28 Jan 2007 12:43:22 +0100 Subject: from future module!!!!!!! In-Reply-To: <1169983511.674847.281290@s48g2000cws.googlegroups.com> References: <1169983511.674847.281290@s48g2000cws.googlegroups.com> Message-ID: lee schrieb: > Guys whats the from future module in python?thanks > http://docs.python.org/lib/module-future.html It's a module with that "future changes" may be activated (currently such as the with_statement, what isn't in the "2.5 standard" so far). BTW, it's not the 'from future' module, it's just the 'future' (or '__future__') module. The 'from' clause is a keyword in python used for imports in the module namespace. Stargaming From S.Mientki-nospam at mailbox.kun.nl Tue Jan 16 18:13:37 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 17 Jan 2007 00:13:37 +0100 Subject: Anyone has a nice "view_var" procedure ? In-Reply-To: <1168904865.253014.210140@m58g2000cwm.googlegroups.com> References: <3de03$45abe7d2$d443bb3a$6698@news.speedlinq.nl> <1168904865.253014.210140@m58g2000cwm.googlegroups.com> Message-ID: <8ab5f$45ad5c12$d443bb3a$7243@news.speedlinq.nl> Adam wrote: > Stef Mientki wrote: > >> hello, >> >> Is there some handy/ nice manner to view the properties of some variable ? >> As a newbie, I often want to see want all the properties of a var, >> and also some corner values (large arrays) etc. >> >> Probably it's not so difficult, >> but I don't see how to distinguish for example between a string and an >> array. An array has a shape, a string not etc. >> >> >> thanks, >> Stef Mientki > > I am also a newbie so if this is not what you want I can't give much > more as of yet. > Ok, here's my current solution, probably not very Pythonian, (so suggestions are welcome) but it works. (Too bad I can get the name of the var into a function ;-) cheers, Stef Mientki from scipy import * # ############################################################################# def prn ( V ): # print a single row of an array def prn_array_row ( R, row ): if len(R) < 4: print ' Row', row, ':', R else: print ' Row', row, ': [', R[0],R[1], '...', R[-2], R[-1], ']' # print a single element of a list def prn_list_element ( E ): if type(E) == int: return ' ' + str(E) elif type(E) == float: return ' ' + str(E) elif type(E) == complex: return ' ' + str(E) elif type(E) == list: return ' [..]' elif type(E) == tuple: return ' (..)' elif type(E) == array: return ' ([..])' else: return ' ??' print '' if type(V) == int: print 'int32 =', V elif type(V) == float: print 'float64 =', V elif type(V) == complex: print 'complex64 =', V # LIST elif (type(V) == list) | (type(V) == tuple): # count the occurances of the different types N_int,N_float,N_complex,N_list,N_tuple,N_array,N_unknown = 0,0,0,0,0,0,0 for i in range(len(V)): if type(V[i]) == int: N_int += 1 elif type(V[i]) == float: N_float += 1 elif type(V[i]) == complex: N_complex += 1 elif type(V[i]) == list: N_list += 1 elif type(V[i]) == tuple: N_tuple += 1 elif type(V[i]) == ndarray: N_array += 1 else: N_unknown += 1 # print the occurances of the different types # and count the number of types that can easily be displayed if type(V)==list: line = 'list:' else: line = 'tuple:' N = 0 if N_int > 0: line = line + ' N_Int=' + str(N_int) ; N += 1 if N_float > 0: line = line + ' N_Float=' + str(N_float) ; N += 1 if N_complex > 0: line = line + ' N_Complex=' + str(N_complex) ; N += 1 if N_list > 0: line = line + ' N_List=' + str(N_list) ; N += 1 if N_tuple > 0: line = line + ' N_Tuple=' + str(N_tuple) ; N += 1 if N_array > 0: line = line + ' N_Array=' + str(N_array) ; N += 1 if N_unknown > 0: line = line + ' N_Unknown=' + str(N_unknown) ; N += 1 if N == 1: line += ' == Homogeneous ==' print line # check if all elements have the same type if len(V) < 4: line = '' for i in range(len(V)): line += prn_list_element (V[i]) print line else: print prn_list_element (V[0]),\ prn_list_element (V[1]),\ ' .....',\ prn_list_element (V[-2]),\ prn_list_element (V[-1]) # ARRAY elif type(V) == ndarray: print 'Array', V.shape, V.dtype.name if V.ndim == 1: prn_array_row ( V, 0 ) elif V.ndim == 2: if V.shape[1] < 4: for i in range(V.ndim): prn_array_row ( V[i,:], i ) else: prn_array_row ( V[0,:], 0 ) prn_array_row ( V[1,:], 1 ) print ' ......' prn_array_row ( V[-2,:], V.shape[1]-2 ) prn_array_row ( V[-1,:], V.shape[1]-1 ) # MAIN TEST PROGRAM ########################################################## V1 = 3 L1 = [ 11, 12, 33 ] L2 = [ 11, 12, ['aap', 34] ] T1 = ( 11, 12, ('aap', 34) ) T2 = ( 11, ('aap', 34), 5,5,5,5,5,5,8 ) A1 = array ( [1,2,7] ) A2 = array ( [ [1,2,4,4,4,4,4,8], [4,5,5,5,5,5,5,2] ] ) A3 = zeros ((10,10)) prn ( V1 ) prn ( L1 ) prn ( A1 ) prn ( A2 ) prn ( A3 ) prn ( L2 ) prn ( T1 ) prn ( T2 ) From tinaweb at bestemselv.com Fri Jan 26 02:27:48 2007 From: tinaweb at bestemselv.com (Tina I) Date: Fri, 26 Jan 2007 08:27:48 +0100 Subject: Prefered install method? Message-ID: Another noob question: I have written my first linux application that might actually be of interest to others. Just for fun I also wrote an install script that put the files in the common directories for my distro (Debian). That is in /usr/local/. (This particular program can be run directly from the user's /home but as a learning experience I want to do it the 'coorect' way) Now, I don't know if that is the way to do it with python applications. I also don't know if a custom install script is the norm. I have seen some use of makefiles and tried to find something about it but the manual for GNUMake really assume you are familiar with/ using C which I'm not. I have googled a lot for this but can't really find anything aimed for someone just learning programming with Python. So my question is; What is the preferred/ common way to install a python application so it's not really distro specific? And are there any good resources on this on the web? Thanks Tina From charlietaylor at users.sourceforge.net Tue Jan 23 02:23:20 2007 From: charlietaylor at users.sourceforge.net (charlietaylor) Date: Tue, 23 Jan 2007 00:23:20 -0700 Subject: ANN: tk_happy, a framework for creating python Tk apps Message-ID: <20070123002320.1ace5abeb80c198ab3acc3a9bf8d431e.c832e75cd1.wbe@email.secureserver.net> An HTML attachment was scrubbed... URL: From maksim.kasimov at gmail.com Mon Jan 15 12:14:14 2007 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Mon, 15 Jan 2007 19:14:14 +0200 Subject: __getattr__ equivalent for a module In-Reply-To: <45abab5e$0$15166$4d3efbfe@news.sover.net> References: <45abab5e$0$15166$4d3efbfe@news.sover.net> Message-ID: Hi Leif, many thanks - it works Leif K-Brooks wrote: > Maksim Kasimov wrote: >> so my question is: how to tune up a module get default attribute if we >> try to get access to not actually exists attribute of a module? > > You could wrap it in an object, but that's a bit of a hack. > > import sys > > class Foo(object): > def __init__(self, wrapped): > self.wrapped = wrapped > > def __getattr__(self, name): > try: > return getattr(self.wrapped, name) > except AttributeError: > return 'default' > > sys.modules[__name__] = Foo(sys.modules[__name__]) -- Maksim Kasimov From alain.walter at thalesgroup.com Fri Jan 19 12:49:09 2007 From: alain.walter at thalesgroup.com (awalter1) Date: 19 Jan 2007 09:49:09 -0800 Subject: monitor the start and end of applications Message-ID: <1169228949.808574.37250@l53g2000cwa.googlegroups.com> Hello, My purpose is to supervise (from a python program) the launch of some other programs (python or non python programs) as : "I click on the button X and the pg X is launched ..." I want also that my supervision be "wake up" when a pg has exited to check its status or something like that. I suppose I need to use thread and I did, I'm trying several solutions (popen, os.system, commands.getstatusoutput, certainly not correctly) : generally I am able to launch a pg but when it is ended, the thread "caller" is still waiting. Is somebody has encountered similar requirements ? Thanks a lot for your help From harvey.thomas at informa.com Fri Jan 19 05:54:17 2007 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 19 Jan 2007 02:54:17 -0800 Subject: Match 2 words in a line of file References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> <1169172954.107365.133950@51g2000cwl.googlegroups.com> <1169175299.490994.244700@51g2000cwl.googlegroups.com> Message-ID: <1169204056.999939.280660@s34g2000cwa.googlegroups.com> Rickard Lindberg wrote: > I see two potential problems with the non regex solutions. > > 1) Consider a line: "foo (bar)". When you split it you will only get > two strings, as split by default only splits the string on white space > characters. Thus "'bar' in words" will return false, even though bar is > a word in that line. > > 2) If you have a line something like this: "foobar hello" then "'foo' > in line" will return true, even though foo is not a word (it is part of > a word). Here's a solution using re.split: import re import StringIO wordsplit = re.compile('\W+').split def matchlines(fh, w1, w2): w1 = w1.lower() w2 = w2.lower() for line in fh: words = [x.lower() for x in wordsplit(line)] if w1 in words and w2 in words: print line.rstrip() test = """1st line of text (not matched) 2nd line of words (not matched) 3rd line (Word test) should match (case insensitivity) 4th line simple test of word's (matches) 5th line simple test of words not found (plural words) 6th line tests produce strange words (no match - plural) 7th line "word test" should find this """ matchlines(StringIO.StringIO(test), 'test', 'word') From dummy at dummy.nl Fri Jan 19 12:28:02 2007 From: dummy at dummy.nl (Cecil Westerhof) Date: Fri, 19 Jan 2007 18:28:02 +0100 Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> <45af8f52$0$339$e4fe514c@news.xs4all.nl> Message-ID: <45b0ffa2$0$338$e4fe514c@news.xs4all.nl> Gabriel Genellina wrote: > I'll try to explain better: the cgi *protocol* (I'm not talking about the > cgi *module*) requires a *new* python process to be created on *each* > request. Try to measure the time it takes to launch Python, that is, the > time from when you type `python ENTER` on your shell and the interpreter > prompt appears. That time is wasted for *every* cgi request, and I bet it > is much greater than the 95 ms you measure importing a module (be it cgi > or whatever). You'll gain much more responsiveness if you can switch to > another protocol, be it FastCGI, WSGI, mod_python or another. The import of the cgi module takes about 95 milliseconds and the browsers takes around 260 milliseconds to fetch the xml-page. This is why I thought it to be important, but I think you are right, I should not worry about this and switch to another protocol. Is not possible with the current hosting provider, but I'll switch. Pointers where to look for in selecting the protocol are apreciated. > Anyway, comparing the import time between os, sys, and cgi is not very > meaningful. sys is a builtin module, so "import sys" does very little. os > is likely to be already imported by the time your script begins, so > "import os" just verifies that os is already in sys.modules. "import cgi" > is the only example when Python actually has to load something, so it's > not a surprise if it takes longer. Okay, thank you for the explanation. From ggrp1.20.martineau at dfgh.net Sat Jan 6 19:49:20 2007 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 6 Jan 2007 16:49:20 -0800 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> <1168048620.409190.85870@v33g2000cwv.googlegroups.com> Message-ID: <1168130960.670978.111850@s34g2000cwa.googlegroups.com> Carl Banks wrote: > Martin Miller wrote: > > ### non-redundant example ### > > import sys > > > > class Pin: > > def __init__(self, name, namespace=None): > > self.name = name > > if namespace == None: > > # default to caller's globals > > namespace = sys._getframe(1).f_globals > > namespace[name] = self > > > > Pin('aap') # create a Pin object named 'aap' > > Pin('aap2') # create a Pin object named 'aap2' > > print aap.name > > print aap2.name > > The problem with this is that it only works for global namespaces, > while failing silently and subtly if used in a local namespace: Oh, contrair. It would work fine with local namespaces simply by overriding the default value of the optional 'namepace' parameter (see below). > def fun(): > Pin('aap') > aap1 = aap > fun2() > aap2 = aap > print aap1 is aap2 > > def fun2(): > Pin('aap') > > If it's your deliberate intention to do it with the global namespace, > you might as well just use globals() and do it explicitly, rather than > mucking around with Python frame internals. (And it doesn't make the > class unusable for more straightforward uses.) You could be more explicit by just passing 'globals()' as a second parameter to the __init__ constructor (which is unnecessary, since that's effectively the default). It's not clear to me how the example provided shows the technique "failing silently and subtly if used in a local namespace" because what happens is exactly what I would expect if the constructor is called twice with the same string and defaulted namespace -- namely create another object and make the existing name refer to it. If one didn't want the call to Pin in fun2 to do this, just change fun2 to this: def fun2(): Pin('aap', locals()) This way the "print aap1 is aap2" statement in fun() would output "true" since the nested call to Pin would now (explicitly) cause the name of the new object to be put into fun2's local namespace leaving the global one created by the call in fun() alone. Obviously, this was not an objection I anticipated. An important one I would think is the fact that the current documentation says that f_globals is a special *read-only* attribute of a frame object implying that it shouldn't be changed (even though doing so 'works' as my example illustrates). I think other valid arguments against this practice might include whether it's an example of good OOP, or a good programming practice at all, since it involves possibly subtle side-effects, the use of global variables, and/or is 'unpythonic'. Certainly the approach is not without caveats. Despite them, I believe it can be useful in some contexts, as long as what is going on is clearly understood. The point of my reply to the OP was mainly just to illustrate the power and flexibility of Python to the newbie. I guess to that I should have also added that it gives you "enough rope to shoot yourself" as Allen Holub said regarding C++. Cheers, -Martin From pink at odahoda.de Tue Jan 16 04:20:06 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Tue, 16 Jan 2007 10:20:06 +0100 Subject: html + javascript automations = [mechanize + ?? ] or something else? References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> <1168922805.176693.149060@q2g2000cwa.googlegroups.com> Message-ID: Hello, John wrote: > John wrote: >> I have to write a spyder for a webpage that uses html + javascript. I >> had it written using mechanize >> but the authors of the webpage now use a lot of javascript. Mechanize >> can no longer do the job. >> Does anyone know how I could automate my spyder to understand >> javascript? Is there a way >> to control a browser like firefox from python itself? How about IE? >> That way, we do not have >> to go thru something like mechanize? > > I am curious about the webbrowser module. I can open up firefox > using webbrowser.open(), but can one control it? Say enter a > login / passwd on a webpage? Send keystrokes to firefox? > mouse clicks? Not with the webbrowser module - it can only launch a browser. On the website of mechanize you will also find DOMForm , which is a webscraper with basic JS support (using the SpiderMonkey engine from the Mozilla project). But note that DOMForm is in a early state and not developed anymore (according to the site, never used it myself). You could try to script IE (perhaps also FF, dunno..) using COM. This can be done using the pywin32 module . How this is done in detail is a windows issue. You may find help and documentation in win specific group/mailing list, msdn, ... You can usually translate the COM calls from VB, C#, ... quite directly to Python. HTH -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From jg307 at cam.ac.uk Tue Jan 9 05:13:16 2007 From: jg307 at cam.ac.uk (James Graham) Date: Tue, 09 Jan 2007 10:13:16 +0000 Subject: [ANN] html5lib 0.2 Message-ID: DESCRIPTION HTML parsing library based on the WHATWG Web Applications 1.0 "HTML5" specification[1]. The parser is designed to work with all existing flavors of HTML and implements well-defined error recovery that has been specified though analysis of the behavior of modern desktop web browsers. html5lib currently allows parsing to both a custom "simpletree" format and to an ElementTree, if available. Future releases will include support for at least one DOM implementation, and it is possible to implement custom treebuilders although the API should not yet be considered stable. DOWNLOAD http://html5lib.googlecode.com/files/html5lib-0.2.zip BUGS This is the first release of html5lib and it is considered alpha quality software. However, it ships with over 230 passing unit tests covering most of the specified behavior. Bugs should be reported on the issue tracker [2] KNOWN ISSUES Error handling does not yet conform to the specification; not all errors are reported and the error messages are not informative. PROJECT PAGE More information about the project including documentation and information on getting involved is available on the project page: http://code.google.com/p/html5lib/ [1] http://whatwg.org/specs/web-apps/current-work/ [2] http://code.google.com/p/html5lib/issues/list From nszabolcs at gmail.com Mon Jan 29 10:01:39 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 29 Jan 2007 07:01:39 -0800 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <7x3b5uwfa2.fsf@ruckus.brouhaha.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <7x3b5uwfa2.fsf@ruckus.brouhaha.com> Message-ID: <1170082899.639441.246010@a34g2000cwb.googlegroups.com> > If you don't mind possibly getting a few nonalphanumeric characters: > > import os,binascii > print binascii.b2a_base64(os.urandom(6)) what about file('/dev/urandom').read(6).encode('base64') (oneliner and without import as op requested) From adonis at REMOVETHISearthlink.net Sun Jan 28 22:47:26 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Mon, 29 Jan 2007 03:47:26 GMT Subject: Convert from unicode chars to HTML entities In-Reply-To: References: Message-ID: Adonis Vargas wrote: [...] > > Its *very* ugly, but im pretty sure you can make it look prettier. > > import htmlentitydefs as entity > > s = u"? and many more..." > t = "" > for i in s: > if ord(i) in entity.codepoint2name: > name = entity.codepoint2name.get(ord(i)) > entityCode = entity.name2codepoint.get(name) > t +="&#" + str(entityCode) > else: > t += i > print t > > Hope this helps. > > Adonis or import htmlentitydefs as entity s = u"? and many more..." t = u"" for i in s: if ord(i) in entity.codepoint2name: name = entity.codepoint2name.get(ord(i)) t += "&" + name + ";" else: t += i print t Which I think is what you were looking for. Adonis From rweth at cisco.com Sun Jan 7 04:00:06 2007 From: rweth at cisco.com (rweth) Date: Sun, 07 Jan 2007 01:00:06 -0800 Subject: How to invoke parent's method? In-Reply-To: <1168159875.980990@sj-nntpcache-1.cisco.com> References: <1168138626.574514.102060@i15g2000cwa.googlegroups.com> <1168159875.980990@sj-nntpcache-1.cisco.com> Message-ID: <1168160407.52195@sj-nntpcache-1.cisco.com> rweth wrote: > many_years_after wrote: >> Hi, pythoners: >> >> My wxPython program includes a panel whose parent is a frame. The >> panel has a button. When I click the button , I want to let the frame >> destroy. How to implement it? Could the panel invoke the frame's >> method? >> Thanks. >> > I think it "could" if what I read recently in: > http://www.python.org/download/releases/2.2/descrintro/#cooperation > Is applicable. > > Look at the link "Cooperative methods and super" > Write a subclass of panel where the target method of it's parent > is targX (that parent method of Frame that you want to call) > > class myPanel (Panel): > def dadsX (self): > Frame.targX(self) > > > I think you are forced to invoke this within a method of the Class > itself, as opposed to doing so with an instance. > > Good luck! > > You know I just tried a code fragment and got the parent method to work with an instance .. so maybe you don't have to subclass. Here is a transcript illustrating the idea: >>> class DAD: ... def methodx(self): ... print "DAD-methodx" ... >>> class SON(DAD): ... def methodx(self): ... print "SON-methodx" ... >>> >>> >>> billy = SON() >>> billy.methodx() SON-methodx >>> DAD.methodx(billy) DAD-methodx >>> So you can invoke the DAD.methodx via the billy instance of the object .. without subclassing. Now I wonder if this will actually work? From ggrp1.20.martineau at dfgh.net Sun Jan 7 16:01:18 2007 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 7 Jan 2007 13:01:18 -0800 Subject: [OT] (newbie) Is there a way to prevent "name redundancy" in OOP ? References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> <1168042215.514023.121560@s80g2000cwa.googlegroups.com> <1168048620.409190.85870@v33g2000cwv.googlegroups.com> <1168130960.670978.111850@s34g2000cwa.googlegroups.com> <45a12b07$0$300$426a74cc@news.free.fr> Message-ID: <1168203678.193392.158600@i15g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > Martin Miller a ?crit : > (snip) > > > > Oh, contrair. > > I guess you mean "au contraire" ?-) > > (snip) FWIW "contrair" is how it's spelled in the Oxford English dictionary (I actually did look it up before posting because it seemed like there ought be an 'e' on the end). The dictionary also says it's chiefly Scottish but the etymology indicates from the Old French "contraire". Technically I suppose I should have written "Oh, *on* contrair" or better yet just "On the contrary". ;-) -Martin From george.sakkis at gmail.com Mon Jan 15 21:36:25 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 15 Jan 2007 18:36:25 -0800 Subject: Class list of a module References: <1168850336.276790.73810@38g2000cwa.googlegroups.com> Message-ID: <1168914985.821811.183300@v45g2000cwv.googlegroups.com> bearophileHUGS at lycos.com wrote: > Gabriel Genellina: > > >import inspect > > def getClassList(aModule): > > return [cls for cls in vars(aModule).itervalues() > > if inspect.isclass(cls)] > > This is short enough too: > > from inspect import isclass > getclasses = lambda module: filter(isclass, vars(module).itervalues()) > > Bye, > bearophile Or even: from inspect import getmembers, isclass def getclasses(module): return [cls for name,cls in getmembers(module,isclass)] George From jstroud at mbi.ucla.edu Wed Jan 31 06:08:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 31 Jan 2007 11:08:02 GMT Subject: data design In-Reply-To: References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> <45bfbcc3$0$30950$426a74cc@news.free.fr> <1170201274.580256.182740@v45g2000cwv.googlegroups.com> Message-ID: BJ?rn Lindqvist wrote: > On 1/31/07, James Stroud wrote: >> [copy_files] >> files_dir1 = this.file that.file >> path_dir1 = /some/path >> >> files_dir2 = the_other.file yet_another.file >> path_dir2 = /some/other/path >> >> In yaml, it might look thus. >> >> copy_files : >> - files : [this.file, that.file] >> path : /some/path >> - files : [the_other.file, yet_another.file] >> path : /some/other/path >> >> Both are readable (though I like equals signs in appearance over >> colons), but yaml doesn't require a lot of string processing to group >> the files with the paths. I don't even want to think the coding >> gymnastics required to split all of the option names and then group >> those with common suffixes. > > But is not that a perfect world example? Consider: > > [copy_files] > files_dir1=this.file that.file > path_dir1=/some/path > files_dir2=the_other.file yet_another.file > path_dir2=/some/other/path > > versus: > > copy_files: > -files:[this.file,that.file] > path:/some/path > -files:[the_other.file,yet_another.file] > path:/some/other/path > > Mandatory indentation is good in programming languages, but does it > really belong in configuration files? With tabs verboten to boot. > I'm not sure whether to agree with you or disagree with you. My conclusion is that if it is at all possible, try to use an ini file, even if you have to stretch your imagination a bit. More complex formats are prone to one's assigning some imperative meaning to the structure (as I am doing with my example, which might make it a bad one). However, these more complex formats can intensely useful for (1) knowledgeable people with (2) complicated data. From gandalf at designaproduct.biz Tue Jan 9 05:19:15 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 09 Jan 2007 11:19:15 +0100 Subject: A simple array in Python In-Reply-To: <1168337391.770307.54750@11g2000cwr.googlegroups.com> References: <1168337391.770307.54750@11g2000cwr.googlegroups.com> Message-ID: <45A36C23.2030007@designaproduct.biz> bg_ie at yahoo.com wrote: > Hi, > > I have the following enum - > > class State: > Fire = 0 > Water = 1 > Earth = 2 > > And I want a variable which holds a value for each of these states, > something like - > class State: Fire = 0 Water = 1 Earth = 2 myState = {} # It is a dictionary, see http://docs.python.org/tut/node7.html#SECTION007500000000000000000 myState[State.Fire] = 20 myState[State.Earth] = 24 print myState {0: 20, 2: 24} From pavlovevidence at gmail.com Fri Jan 5 00:28:27 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 4 Jan 2007 21:28:27 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> Message-ID: <1167974907.497878.61070@i15g2000cwa.googlegroups.com> jeremito wrote: > I am writing a class that is intended to be subclassed. What is the > proper way to indicate that a sub class must override a method? You can't (easily). If your subclass doesn't override a method, then you'll get a big fat AttributeError when someone tries to call it. But this doesn't stop someone from defining a subclass that fails to override the method. Only when it's called will the error show up. You can, as others have noted, define a method that raises NotImplementedError. But this still doesn't stop someone from defining a subclass that fails to override the method. The error still only occurs when the method is called. There are some advantages to using NotImplementedError: 1. It documents the fact that a method needs to be overridden 2. It lets tools such as pylint know that this is an abstract method 3. It results in a more informative error message But, in the end, if someone wants to define a class that defiantly refuses to declare a method, you can't stop them. Carl Banks From ironfroggy at gmail.com Mon Jan 15 22:21:31 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Mon, 15 Jan 2007 22:21:31 -0500 Subject: assert versus print [was Re: The curious behavior of integer objects] In-Reply-To: References: Message-ID: <76fd5acf0701151921m7932cb82u638bbbb002d7b670@mail.gmail.com> On 1/15/07, Steven D'Aprano wrote: > On Mon, 15 Jan 2007 21:38:42 -0500, Calvin Spealman wrote: > > > On 1/15/07, Steven D'Aprano wrote: > >> On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote: > >> > >> > assert foo(0x10) == 0 # Assertions are much better tests than prints :-) > >> > >> I dispute that assertion (pun intended). > > > > Hah! > > > >> Firstly, print statements work even if you pass the -O (optimize) flag > >> to Python. Your asserts don't. > > > > This is true, but the concept can be adapted to a things like an > > assert_() function. > > Hence defeating the optimization :) > > So what you're saying is, some custom function that you write yourself is > better than print? I suppose I can't argue with that :) > > > >> Secondly, a bare assertion like that gives you very little information: > >> it just tells you that it failed: > >> > >> >>> x = 1 > >> >>> assert x == 0 > >> Traceback (most recent call last): > >> File "", line 1, in ? > >> AssertionError > >> > >> To provide the same information that print provides, you need something > >> like this: > >> > >> assert x == 0, "x == %s not 0" % x > > > > What information would I need to know if my test passed? Nothing, I say. > > Maybe. But then it is hard to tell the difference between "my test > function printed nothing because it is broken, and my test function > printed nothing because it succeeded". > > There are good arguments both for and against successful tests printing a > result. Keep in mind that a successful assert doesn't actually print > "nothing" in the interactive interpreter: when it completes, you do get > feedback because Python prints a prompt. Getting feedback that the test > completed successfully is vital. The only question is whether that > feedback should be minimal or verbose. > > But in any case, you have misunderstood the assertion. The error message > is printed *if the assert fails*, not if it passes. > > > > I only want to know when the tests fail, especially as I add more of > > them. Having no output is a great way to know nothing puked. > > Sure -- for unit testing. For interactive exploration, seeing the value of > a variable is better than guessing. That's why a bare object reference in > the interactive interpreter prints itself, but in a script does nothing. 1) I was trying to nudge the OP towards unit testing 2) if you look at the printed verson of an object you are as much guessing as you would with an assert and no output 3) It was just an arbitrary statement and although I stand by it, is it worth this much discussion? > -- > Steven D'Aprano > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From gagsl-py at yahoo.com.ar Wed Jan 24 00:06:59 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 02:06:59 -0300 Subject: newbie question: ftp.storbinary() References: Message-ID: "Scott Ballard" escribi? en el mensaje news:BAY119-F308650E60A44C911FD66C7C4AD0 at phx.gbl... > Sorry for the lame question, I'm still trying to pick up Python and new to > the list here. It's not a lame question... > Question: > I'm trying to write a python script that will access an FTP site and > upload > some files. I've gotten everything working except for the actual uploading > of the files. > > I'm assuming that I should use storbinary( command, file[, blocksize]) to > transfer the files. the documentation says "command should be an > appropriate > "STOR" command: "STOR filename"." > > I can't seem to figure out an `appropriate "STOR" command' is??? The ftplib is perhaps too low level in this regard. There are a few variants: STOR, STOU, APPE. Try Google, or go right into the official specification, RFC959. http://www.faqs.org/rfcs/rfc959.html (specially section 4.1, FTP Commands). The example command above "STOR filename" will upload the file (the second argument to storbinary) overwriting without prompt any previous file with the same name (if it existed). -- Gabriel Genellina From antonyliu2002 at yahoo.com Fri Jan 5 01:09:38 2007 From: antonyliu2002 at yahoo.com (antonyliu2002 at yahoo.com) Date: 4 Jan 2007 22:09:38 -0800 Subject: Undefined symbol __pure_virtual when importing MySQLdb Message-ID: <1167977378.425615.220350@51g2000cwl.googlegroups.com> I downloaded MySQL-python-1.2.1 from SourceForge and installed it on a Mandrake system (Mandrake Linux 9.2 3.3.1-2mdk on linux2). The installation was successful. The gcc version is 3.3. My Python version is 2.4.2. When I import MySQLdb, I get an error which says that __pure_virtual is an undefined symbol. Look: >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ? File "/usr/local/python2.4/site-packages/MySQLdb/__init__.py", line 19, in ? import _mysql ImportError: /usr/local/python2.4/site-packages/_mysql.so: undefined symbol: __pure_virtual By the way, mysql (5.0.27-standard)is running OK on the Mandrake system. Look: [antonyliu at myhost antonyliu]$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 13 to server version: 5.0.27-standard Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> I have googled hard, and did see someone asking the same question, but haven't found a good solution to this problem. Could anyone give me a hint? Thanks a lot! From horpner at yahoo.com Thu Jan 4 11:23:35 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 4 Jan 2007 17:23:35 +0100 Subject: Sorting on multiple values, some ascending, some descending References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> Message-ID: On 2007-01-03, dwelden wrote: > I have successfully used the sort lambda construct described in > http://mail.python.org/pipermail/python-list/2006-April/377443.html. > However, how do I take it one step further such that some > values can be sorted ascending and others descending? Easy > enough if the sort values are numeric (just negate the value), > but what about text? > > Is the only option to define an external sorting function to > loop through the list and perform the comparisons one value at > a time? Another trick is to factor the key application out of the sort. This may be a good idea if when you want to minimize the number of times your key function is called. The idea is to mangle the list temporarily so you can use an unkeyed sort, and then unmangle the sorted data. Here's a silly example using a phone directory that's not stored in a format that's easy to sort. >>> a = [("Neil Cerutti", "8025552954"), ("Ted Smith", "8025552281"), ("Barny Fife", "8025551105")] >>> b = [(" ".join(reversed(x.split())), y) for (x, y) in a] >>> b [('Cerutti Neil', '8025552954'), ('Smith Ted', '8025552281'), ('Fife Barny', '8025551105')] >>> b.sort() >>> b [('Cerutti Neil', '8025552954'), ('Fife Barny', '8025551105'), ('Smith Ted', '8025552281')] >>> a = [(" ".join(reversed(x.split())), y) for (x, y) in b] >>> a [('Neil Cerutti', '8025552954'), ('Barny Fife', '8025551105'), ('Ted Smith', '8025552281')] -- Neil Cerutti Eddie Robinson is about one word: winning and losing. --Eddie Robinson's agent Paul Collier From carsten at uniqsys.com Wed Jan 3 09:47:44 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 03 Jan 2007 09:47:44 -0500 Subject: function without brackets ? In-Reply-To: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> References: <57668$459bbf95$d443bb3a$16218@news.speedlinq.nl> Message-ID: <1167835664.3391.6.camel@dot.uniqsys.com> On Wed, 2007-01-03 at 15:37 +0100, Stef Mientki wrote: > If I call a parameterless function without brackets at the end, > the function is not performed, but ... > I don't get an error message ??? > > Is this normal behavior ? Yes. If you "call" a function without brackets, it's not a call. Remember that functions are first class objects that can be passed around like any other object. Hence, Python needs the distinction between x = foo() # Assign the *result* of calling foo to x and x = foo # Assign the *function* foo itself to x. You don't get an error message because a function name without parentheses is a valid expression that refers to that function. Hope this helps, Carsten. From Thomas.Ploch at gmx.net Sun Jan 7 09:52:00 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 15:52:00 +0100 Subject: Why less emphasis on private data? In-Reply-To: References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> Message-ID: <45A10910.7010107@gmx.net> Jorgen Grahn schrieb: > On 06 Jan 2007 17:38:06 -0800, Paul Rubin wrote: >> "BJ?rn Lindqvist" writes: >>> It is given that emphasizing private data (encapsulation) leads to >>> more internal complexity and more lines of code because you have to >>> write getters and setters and stuff. >> You can have public variables in Java if you choose to. Writing >> private variables with public setters and getters is just a style choice. > > Privates with getters/setters are (as I think someone else hinted) pretty > pointless. The interesting stuff is the private data that *is* private, i.e. > not meant for users at all. Not really pointless, since you can hide your data structures that you don't want to be fiddled around with (which for me is almost the only point to use it). > But yes, I don't mind not having 'private:' in Python. I don't have > compile-time type checking anyway. In fact, I don't always know what the > attributes of my objects /are/ until runtime. Me neither, although I have to say that the '__' prefix comes pretty close to being 'private' already. It depends on the definition of private. For me, private means 'not accessible from outside the module/class'. Thomas From ng6 at padowan.dk Thu Jan 11 17:49:45 2007 From: ng6 at padowan.dk (Ivan Johansen) Date: Thu, 11 Jan 2007 23:49:45 +0100 Subject: Embedding Python with Tkinter Message-ID: <45a6bf07$0$2084$edfadb0f@dtext02.news.tele.dk> I have written a Windows GUI application in C++ and I would like to embed Python into the application to enable users to write plugins. The problem is when the plugin tries to use Tkinter. Tkinter creates its own root window, which I remove by calling: root = Tk() root.withdraw() But when I create a new dialog with Tkinter, I have to create it without a parent, which causes it to be shown in the task bar and I cannot make it modal. Does anyone know how to create a Tkinter window as a child of a window that was not created by Tkinter? Ivan Johansen From mail at microcorp.co.za Mon Jan 8 06:11:14 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 8 Jan 2007 13:11:14 +0200 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com><7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: <01f701c73316$3c945680$03000080@hendrik> "Paul Rubin" wrote: > If you want to write bug-free code, pessimism is the name of the game. A healthy touch of paranoia does not come amiss either... And even then things foul up in strange ways because your head is never quite literal enough. When you hear a programmer use the word "probability" - then its time to fire him, as in programming even the lowest probability is a certainty when you are doing millions of things a second. But this is off topic, really - I don't think that hiding things make much difference, especially as the python hiding is not absolute. - Hendrik From tactics40 at gmail.com Wed Jan 10 16:37:33 2007 From: tactics40 at gmail.com (tac-tics) Date: 10 Jan 2007 13:37:33 -0800 Subject: Question about compiling. In-Reply-To: <87ac0qy5a6.fsf@smsnet.pl> References: <87ac0qy5a6.fsf@smsnet.pl> Message-ID: <1168465053.243581.166220@k58g2000hse.googlegroups.com> > That's not the whole truth. :) The whole truth is that from a developer's POV, .pyc files are unimportant. From heikki at osafoundation.org Fri Jan 19 14:24:30 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 19 Jan 2007 11:24:30 -0800 Subject: More M2Crypto issues In-Reply-To: <6u7sh.264$4H1.150@newssvr17.news.prodigy.net> References: <6u7sh.264$4H1.150@newssvr17.news.prodigy.net> Message-ID: John Nagle wrote: > Actually, at the moment I'm having an M2Crypto problem related > to a SWIG/OpenSSL conflict. Older versions of OpenSSL have an > include file that needs __i386__ defined, which is something GCC > does based on what platform you're on. SWIG uses CPP, but > doesn't set the platform defines, so the SWIG phase of the > M2Crypto build fails. I'm currently trying to get the shared > host where that build took place upgraded to a later version of > OpenSSL, but that requires a server restart, so it may take > a few days. I'm doing something that requires M2Crypto to > run on a range of machines, which turns out to be rather harder > than expected. Which version of OpenSSL is that? -- Heikki Toivonen From haraldarminmassa at gmail.com Sat Jan 6 17:46:49 2007 From: haraldarminmassa at gmail.com (GHUM) Date: 6 Jan 2007 14:46:49 -0800 Subject: sheeps be carefull of Python Message-ID: <1168123609.117003.310180@v33g2000cwv.googlegroups.com> sometimes Python is more dangerous than documented: http://news.nationalgeographic.com/news/2006/09/060915-python-ewe.html Harald From mail at microcorp.co.za Wed Jan 10 02:33:05 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 10 Jan 2007 09:33:05 +0200 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com><7x7ivz88af.fsf@ruckus.brouhaha.com><7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: <019e01c7348c$1cae4fc0$03000080@hendrik> "Steven D'Aprano" wrote: > On Tue, 09 Jan 2007 10:27:56 +0200, Hendrik van Rooyen wrote: > > > "Steven D'Aprano" wrote: > > > > > >> On Mon, 08 Jan 2007 13:11:14 +0200, Hendrik van Rooyen wrote: > >> > >> > When you hear a programmer use the word "probability" - > >> > then its time to fire him, as in programming even the lowest > >> > probability is a certainty when you are doing millions of > >> > things a second. > >> > >> That is total and utter nonsense and displays the most appalling > >> misunderstanding of probability, not to mention a shocking lack of common > >> sense. > > > > Really? > > > > Strong words. > > > > If you don't understand you need merely ask, so let me elucidate: > > > > If there is some small chance of something occurring at run time that can > > cause code to fail - a "low probability" in all the accepted senses of the > > word - and a programmer declaims - "There is such a low probability of > > that occurring and its so difficult to cater for that I won't bother" > > - then am I supposed to congratulate him on his wisdom and outstanding > > common sense? > > > > Hardly. - If anything can go wrong, it will. - to paraphrase Murphy's law. > > > > To illustrate: > > If there is one place in any piece of code that is critical and not protected, > > even if its in a relatively rarely called routine, then because of the high > > speed of operations, and the fact that time is essentially infinite, > > Time is essentially infinite? Do you really expect your code will still be > in use fifty years from now, let alone a billion years? My code does not suffer from bit rot, so it should outlast the hardware... But seriously - for the sort of mistakes we make as programmers - it does not actually need infinite time for the lightning to strike - most things that will actually run overnight are probably stable - and if it takes say a week of running for the bug to raise its head - it is normally a very difficult problem to find and fix. A case in point - One of my first postings to this newsgroup concerned an intermittent failure on a serial port - It was never resolved in a satisfactory manner - eventually I followed my gut feel, made some changes, and it seems to have gone away - but I expect it to bite me anytime - I don't actually *know* that its fixed, and there is not, as a corollary to your sum below here, any real way to know for certain. > > I know flowcharts have fallen out of favour in IT, and rightly so -- they > don't model modern programming techniques very well, simply because modern > programming techniques would lead to a chart far too big to be practical. I actually like drawing data flow diagrams, even if they are sketchy, primitive ones, to try to model the inter process communications (where a "process" may be just a python thread) - I find it useful to keep an overall perspective. > But for the sake of the exercise, imagine a simplified flowchart of some > program, one with a mere five components, such that one could take any of > the following paths through the program: > > START -> A -> B -> C -> D -> E > START -> A -> C -> B -> D -> E > START -> A -> C -> D -> B -> E > ... > START -> E -> D -> C -> B -> A > > There are 5! (five factorial) = 120 possible paths through the program. > > Now imagine one where there are just fifty components, still quite a > small program, giving 50! = 3e64 possible paths. Now suppose that there is > a bug that results from following just one of those paths. That would > match your description of "lowest probability" -- any lower and it would > be zero. > > If all of the paths are equally likely to be taken, and the program takes > a billion different paths each millisecond, on average it would take about > 1.5e55 milliseconds to hit the bug -- or about 5e44 YEARS of continual > usage. If every person on Earth did nothing but run this program 24/7, it > would still take on average almost sixty million billion billion billion > years to discover the bug. In something with just 50 components it is, I believe, better to try to inspect the quality in, than to hope that random testing will show up errors - But I suppose this is all about design, and about avoiding doing known no - nos. > > But of course in reality some paths are more likely than others. If the > bug happens to exist in a path that is executed often, or if it exists > in many paths, then the bug will be found quickly. On the other hand, if > the bug is in a path that is rarely executed, your buggy program may be > more reliable than the hardware you run it on. (Cynics may say that isn't > hard.) Oh I am of the opposite conviction - Like the fellow of the Circuit Cellar I forget his name ( Steve Circia (?) ) who said: "My favourite Programming Language is Solder"... I find that when I start blaming the hardware for something that is going wrong, I am seldom right... And this is true also for hardware that we make ourselves, that one would expect to be buggy, because it is new and untested. It is almost as if the tools used in hardware design are somehow less buggy than a programmer's fumbling attempts at producing something logical. > > You're project manager for the development team. Your lead developer tells > you that he knows this bug exists (never mind how, he's very clever) and > that the probability of reaching that bug in use is about 3e-64. This is too convenient - This lead developer is about as likely as my infinite time... > > If it were easy to fix, the developer wouldn't even have mentioned it. > This is a really hard bug to fix, it's going to require some major > changes to the program, maybe even a complete re-think of the program. > Removing this bug could even introduce dozens, hundreds of new bugs. > > So okay Mister Project Manager. What do you do? Do you sack the developer, > like you said? How many dozens or hundreds of man-hours are you prepared > to put into this? If the money is coming out of your pocket, how much are > you willing to spend to fix this bug? > Do a design review, Put in a man with some experience, and hope for the best - in reality what else can you do, short of trying to do it all yourself? > > [snip] > > > How is this a misunderstanding of probability? - probability applies to > > any one trial, so in a series of trials, when the number of trials is > > large enough - in the > > order of the inverse of the probability, then ones expectation must be > > that the rare occurrence should occur... > > "Even the lowest probability is a certainty" is mathematically nonsense: > it just isn't true -- no matter how many iterations, the probability is > always a little less than one. And you paper over a hole in your argument > with "when the number of trials is large enough" -- if the probability is > small enough, "large enough" could be unimaginably huge indeed. *grin* sure - this is not the maths tripos... But I am willing to lay a bet, that over an evening's play at roulette, the red will come up at least once. I would expect to win too. > > Or, to put it another way, while anything with a non-zero probability > _might_ happen (you might drop a can of soft drink on your computer, > shorting it out and _just by chance_ causing it to fire off a perfectly > formatted email containing a poem about penguins) we are justified in > writing off small enough probabilities as negligible. It's not that they > can't happen, but the chances of doing so are so small that we can rightly > expect to never see them happen. I promise I won't hold my breath... Man inspecting the work of a bunch of monkeys with Keyboards: "Hey Harry - I think we might have something here - check this: To be, or not to be, that is the iuuiihiuweriopuqewt" > > You might like to read up on Borel's "Law" (not really a law at all, > really just a heuristic for judging when probabilities are negligible). > Avoid the nonsense written about Borel and his guideline by Young Earth > Creationists, they have given him an undeserved bad name. > > http://www.talkorigins.org/faqs/abioprob/borelfaq.html > ok will have a look later 8<-------------- > > Now how does all this show a shocking lack of common sense? > > You pay no attention to the economics of programming. Programming doesn't > come for free. It is always a trade-off for the best result with the least > effort. Any time people start making absolute claims about fixing every > possible bug, no matter how obscure or unlikely or how much work it will > take, I know that they aren't paying for the work to be done. Too much assumption from too little data. Have actually been the part owner of a small company for the last two decades or so - I am paying, all right, I am paying, and paying... Which maybe is why I want perfection... - Hendrik From removethis.kartic.krishnamurthy at gmail.com Mon Jan 29 13:56:09 2007 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 29 Jan 2007 18:56:09 GMT Subject: Sourcing Python Developers Message-ID: <45BE4348.9020500@gmail.com> Hello, My company has quite a few opening involving python expertise. We are always looking for python resources (and find it difficult filling these positions, might I add). Is there any place to find developers' resumes (like finding jobs from http://python.org/community/jobs/)? If any one knows of a resume repository (other than Monster, Dice, Costs-an-arm-and-leg job site) please share. In any case, we have immediate requirements for a Pythonista with C++, MySQL, XML, Debian expertise. Please email resume to: python-resumes(at)temporaryforwarding.com Thank you, --Kartic From dizzydd44 at hotmail.com Wed Jan 3 00:12:35 2007 From: dizzydd44 at hotmail.com (Dave Dean) Date: Wed, 03 Jan 2007 05:12:35 GMT Subject: Iterate through list two items at a time References: Message-ID: <7XGmh.28517$hI.25073@newssvr11.news.prodigy.net> Thanks for all the fast responses. I'm particularly a fan of the zip method, followed closely by the xrange example. All, of course, are a lot of help! Thanks, Dave From john.pye at gmail.com Mon Jan 8 18:38:24 2007 From: john.pye at gmail.com (John Pye) Date: 8 Jan 2007 15:38:24 -0800 Subject: error with "import md5" Message-ID: <1168299504.482909.246970@q40g2000cwq.googlegroups.com> Hi all, I'm doing some convoluted stuff with running a python script from inside a shared library that's running inside a Tcl/Tk interpreter. It's all been going surprisingly well, up until the point where my Python script attempts to import matplotlib, which includes a reference to import md5: I get this error bubbling through: Traceback (most recent call last): File "/home/john/ascend/models/johnpye/extpy/extpytest.py", line 5, in ? import matplotlib; File "/usr/lib/python2.4/site-packages/matplotlib/__init__.py", line 150, in ? import md5, os, re, shutil, sys, warnings ImportError: /usr/lib/python2.4/lib-dynload/md5.so: undefined symbol: _Py_NoneStruct Is it possible that this could be a bug in the md5 library (Python 2.4.4c1), or does it look like a problem perhaps with RTDL_NOW | RTDL_LAZY stuff? Cheers JP From dickey at saltmine.radix.net Fri Jan 26 19:03:38 2007 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Sat, 27 Jan 2007 00:03:38 -0000 Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> Message-ID: <12rl5mq4nnqoea0@corp.supernews.com> Neil Cerutti wrote: > I don't really expect it to work, but if anything will, that is > it. Curses supports only ASCII and a some special symbol codes > defined by curses. un - no. Curses supports whatever the flavor of curses you have does. Often that's the 8-bit flavor of ncurses, but the limitation is definitely in the python configuration. -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From sebastian_busch at gmx.net Sun Jan 7 04:20:21 2007 From: sebastian_busch at gmx.net (Sebastian Busch) Date: Sun, 07 Jan 2007 10:20:21 +0100 Subject: where is python on linux? In-Reply-To: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> Message-ID: Frank Potter wrote: > ... where is the executable python file? ... does whereis python tell you what you want to know? sebastian. From jmfbahciv at aol.com Wed Jan 10 11:22:19 2007 From: jmfbahciv at aol.com (jmfbahciv at aol.com) Date: Wed, 10 Jan 07 16:22:19 GMT Subject: Internet Survey References: <1168354695.334946.157400@51g2000cwl.googlegroups.com> <0001HW.C1CA63B1059BC980F0203648@news.verizon.net> Message-ID: In article <0001HW.C1CA63B1059BC980F0203648 at news.verizon.net>, Lefty Bigfoot wrote: >On Wed, 10 Jan 2007 08:28:33 -0600, jmfbahciv at aol.com wrote >(in article ): > >> In article , >> "Elan Magavi" wrote: >>> Is that like.. OctaPussy? >> >> I didn't read their stuff. Are they really trying to put a >> round peg in a square hole? > >Sounds more like an octagonal pole in a round hole. Nah, I figured they picked the word octal because it's never been used before..... /BAH From aahz at pythoncraft.com Fri Jan 19 16:12:12 2007 From: aahz at pythoncraft.com (Aahz) Date: 19 Jan 2007 13:12:12 -0800 Subject: OT Annoying Habits (Was: when format strings attack) References: Message-ID: In article , Carroll, Barry wrote: > >Personally, I don't think top-posting is the most annoying newsgroup >habit. I think it's making a big fuss about minor inconveniences. =20 Thing is, nobody will ignore your posts for following standard Usenet conventions, but some of us will definitely ignore your posts if you don't. It's your choice how much attention you want. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From rw at smsnet.pl Sun Jan 28 13:18:06 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Sun, 28 Jan 2007 19:18:06 +0100 Subject: string byte dump References: <9609c$45bce423$d8a87c2a$8428@NEXICOM.NET> Message-ID: <874pqb9fs1.fsf@smsnet.pl> Jammer writes: > Does anyone that knows python want to write me a byte dump for strings? :-) > > I am trying to modify a plugin (that someone else wrote) that uses > interprocess communication. > It works on strings without special characters but it fails on other > stings like "Bj?rk". > > It calls decode('utf8') but I guess the strings are not utf8 so I need > to find out what is being input. Try this: >>> "abc".encode("hex") '616263' -- HTH, Rob From bearophileHUGS at lycos.com Sat Jan 13 08:12:40 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Jan 2007 05:12:40 -0800 Subject: AlphaBeta Search In-Reply-To: <1168649650.163717.263240@38g2000cwa.googlegroups.com> References: <1168649650.163717.263240@38g2000cwa.googlegroups.com> Message-ID: <1168693959.611167.80050@s34g2000cwa.googlegroups.com> Chris wrote: > I know this probably seems trivial, but I can't seem to find the bug in > my alphabeta search implementation. This is another alphabeta implementation (all the nicest algorithms are inside this AIMA codebase): http://aima.cs.berkeley.edu/python/games.html Later when you program works you can find this helpful to improve your algorithm: http://citeseer.ist.psu.edu/11954.html Bye, bearophile From vinay_sajip at yahoo.co.uk Sun Jan 21 11:01:16 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 21 Jan 2007 08:01:16 -0800 Subject: selective logger disable/enable In-Reply-To: <1169349399.938121.238430@38g2000cwa.googlegroups.com> References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> <1169349399.938121.238430@38g2000cwa.googlegroups.com> Message-ID: <1169395276.181654.160810@a75g2000cwd.googlegroups.com> Gary Jefferson wrote: > Thanks for the reply Vinay. I had been reading those docs prior to > posting, but addFilter/removeFilter only work on individual logger > instances and handlers. I want to globally enable/disable multiple > logger instances, based on their namespaces (see the example I > provided). I cannot find a way to do this. I can certainly call > addFilter on every instance of every logger throughout the source code, > but this is more than inconvenient -- it breaks when new modules are > added with their own loggers in their own namespaces (until fixed by > manually adding addFilter() to those instances). > > e.g., suppose you have a source tree with a several components that do > network access, and several components that do other things like saving > state to disk, accessing the filesystem, etc. And suppose you find a > bug that you think is in the networking code. It would be nice to be > able to GLOBALLY enable just the loggers that belong in the networking > namespace, and disable all others (similar to how Filters are supposed > to work for individual loggers). And then to be able to do this with > any component, by providing, for example, a command line switch or > environment variable. Otherwise, the poor programmer is forced to go > and edit every module in the source tree to selectively turn on/off > their respecitve loggers. Or am I missing something really obvious > about how this is done with the logging module? I don't know enough about your target environment and application to necessarily give you the best advice, but I'll make some general comments which I hope are useful. You seem to be thinking that loggers are binary - i.e. you turn them on or off. But they can be controlled more finely than that; you should be able to get the effect that you want by using the different logging levels available judiciously, as well as using the fact that loggers inhabit a named hierarchy. Note that loggers, by default, inherit the level of the first ancestor logger which has an explicitly set level (by ancestor, I mean in the name hierarchy). The root logger's default level is WARNING, so by default all loggers will work at this level. [N.B. You can also set levels for individual handlers, e.g. to ensure that only CRITICAL conditions are emailed to a specified email address using SMTPHandler, or that ERROR conditions and above are written to file but not to console.] So, for your networking scenario, let's suppose you do the following: Have all network loggers live in the hierarchy namespace below "network" (e.g. "network", "network.tcp", "network.http" etc.). By default, all of these will only log events of severity WARNING and above. Also, suppose you log events in your application code, which are sometimes but not always of interest, at level DEBUG or level INFO. Then, these events will never show up in the logging output, since they are below WARNING in severity. Subsequently, if you want to turn on logging verbosity for the network code only, you can arrange, via a command-line switch or environment variable or configuration file, to do logging.getLogger("network").setLevel(logging.DEBUG) whereupon you will start seeing events from the networking code at severity DEBUG and INFO. This will affect all loggers in the "network" hierarchy whose levels you have not explicitly set (so that they will get the effective level of the first ancestor which has a level explicitly set - the logger named "network"). If all you are interested in is turning on verbosity based on different event severities (levels), you should not need to use or set Filters. Filters are for use only when levels don't meet your use case requirements. Best regards, Vinay Sajip From hg at nospam.org Mon Jan 15 04:36:35 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 10:36:35 +0100 Subject: check if there is data in stdin without blocking References: <4PMqh.47441$X97.9536@newsfe18.lga> <1168876929.239494.93830@v45g2000cwv.googlegroups.com> Message-ID: Paul Boddie wrote: > hg wrote: >> import select > > [...] > >> File "/home/philippe/Desktop/select.py", line 4, in ? > > Consider which module Python is trying to import here: the standard > library select module or your own program? > > Paul Argh !!!! ;-) thanks From pierre at saiph.com Sat Jan 13 04:58:04 2007 From: pierre at saiph.com (Imbaud Pierre) Date: Sat, 13 Jan 2007 10:58:04 +0100 Subject: closed: module file In-Reply-To: <45a7ba78$0$316$426a74cc@news.free.fr> References: <45a7ba78$0$316$426a74cc@news.free.fr> Message-ID: <45a8ad2d$0$31416$426a34cc@news.free.fr> Imbaud Pierre a ?crit : > I am willing to retrieve the file an imported module came from; > module.__file__, or inspect.getfile(module) only gives me the > relative file name. How do I determine the path? > Its obviously possible from python: ipython displays the information > (interactively: *module?*). > Python 2.4 on Suse 9.3 (clueless, I guess) Apologies: module.__file__, or inspect.getfile(module) only *gave* me the relative file name, because the module was found in the current directory! Changing the current directory, and having the module be found thru the path, changed the returned path to an absolute directory! Hence the simplest form at hand was used. Thank you, python! From danb_83 at yahoo.com Tue Jan 9 22:39:22 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Jan 2007 19:39:22 -0800 Subject: Summarizing data by week In-Reply-To: <1168372624.543712.149070@77g2000hsv.googlegroups.com> References: <1168372624.543712.149070@77g2000hsv.googlegroups.com> Message-ID: <1168400362.399657.291890@k58g2000hse.googlegroups.com> On Jan 9, 1:57 pm, "Mike Orr" wrote: > What's the best way to summarize data by week? I have a set of > timestamped records, and I want a report with one row for each week in > the time period, including zero rows if there are weeks with no > activity. I was planning to use ISO weeks because datetime has a > convenient .isocalendar() method, but I want each output row to have a > label like this: > > 2006 week 5 (Feb) > > However, to get the month (of the Thursday of that week) I have to > convert it back to an actual date,and I don't see a method to do that > in datetime or dateutil or mx.DateTime. > > I was planning to use a dateutil.rrule to generate the weeks from the > minimum to maximum date, including any weeks that have no activity (so > they won't be in the dictionary). But rrule sequences are based on an > actual start date, not an ISO week, so that won't work. Unless perhaps > I take the minimum date and calculate the Thursday of that week, and > start from there. Then all my conversions would be to iso_week rather > than from iso_week. That would work. The first Thursday of the year can be computed as: def first_thursday(year): jan1 = datetime.date(year, 1, 1) return jan1 + datetime.timedelta((3 - jan1.weekday()) % 7) From gagsl-py at yahoo.com.ar Sun Jan 14 11:50:44 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Jan 2007 13:50:44 -0300 Subject: Decorators inside of class and decorator parameters References: <1168728983.541526.202320@l53g2000cwa.googlegroups.com> Message-ID: "Colin J. Williams" escribi? en el mensaje news:eodck0$32a$1 at sea.gmane.org... > Gabriel Genellina wrote: >> As said in the beginning, there is no use for decorators as methods >> (perhaps >> someone can find a use case?) > Except, perhaps to indicate to the script reader that the decorator only > applies within the class? But it looks rather strange - a method without self, that is not a classmethod nor static method, and can't be called on an instance... -- Gabriel Genellina From S.Mientki-nospam at mailbox.kun.nl Sat Jan 6 13:49:52 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 06 Jan 2007 19:49:52 +0100 Subject: still struggling, howto use a list-element as a name ? Message-ID: In the example below, "pin" is an object with a number of properties. Now I want 1- an easy way to create objects that contains a number of these "pin" 2- an multiple way to access these "pin", i.e. device.pin[some_index] device.some_logical_name ad 1: a dictionary (as "pinlist" in the example) seems a very convenient way (from a viewpoint of the device creator). As you can see in the "__init__" section this dictionary can easily be transported to the pin-objects. ad 2: THAT's the problem: how do automate these lines "self.GND = self.pin[0]" I'm also in for other solutions. thanks, Stef class Power_Supply(device): pinlist = { 0: ('GND', _DIG_OUT, _par2), 1: ('VCC', _DIG_OUT, _par33) } def __init__(self): # store pin-names and pin-parameters in pins for k in self.pinlist.keys(): self.pin[k].Name = self.pinlist[k][0] self.pin[k].Value = self.pinlist[k][2] # for some pins, we also want to be able to use logical names # HOW TO USE SOMETHING like # "self.pinlist[0] = self.pin[0]" # INSTEAD OF self.GND = self.pin[0] self.VCC = self.pin[1] # create a Power_Supply instance and # test if pins can be referenced in Power = Power_Supply() netlist1 = ( Power.VCC, Power.pin[1], Power.GND, Power.pin[0] ) From sschwarzer at sschwarzer.net Fri Jan 5 20:38:15 2007 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sat, 06 Jan 2007 02:38:15 +0100 Subject: How to get file name on a remote server with ftplib? In-Reply-To: <1168009814.236723.105280@51g2000cwl.googlegroups.com> References: <1168008952.020516.130890@s80g2000cwa.googlegroups.com> <1168009814.236723.105280@51g2000cwl.googlegroups.com> Message-ID: <459EFD87.9000107@sschwarzer.net> On 2007-01-05 16:10, wittempj at hotmail.com wrote: > alex wrote: >> My script is trying to get a file from a remote server, every day it >> ftps from a directory. My code works perfect if I know the name of the >> file in the remote directory. >> >> ftp.retrbinary('RETR ' + filename, handleDownload) >> >> The problem is that in the future the name of the file is going to be >> aleatory. How can I get the file's name (only one file is in that >> directory) and store it in a variable before executing ftp.retrbinary? >> >> Thanks a lot for your help, >> > You can use the nlst(dirname) method to retrieve a directory listing on > the remote server. If the remote server doesn't support NLST command > rhen you could do ftp.retrlines('LIST') and parse the results to get a > directory listing. ftputil ( http://ftputil.sschwarzer.net/ ) could help with this parsing. A session may look like >>> import ftputil >>> host = ftputil.FTPHost("ftp.domain.com", "user", "password") >>> file_names = host.listdir(host.curdir) >>> file_names ['wanted_filename'] >>> file_name = file_names[0] >>> host.download(file_name, file_name, "b") >>> host.close() Ok, I admit this isn't a pure-ftplib solution. :-) Stefan -- Dr.-Ing. Stefan Schwarzer SSchwarzer.com - Softwareentwicklung f?r Technik und Wissenschaft http://sschwarzer.com From Robert.Katic at gmail.com Tue Jan 16 11:27:18 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 16 Jan 2007 08:27:18 -0800 Subject: arguments of a function/metaclass In-Reply-To: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> References: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> Message-ID: <1168964835.087773.221950@s34g2000cwa.googlegroups.com> rubbishemail at web.de je napisao/la: > Hello, > > > I have a member function with many (20) named arguments > > def __init__(self,a=1,b=2): > self.a=a > self.b=b > > I would like to get rid of the many redundant lines like self.a=a and > set the members automatically. > The list of default arguments could be given like > > def __init__(**kwargs): > arglist={"a":1,"b":2] > > if this makes things easier > > Of course there has to be a check that raises an error in case of an > unknown argument not mentioned in this list. > > > I am sure there is an elegant way how to do this, could you give me any > hints??? > > > Many thanks > > > > Daniel A simply solution: def __init__(self, a=1, b=2, c=3, ......): for key, val in locals().items(): if key != 'self': setattr(self.__class__, key, val) in addition: def set(self, **kwarg): for key in kwargs: if hasattr(self.__class__, key): setattr(self.__class__, key, kwargs[key]) else: raise .... This solution is appropriate with use of proprieties. For better proprety usage look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418 From buzzard at urubu.freeserve.co.uk Mon Jan 29 20:27:08 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 30 Jan 2007 01:27:08 +0000 Subject: set update in 2.5 In-Reply-To: References: <45bc0c0c.0@entanet> Message-ID: <45bea503.0@entanet> Peter Otten wrote: > Duncan Smith wrote: > > >> In moving from 2.4 to 2.5 I find that some of my unit tests are now >>failing. I've worked out that the problem relates to the set update >>method. In 2.4 I could update a set with an iterable type derived from >>dict as the argument. I now find that the set is updated with the hash >>values of the items in my iterable, rather than the items themselves. >>Converting to a list first gets round the problem. >> >>My iterable type has the same API as 'set' but requires items to have >>hashable 'uid' attributes, so they can also be looked up by uid. I hope >>this, and the fact that this worked fine in 2.4 will be enough to track >>down the issue without me having to paste reams of code (other than the >>following, pasted from IDLE). Any ideas? Cheers. >> >>Duncan >> >> >> >>>>>from graphItems import Node >>>>>from keyed_sets import KeyedSet >>>>>n = Node(1) >>>>>n.uid >> >>1 >> >>>>>k = KeyedSet([n]) >>>>>k >> >>KeyedSet([1]) >> >>>>>type(iter(k).next()) >> >> >> >>>>>type(k[1]) >> >> >> >>>>>s = set() >>>>>s.update(list(k)) >>>>>type(iter(s).next()) >> >> >> >>>>>s = set() >>>>>s.update(k) >>>>>type(iter(s).next()) >> >> >> >>>>>s = set() >>>>>s.add(n) >>>>>type(iter(s).next()) >> >> >> >>>>>hash(n) >> >>1 >> > > Is your KeyedSet derived from dict? > Thanks Peter. It is derived from dict. > $ python2.5 > [snip] > >>>>class D(dict): > > ... def __iter__(self): return self.itervalues() > ... > >>>>d = D(a=1, b=2) >>>>set(d) > > set(['a', 'b']) > > > $ python2.4 > [snip] > >>>>class D(dict): > > ... def __iter__(self): return self.itervalues() > ... > >>>>d = D(a=1, b=2) >>>>set(d) > > set([1, 2]) > > > I think you should file a bug report. The fix is probably > > --- setobject.c 2006-09-08 08:02:26.000000000 +0200 > +++ setobject_new.c 2007-01-28 10:02:24.071688248 +0100 > @@ -854,7 +854,7 @@ > if (PyAnySet_Check(other)) > return set_merge(so, other); > > - if (PyDict_Check(other)) { > + if (PyDict_CheckExact(other)) { > PyObject *value; > Py_ssize_t pos = 0; > while (PyDict_Next(other, &pos, &key, &value)) { > > Peter I will file a report. Cheers. Duncan From martin at v.loewis.de Wed Jan 3 10:52:22 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 16:52:22 +0100 Subject: bad marshal data in site.py in fresh 2.5 install win In-Reply-To: References: <4595B89C.9090208@v.loewis.de> Message-ID: <459bd136$0$20860$9b622d9e@news.freenet.de> TiNo schrieb: > File "F:\Python25\lib\encodings\__init__.py", line 32, in > from encodings import aliases > ValueError: bad marshal data > > also removed site.pyc, and run it again, but with the same result. It's likely rather aliases.pyc which is bad, so try removing that. If in doubt, remove all .pyc files. If one of them is bad, it's either because the stick wasn't ejected properly at some point, or it suffers from data loss. Regards, Martin From toby at tobiah.org Thu Jan 25 17:39:57 2007 From: toby at tobiah.org (Tobiah) Date: Thu, 25 Jan 2007 14:39:57 -0800 Subject: Right-Justifying Numeric Output In-Reply-To: References: Message-ID: <45b92516$0$24366$88260bb3@free.teranews.com> > Thank you very much! I didn't see this in any of my Python books or on > the I like to look at the printf docs for any C compiler. On Unix, man 3 printf -- Posted via a free Usenet account from http://www.teranews.com From exarkun at divmod.com Wed Jan 17 11:40:11 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 17 Jan 2007 11:40:11 -0500 Subject: how to write unicode to a txt file? In-Reply-To: <1169051293.848769.163860@s34g2000cwa.googlegroups.com> Message-ID: <20070117164011.11447.458124722.divmod.quotient.19755@ohm> On 17 Jan 2007 08:28:14 -0800, Frank Potter wrote: >I want to change an srt file to unicode format so mpalyer can display >Chinese subtitles properly. >I did it like this: > >txt=open('dmd-guardian-cd1.srt').read() >txt=unicode(txt,'gb18030') >open('dmd-guardian-cd1.srt','w').write(txt) > >But it seems that python can't directly write unicode to a file, >I got and error at the 3rd line: >UnicodeEncodeError: 'ascii' codec can't encode characters in position >85-96: ordinal not in range(128) > >How to save the unicode string to the file, please? You cannot save unicode to a file. Files can only contain bytes. You can encode the unicode into a str and then write the str to the file. f = open('...', 'w') f.write(txt.encode(encoding)) f.close() The encoding you select must be able to represent each code point in the unicode object you encode with it. The "ascii" encoding cannot encode all of your code points, so when Python implicitly uses it, you get the exception above. If you use an encoding like "utf-8" which can represent every code point, you won't see this exception. You could also use the same encoding which you used to decode the str originally, "gb18030", which will be able to represent every code point, since it produced them in the first place. Of course, if you do this, you may as well not even bother to do the decoding in the first place, unless you have some code in between the input and output steps which manipulates the unicode in some way. Jean-Paul From omniflex at mail.ru Mon Jan 8 11:06:54 2007 From: omniflex at mail.ru (Alex) Date: Mon, 8 Jan 2007 18:06:54 +0200 Subject: popen, Pipes with programs that expect user input Message-ID: <536598837.20070108180654@mail.ru> Hello everyone, I am writing a terminal server client-server application, that offers the client the ability to run commands on the server and read their output. So far everything works fine, but I encounter a problem with commands which require some sort of user input; i.e. they don't return immediately. This is my setup: Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32 --------------------- import os def myExecEx(command): """Executes a command and returns a tuple (stdin, stdout_stderr)""" outErrFile, inFile = os.popen4(command) return (inFile, outErrFile) fouterr, fin = myExecEx('date') # try 'date /t' as well #fin.write('\n') try: data=fouterr.read() print data except: print "an exception occurred" --------------------- On Windows, the 'date' command will show the current date, and then prompt me to enter a new one (thus waiting for something to come to STDIN) I am reading the output with: data=fouterr.read() but data is empty (also, I must mention that "an exception occurred" is not shown) If I execute myExecEx('date /t') (the /t parameter tells the date tool that it has to print the current date and not wait for user input), then the program works as expected). Also, I noticed that if I uncomment the line in which I wrote to STDIN: fin.write('\n') then I can read STDOUT without problems (but this is counter-intuitive to me; I don't know what to write to STDIN before I see what STDOUT has to say). I have tried other commands from the popen family, but in either case the behaviour was the same. Could someone point out the cause of this? It seems to me that the interpreter is stuck at this line data=fouterr.read() and it won't go forward unless popen returns. If so, how should the objective be achieved? Thank you From jstroud at mbi.ucla.edu Mon Jan 15 22:59:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 15 Jan 2007 19:59:26 -0800 Subject: Does class patching actually work In-Reply-To: References: Message-ID: John Nagle wrote: > In M2Crypto/m2urllib there is this: > > import string, sys, urllib > from urllib import * > > def open_https(self, url, data=None, ssl_context=None): > ... > > # Minor brain surgery. > URLopener.open_https = open_https > > The intent of this is to replace method open_https of class URLopener > with a local, patched version. > > Does that actually work? When I've tried to do that in other code, it > seems to have no effect. In fact, I can write > > URLopener.open_https = None > > and nothing changes. > > John Nagle I'm not able to reproduce your results with python 2.5. py> from urllib import * py> URLopener.open_https = None py> URLopener.open_https py> type(URLopener.open_https) py> def doit(self, url, data=None, ssl_context=None): ... print 'self is %s, url is %s' % (self, url) ... ... py> URLopener.open_https = doit py> u = URLopener() py> u = u.open_https('http://wherever.com') self is , url is http://wherever.com From exarkun at divmod.com Tue Jan 2 12:10:28 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 2 Jan 2007 12:10:28 -0500 Subject: Looking for python SIP/MGCP stacks In-Reply-To: <1ECA23B17E8AB54C859FA0449B729F0E03428702@xmb-sjc-235.amer.cisco.com> Message-ID: <20070102171028.11447.1431176323.divmod.quotient.4684@ohm> On Tue, 2 Jan 2007 09:02:17 -0800, "Jenny Zhao \(zhzhao\)" wrote: >Thanks Anthony. > >I am wondering where I can get Divmod Sine and Shtoom. Are they open >source ? > http://divmod.org/trac/wiki/DivmodSine http://divmod.org/trac/wiki/ShtoomProject Shtoom is LGPL. Sine borrows some code from it, so it is probably LGPL as well. Jean-Paul From pavlovevidence at gmail.com Sun Jan 21 19:04:33 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 21 Jan 2007 16:04:33 -0800 Subject: Reading Fortran Data References: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> Message-ID: <1169424273.929396.133880@m58g2000cwm.googlegroups.com> Tyler wrote: > Hello All: > > After trying to find an open source alternative to Matlab (or IDL), I > am currently getting acquainted with Python and, in particular SciPy, > NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's > NumPy manual, I have a quick question (hopefully) regarding how to read > in Fortran written data. I think you made a good choice, if for no other reason than the fact that Python and numpy absolutely rock when it comes to interfacing with Fortran (and any C code that can be called by Fortran). I suggest having a look at pyfort and/or f2py to see if they can be useful to you. If your data files are temporary (that is, they only exist to pass data from one program to another), you might not even need them. For completeness, I'll answer how to write as well as read Fortran data. It turns out that all of this can be done without numpy, but there is one very convenient numpy function. > The data files are not binary, but ASCII text files with no formatting > and mixed data types (strings, integers, floats). For example, I have > the following write statements in my Fortran code: > > I write the files as such: > WRITE(90,'(A30)') fgeo_name > WRITE(90,'(A30)') fmed_name Fortran pads it's output when using a width field. A good way to do this in Python is to use string formating with a given width. If fgeo_name is a Python string, they you'd write something like this: f.write("%-30s\n" % fgeo_name) The negeative sign is to pad the name on the left, which is how Fortran does it (by default, Python string formatting pads on the right). You could also use the .ljust method of string objects: f.write(fgeo_name.ljust(30) + "\n") Don't forget the newline on the end. > WRITE(90,*) nfault,npoint Fortran writes this as two arbitrary integers separated by a space. To do this in Python, use string formating. This also adds a space to the beginning as most Fortran implementations seem to do. f.write(" %d %d\n" % (nfault,npoint)) > WRITE(90,*) (xpt(n), n=1,npoint) > WRITE(90,*) (ypt(n), n=1,npoint) Now, an array. I think you'd be safest writing one value per line. You would do that like this: for x in xpt: f.write(" %#g\n" % x) The # sign is there to force the number to be formatted with a decimal point. You'll probably want to tweak the format string in other ways (to specify a precision, for instance). > and, > > WRITE(10,'(A30)') fname > DO i=1,nfault > WRITE(10,*) dbn(i),dtn(i),xfwnt(i),yfwnt(i),xfent(i),yfent(i),& > & slpvlS(i),slpvlD(i),slpvlT(i),segdp1(i) > END DO I'd write this as one number per line. f.write("%-30s\n" % fname) for i in range(nfault): f.write(" %#g\n" % dbn[i]) f.write(" %#g\n" % dtn[i]) # and so on If you know Python well, there are "more Pythonic" ways to do this, but this is straightforward and works well enough. Now for the reading part. > I then respectively read them into Fortran as: > READ(70,'(A30)') fgeo_name > READ(70,'(A30)') fmed_name Once you've opened a file, then: fgeo_name = f.readline().strip() fmed_name = f.readline().strip() Note that this strips the padding off the name. If the first line of the file is "ABC" followed by 27 spaces, the result will be "ABC" with the spaces stripped. > READ(70,*) nfault,npoint Python doesn't have any built in input formating (a la READ in Fortran or scanf in C), so one usually does this kind of thing by hand. Fortunately, Python makes this quite easy. The following will do what you want: s = f.readline().split() nfault = int(s[0]) npoint = int(s[1]) Here's what happens: it reads in a line, and splits the line on whitespace into substrings. It assigns the list of substrings to s. Then it converts the first substring (s[0]) to an int and assigns it to nfault; the second (s[1]) to npoint. With more advanced knowledge of Python, you could write it in one line like this: nfault,npoint = (int(ss) for ss in f.readline().split()) > READ(70,*) (x(n), n=1,npoint) > READ(70,*) (y(n), n=1,npoint) Fortran programs seem to wrap free-form output to 80 columns, inserting newlines whenever. Because of this, you can't really free-form read data in a line-by-line way (unless it's short, like the above example), but now have to read data number-by-number, which is not so straightforward. Fortunately, numpy has a function, fromfile, which reads data number-by-number. If f is the file object you're reading from, then you could read in the array like this: x = numpy.fromfile(f,sep=" ",count=npoint,dtype=numpy.Float) According to my tests, this leaves f pointing right past the end of the array, so that you can still read in other arrays and variables. Don't forget to specify the type. > and, > > READ(20,'(A30)') fname > DO i=1,nfault > READ(20,*) dbn(i),dtn(i),xfwnt(i),yfwnt(i),xfent(i),yfent(i),& > & slpvlS(i),slpvlD(i),slpvlT(i),segdp1(i) > END DO Because this line has a very good chance of being split up upon output, and because they're all real numbers, I'd use numpy.fromfile to read this, and then assign to the different arrays. So, for i in range(nfault): tmp = numpy.fromfile(f,sep=" ",count=10,dtype=numpy.Float) dbn[i] = tmp[0] dtn[i] = tmp[1] # and so on More advanced stuff, such as use of slices, can simplify this a lot. > I also read them into IDL for visualization using the "READF" command. > I was wondering how I might go about reading this into Python using > NumPy. If this is not trivial, let me know and I'll just wait until the > NumPy manual arrives. One thing I highly recommend is that you not ignore the Pure Python stuff. Many of the solutions I gave you here didn't use numpy at all. Successful usage of the numpy is going to depend a lot on knowing normal Python. For numerical applications, I suggest you become very familiar with file I/O, strings and string handling, basic container types (lists, tuples, dicts, and sets) and the operations they support (slicing, iteration), and of course, numerics. Carl Banks From h-broutin at bordeaux-port.fr Mon Jan 29 09:01:58 2007 From: h-broutin at bordeaux-port.fr (herve) Date: Mon, 29 Jan 2007 15:01:58 +0100 Subject: wxPython StatusBar Help Message-ID: <45bdfdc3$0$6722$426a74cc@news.free.fr> Hi, everybody I'm working with wxPython 2.8.1.1. Does anybody know how to change the foreground colors in a wx.StatusBar From moin at blackhole.labs.rootshell.ws Tue Jan 16 17:50:33 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Tue, 16 Jan 2007 16:50:33 -0600 Subject: POSH Message-ID: <20070116165033.a5e980d7.moin@blackhole.labs.rootshell.ws> Hi Folks, I am implementing a multithreaded Network application in Python. As most of you know that the GIL hinders the performance scalablity in SMP machines. I came across POSH. Here they talk about multiple instances of Python Interpreter sticking around a Shared memory , bypassing the GIL effect. Is anybody tried the POSH - does it really increases the performance ?? How good or bad is to have the POSH module imported into ones Python code. Please share your experience, if any, about POSH. Cheers Moin -- S.Mohideen From timr at probo.com Fri Jan 19 03:40:05 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 19 Jan 2007 08:40:05 GMT Subject: Is it possible to fasten the import of cgi? References: <45af6f47$0$322$e4fe514c@news.xs4all.nl> Message-ID: <5q01r2p4hnnrm1b8fh5dul6qmoc1lsf4re@4ax.com> Cecil Westerhof wrote: > >I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I >can not time the time used to import time, but os and sys do not take more >as a millisecond. My script itself takes 3 or 4 milliseconds. But importing >cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is >there a way to make this more fast? The import off cgi makes the script at >least 20 times as slow. Something like mod-python is not a possibility. I >could use it on my test machine, but not at the osting provider. Realistically, do you plan to support more than a few dozen requests per minute? If not, then it doesn't matter at all. The script launch overhead is an insignificant part of the user's browser experience. If you do expect a hundred requests per minute, then CGI is not an appropriate choice. You either need to switch to a one of the web frameworks (like CherryPy or Django or WebWare or one of the hundreds of others), or move to PHP. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From http Wed Jan 24 20:09:50 2007 From: http (Paul Rubin) Date: 24 Jan 2007 17:09:50 -0800 Subject: Static variables References: <45b7cfd4$0$16160$426a74cc@news.free.fr> <1169687035.433771.177900@v45g2000cwv.googlegroups.com> Message-ID: <7xd5536hep.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > An interesting solution, I have never created such grouped closures. I > don't know if this solution is better than a class with some class > attributes plus some class methods... It's a Scheme idiom but I think once the object gets this complicated, it's probably more Pythonic to use a class. From smusnmrNOSPAM at yahoo.com Fri Jan 5 08:56:52 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Fri, 5 Jan 2007 14:56:52 +0100 Subject: where to find wx package References: Message-ID: Thanks Rob! siggi "Rob Williscroft" schrieb im Newsbeitrag news:Xns98AF674C4339FrtwfreenetREMOVEcouk at 216.196.109.145... > siggi wrote in news:enl7h1$49m$1 at zam602.zam.kfa-juelich.de in > comp.lang.python: > >> Hi all, >> >> a newbie question: >> >> I have a program gui03A.py using wxPython, importing it such: >> "from wxPython.wx import *" >> >> The program works, but I get the warning message: >> >> "gui03A.py:4: DeprecationWarning: The wxPython compatibility package >> is no longer automatically generated or activly maintained. Please >> switch to the wx package as soon as possible." >> >> However, after extensive searching on www.python.org and Googling the >> web, I do not find any package with "wx" as its only name. >> >> Where can I get the wx package (for win32 XP)? > > The "wx package" talked about above is also part of WxPython, > so you have already got it. To import it use: > > import wx > > You will need to translate all (well most) identifiers in > your programme from wxBlah to wx.Blah so: > > class MyFrame( wxFrame ): > pass > > becomes > > class MyFrame( wx.Frame ): > pass > > Rob. > -- > http://www.victim-prime.dsl.pipex.com/ From felipe.lessa at gmail.com Mon Jan 8 11:35:21 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Mon, 8 Jan 2007 14:35:21 -0200 Subject: Suitability for long-running text processing? In-Reply-To: <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> Message-ID: On 1/8/07, tsuraan wrote: > > > > I just tried on my system > > > > (Python is using 2.9 MiB) > > >>> a = ['a' * (1 << 20) for i in xrange(300)] > > (Python is using 304.1 MiB) > > >>> del a > > (Python is using 2.9 MiB -- as before) > > > > And I didn't even need to tell the garbage collector to do its job. Some > info: > > It looks like the big difference between our two programs is that you have > one huge string repeated 300 times, whereas I have thousands of > four-character strings. Are small strings ever collected by python? In my test there are 300 strings of 1 MiB, not a huge string repeated. However: $ python Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # Python is using 2.7 MiB ... a = ['1234' for i in xrange(10 << 20)] >>> # Python is using 42.9 MiB ... del a >>> # Python is using 2.9 MiB With 10,485,760 strings of 4 chars, it still works as expected. -- Felipe. From harry.g.george at boeing.com Wed Jan 24 01:04:22 2007 From: harry.g.george at boeing.com (Harry George) Date: Wed, 24 Jan 2007 06:04:22 GMT Subject: My python programs need a GUI, wxPython or PyQt4? References: <45b69f63$0$24463$88260bb3@free.teranews.com> Message-ID: "Joshua J. Kugler" writes: > Daniel wrote: > > > I've downloaded both the wxPython and the PyQt4 package, and by the > > first impression I must say that the PyQt4 system had a very > > compelling presentation. From what I can understand from the feedback > > I've gotten so far is that the wxPython is a better choice when it > > comes to compability (with linux), and it's free even if I want to > > create applications and sell them. > > So, from what I understand I will have to go with PyQt4 since (from > > my understanding): > > 1. I will not sell the applications I'm working with since they will > > only be used by the internal QA at a computer game company. > > Even that is getting on shaky ground, at least according to Troll Tech. > See: http://www.trolltech.com/developer/knowledgebase/190/ So, write it > for internal use, and put up for distribution on your personal web site > (pending company approval, of course). > > j > > -- > Joshua Kugler > Lead System Admin -- Senior Programmer > http://www.eeinternet.com > PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE > > -- > Posted via a free Usenet account from http://www.teranews.com > There are several OSS suppliers that use GPL, and then try to define its meaning. They are welcome to comment on their understanding of the GPL, but they do not have the authority to actually define its legal ramifications. Check with your company legal staff. Having said that, I have been troubled by trolltech's approach from the beginning, and therefore stay away from it. PyGTK and wdxPython are solid GUIs, without the legal uncertainty. -- Harry George PLM Engineering Architecture From helgaorg at gmail.com Tue Jan 30 10:42:22 2007 From: helgaorg at gmail.com (Jason Persampieri) Date: Tue, 30 Jan 2007 10:42:22 -0500 Subject: printing to a redirected stdout from a process that was called with "2>&1 > /dev/null &" In-Reply-To: <20070130153919.GA12259@kateandchris.net> References: <1170112357.792999.241280@s48g2000cws.googlegroups.com> <20070130153919.GA12259@kateandchris.net> Message-ID: Sadly, the group is tied to Python 2.3 for now. Actually, I got around this problem by using an intermediate process that happens to handle output on its own (bsub). On 1/30/07, Chris Lambacher wrote: > > The subprocess module is probably a good starting point: > http://docs.python.org/dev/lib/module-subprocess.html > > It will allow you greater control over what happens with the output of a > process that you start. Specifically look at the the stdout and stderr > arguments to Popen. You can provide these with an open file descriptor or > a > file object and it will dump the output into there. > > -Chris > > > > _jason > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mattheww at chiark.greenend.org.uk Tue Jan 30 13:06:15 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 30 Jan 2007 18:06:15 +0000 (GMT) Subject: Synchronous shutil.copyfile() References: Message-ID: Hugo Ferreira wrote: > I have a problem. I'm using calling shutil.copyfile() followed by > open(). The thing is that most of the times open() is called before > the actual file is copied. I don't have this problem when doing a > step-by-step debug, since I give enough time for the OS to copy the > file, but at run-time, it throws an exception. > > Is there anyway to force a sync copy of the file (make python wait for > the completion)? shutil.copyfile() closes both files before it returns, so I suspect this is an OS-level bug. The most likely culprits are buggy network filesystems and buggy on-access virus scanners. -M- From robert.kern at gmail.com Thu Jan 11 18:18:51 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 Jan 2007 17:18:51 -0600 Subject: Rational Numbers In-Reply-To: References: Message-ID: Noud Aldenhoven wrote: > I'm a mathematician (in learning, with a bad feeling for English) and > don't trust irrational numbers in programming languages. You may want to look at SAGE. It provides a ton of good mathematical code. http://sage.scipy.org/sage/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steven.bethard at gmail.com Wed Jan 31 19:08:54 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 31 Jan 2007 17:08:54 -0700 Subject: How to sort using hash's key? In-Reply-To: References: Message-ID: JoJo wrote: > I want to sort a dict via its key,but I have no idea on how to do it. >>> d = dict(a=2, b=1) >>> for key in sorted(d): ... print key, d[key] ... a 2 b 1 STeVe From gagsl-py at yahoo.com.ar Mon Jan 15 17:57:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 19:57:46 -0300 Subject: The curious behavior of integer objects In-Reply-To: References: Message-ID: <7.0.1.0.0.20070115195128.05c0b0e8@yahoo.com.ar> At Monday 15/1/2007 19:28, Jim B. Wilson wrote: >Am I nuts? Or only profoundly confused? I expected the this little script >to print "0": > >class foo(int): > def __init__(self, value): > self = value & 0xF > >print foo(0x10) > >Instead, it prints "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine). Integers are immutable. Insert a print statement and you'll see your __init__ is never called. Anyway, what would you expect from "self = something"? Use __new__ instead: py> class foo(int): ... def __new__(cls, value): ... return int(value & 0xF) ... py> foo(1) 1 py> foo(0x10) 0 See "Special method names" inside the Python Reference Manual. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Wed Jan 10 10:18:59 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Jan 2007 16:18:59 +0100 Subject: Working with named groups in re module References: Message-ID: Neil Cerutti wrote: > A found some clues on lexing using the re module in Python in an > article by Martin L?wis. > Here, each alternative in the regular expression defines a > named group. Scanning proceeds in the following steps: > > 1. Given the complete input, match the regular expression > with the beginning of the input. > 2. Find out which alternative matched. you can use lastgroup, or lastindex: http://effbot.org/zone/xml-scanner.htm there's also a "hidden" ready-made scanner class inside the SRE module that works pretty well for simple cases; see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/457664 From paddy3118 at netscape.net Sat Jan 6 12:20:08 2007 From: paddy3118 at netscape.net (Paddy) Date: 6 Jan 2007 09:20:08 -0800 Subject: Python re expr from Perl to Python In-Reply-To: <1168103258.602286.146100@42g2000cwt.googlegroups.com> References: <1168103258.602286.146100@42g2000cwt.googlegroups.com> Message-ID: <1168104008.910681.46800@38g2000cwa.googlegroups.com> Paddy wrote: > Michael M. wrote: > > > In Perl, it was: > > > > > > ## Example: "Abc | def | ghi | jkl" > > ## -> "Abc ghi jkl" > > ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st > > pipe). > > $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; > > > > ## -- remove [ and ] in text > > $na =~ s/\[//g; > > $na =~ s/\]//g; > > # print "DEB: \"$na\"\n"; > > > > > > # input string > > na="Abc | def | ghi | jkl [gugu]" > > # output > > na="Abc ghi jkl gugu" > > > > > > How is it done in Python? > > Here is how to do it without regexps in python. > The first and last line below are all that are needed. The others show > intermediate expressions that lead to the result. > > >>> from itertools import groupby > > >>> na="Abc | def | ghi | jkl [gugu]" > >>> [(g[0], ''.join(g[1])) for g in groupby(na, lambda c: c not in ' \t|[]')] > [(True, 'Abc'), (False, ' | '), (True, 'def'), (False, ' | '), (True, > 'ghi'), (False, ' | '), (True, 'jkl'), (False, ' ['), (True, 'gugu'), > (False, ']')] > >>> [''.join(g[1]) for g in groupby(na, lambda c: c not in ' \t|[]') if g[0]] > ['Abc', 'def', 'ghi', 'jkl', 'gugu'] > > >>> ' '.join(''.join(g[1]) for g in groupby(na, lambda c: c not in ' \t|[]') if g[0]) > 'Abc def ghi jkl gugu' > >>> > > > - Paddy. And I leave the deletion of def to the reader :-) (i.e: I missed that bit and adding it in would make a long comprehension too long to comprehend). From agriff at tin.it Tue Jan 9 02:49:56 2007 From: agriff at tin.it (Andrea Griffini) Date: Tue, 09 Jan 2007 08:49:56 +0100 Subject: Why less emphasis on private data? In-Reply-To: References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: <45a347ad$0$22395$4fafbaef@reader2.news.tin.it> Steven D'Aprano wrote: > That is total and utter nonsense and displays the most appalling > misunderstanding of probability, not to mention a shocking lack of common > sense. While I agree that the programming job itself is not a program and hence the "consider any possibility" simply doesn't make any sense I can find a bit of truth in the general idea that *in programs* it is dangerous to be deceived by probability. When talking about correctness (that should be the main concern) for a programmer "almost never" means "yes" and "almost always" means "not" (probability of course for example kicks in about efficency). Like I said however this reasoning doesn't work well applied to the programming process itself (that is not a program... as programmers are not CPUs; no matter what bigots of software engineering approaches are hoping for). Private variables are about the programming process, not the program itself; and in my experience the added value of C++ private machinery is very low (and the added cost not invisible). When working in C++ I like much more using all-public abstract interfaces and module-level all-public concrete class definitions (the so called "compiler firewall" idiom). Another thing on the same "line of though" of private members (that should "help programmers") but for which I never ever saw *anything but costs* is the broken idea of "const correctness" of C++. Unfortunately that is not something that can be avoided completely in C++, as it roots in the core of the language. Andrea From practicalperl at gmail.com Fri Jan 19 22:20:29 2007 From: practicalperl at gmail.com (Jm lists) Date: Sat, 20 Jan 2007 11:20:29 +0800 Subject: **argv can't work Message-ID: hello members, See my script piece below: def testB(shift,**argv): print "first argument is %s" %shift print "all other arguments are:",argv testB('mails','Jen','Jen at att.com','Joe','Joe at aol.com') It can't work at all.please help tell me the reasons.thanks. From gagsl-py at yahoo.com.ar Sat Jan 20 21:51:24 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Jan 2007 23:51:24 -0300 Subject: Code reformater? In-Reply-To: References: Message-ID: <7.0.1.0.0.20070120234347.03e54a30@yahoo.com.ar> At Saturday 20/1/2007 14:37, Siggi wrote: > > When I copy/paste Python code from the web, every so often, > > the TABs are wrong, which means that the code won't work and I have to > > manually reformat the code. > > > > Is there a code reformater that can parse the code to make it right? > > > > Thanks. > >Maybe my thread "help: code formatter, 08/01/2007 helps a little? Here are >some of the answers: > >* >Why don't you just write one? :) >Seriously: Try. >* >Tools\scripts\reindent.py in your Python distribution. >* >Why, yes, there is: > http://lacusveris.com/PythonTidy/PythonTidy.python >* >tabnanny ? As the indentation *is* significant in python, none of the above can help if you lose the indentation. Try to reconstruct this: def foo(): if a>0: if b>0: print 1 print 2 else: return 3 return 4 The tools may help to make the indentation consistent (tabs/8 spaces/4 spaces/2 spaces mixed) or look better, but not to make it right. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tactics40 at gmail.com Mon Jan 22 17:53:01 2007 From: tactics40 at gmail.com (tac-tics) Date: 22 Jan 2007 14:53:01 -0800 Subject: arrow keys don't work Message-ID: <1169506381.452422.179070@11g2000cwr.googlegroups.com> I've noticed that in Python 2.5, the interactive prompt does not support intelligent use of arrow keys like 2.4 did (up/down for previous/next statement, left/right for moving the cursor). What exactly is the reason for this and is there an easier fix than downgradinig to 2.4? Thanks. From steve at holdenweb.com Wed Jan 24 10:19:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Jan 2007 15:19:41 +0000 Subject: Email attachments Message-ID: I'm having some trouble getting attachments right for all recipients, and it seems like Apple's mail.app is the pickiest client at the moment. It doesn't handle attachments that both Thunderbird and Outlook find perfectly acceptable. Since the code I'm using is currently ugly and embedded, before I trim it down for posting could anyone who's successfully generated emails with attachments received by mail.app let me know if they had any problems along the way? Google hasn't given me much on this, but I'm not feeling very creative today. Note that this is an important application: it sends out the invoices for PyCon sponsorship! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From researchbase at gmail.com Sat Jan 20 11:12:14 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sat, 20 Jan 2007 21:42:14 +0530 Subject: confused on python rpc with apache, is it possible? In-Reply-To: <1169276359.477277.17930@q2g2000cwa.googlegroups.com> References: <51ce8uF1k0tl5U1@mid.uni-berlin.de> <1169276359.477277.17930@q2g2000cwa.googlegroups.com> Message-ID: > Use mod_python with some xmlrpc handler. There is more than one around. > Google for them. That way you can keep Apache for both Python and PHP. > I am confused. I have some documents on xml-rpc but none of them mentioned apache. Krishnakant. From harlinseritt at yahoo.com Mon Jan 8 12:41:54 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 8 Jan 2007 09:41:54 -0800 Subject: where is python on linux? In-Reply-To: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> Message-ID: <1168278114.501189.104450@38g2000cwa.googlegroups.com> Hi Frank, Usually "Python" is installed in /usr/lib/python[VER] but you should be able to call up /usr/bin/python without any difficulty. Harlin Seritt Frank Potter wrote: > I installed fedora core 6 and it has python installed. > But the question is, where is the executable python file? > I can't find it so I come here for help. > I want to config pydev for eclipse and I need to know where the > ececutable python file is. > Thank you! From ms at cerenity.org Wed Jan 31 19:37:49 2007 From: ms at cerenity.org (Michael) Date: Thu, 01 Feb 2007 00:37:49 +0000 Subject: from future module!!!!!!! References: <1169983511.674847.281290@s48g2000cws.googlegroups.com> Message-ID: <45c135cd$0$8734$ed2619ec@ptn-nntp-reader02.plus.net> Stargaming wrote: > The 'from' clause is a keyword in python used for > imports in the module namespace. Typically, but in the case of "from __future__ ..." it actually changes the logic of the interpreter/compiler. As a result if you intend to use any features from __future__ you have to ensure that that directive comes first. It looks like any other module on the surface, but it's a little special. (This also means that if you intend to use any modules that use these features you need to import it in your top level code as well) Michael. From brochu121 at gmail.com Wed Jan 17 14:18:40 2007 From: brochu121 at gmail.com (David Brochu) Date: Wed, 17 Jan 2007 14:18:40 -0500 Subject: Python-list Digest, Vol 40, Issue 215 In-Reply-To: References: Message-ID: <9583ed900701171118i59b3aa61r531a6e0828cf47db@mail.gmail.com> How is it that when I try to send out a valid response to help someone with their python issue I get flagged, but this guy can send out something totally useless to the python community? > > > > > ---------- Forwarded message ---------- > From: david.bostwick at chemistry.gatech.edu (David Bostwick) > To: python-list at python.org > Date: Wed, 17 Jan 2007 18:42:35 GMT > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willing to accept an Orwellian doublespeak and enslavement world ? > In article <1169058752.659674.6680 at s34g2000cwa.googlegroups.com>, "Robert > Hicks" wrote: > >Please, none of the real facts points to anything else except what > >actually happened. Two planes hit two towers and they came down. > > > > You're talking to the wind. This is a conspiracy precisely because people > deny the crackpots. Denial of their "evidence" proves that there is a > coverup. Logic is not involved, only belief that doesn't respond to > dissenting evidence. > > > > > ---------- Forwarded message ---------- > From: "Carroll, Barry" > To: , > Date: Wed, 17 Jan 2007 10:50:20 -0800 > Subject: RE: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > > -----Original Message----- > > From: st911 at rock.com [mailto:st911 at rock.com] > > Sent: Wednesday, January 17, 2007 10:23 AM > > To: python-list at python.org > > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > > willingto accept an Orwellian doublespeak and enslavement world ? > > > > > > > ... buildings collapse all the time when you design to the > cold-formed > > > strength rather than the hot-formed strength of a material, then > heat > > > the material removing its tempered strength (which for steel occurs > at > > > much lower than usual flame temeratures). > > > > Actually, modern steel frame buildings have never collapsed from > > kerosine fire. > > Besides there are SERIOUS anomalies indicative of thermate and > > explosives. > > Yellow hot molten metal were seen trickling down less than hour after > > the fires. > > Red hot molten metal pools were seen in the rubble weeks after the > > collapse. > > The building and their contents pulverized to dust from the brisance > of > > very well > > planted and hidden explosives. I was not aware that Alqaeda has > > invisible man > > technology past the security cameras. > > > > > And what did this rant have to do with any of the sci.* or > programming > > > newsgroups you posted it to? > > > > Your ignoramus is the exact reason why this has to be posted there. > > > > > David A. Smith > > > > And why did bldg 7 commit suicide. How was the boeing767 maneouvered > > so close to the ground into pentagon? > > > > Where is the DNA to confirm the identities of 19 in the fairy tale? > > > > Do you work for the story writing agency ? > > > Ladies and Gentlemen: > > PLEASE take this discussion to a more appropriate forum. There are many > > forums where people will be happy to debate this: physics, firefighting, > metallurgy, geopolitics, etc. This forum is about the Python > programming language. Let's keep it that way. > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning cathedrals. > > -Quarry worker's creed > > > > > > > ---------- Forwarded message ---------- > From: "Carroll, Barry" > To: "Robert Hicks" , > Date: Wed, 17 Jan 2007 10:53:06 -0800 > Subject: RE: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > -----Original Message----- > > From: Robert Hicks [mailto:sigzero at gmail.com] > > Sent: Wednesday, January 17, 2007 10:33 AM > > To: python-list at python.org > > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > > willingto accept an Orwellian doublespeak and enslavement world ? > > > > Please, none of the real facts points to anything else except what > > actually happened. Two planes hit two towers and they came down. > > > Ladies and Gentlemen: > > PLEASE take this discussion to a more appropriate forum. There are many > > forums where people will be happy to debate this: physics, firefighting, > metallurgy, geopolitics, etc. This forum is about the Python > programming language. Let's keep it that way. > > Regards, > > Barry > barry.carroll at psc.com > 541-302-1107 > ________________________ > We who cut mere stones must always be envisioning cathedrals. > > -Quarry worker's creed > > > > > > > ---------- Forwarded message ---------- > From: "Robert Hicks" > To: python-list at python.org > Date: 17 Jan 2007 10:54:54 -0800 > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > > > > Regards, > > > > Barry > > barry.carroll at psc.com > > 541-302-1107 > > ________________________ > > We who cut mere stones must always be envisioning cathedrals. > > > > -Quarry worker's creed > > Sure, but did you actually post your phone number on USENET? > > Robert > > > > > > ---------- Forwarded message ---------- > From: "Emin" > To: python-list at python.org > Date: 17 Jan 2007 11:02:51 -0800 > Subject: Re: question about module resolution > I put the lines you suggested in baz.py, but got an error: > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import baz > Traceback (most recent call last): > File "", line 1, in > File "baz.py", line 3, in > from .. import config > ValueError: Attempted relative import in non-package > > On Jan 17, 11:20 am, Peter Otten <__pete... at web.de> wrote: > > Emin wrote: > > > I often find myself wanting to have a child module get some parameters > > > defined in a parent module. For example, imagine I have the following > > > directory structure and want something in baz.py to look at a value in > > > config.py. I end up putting in things like import sys; > > > sys.path.append('../..'). Is there a better way? > > > > > foo/ > > > __init__.py > > > config.py > > > bar/ > > > __init__.py > > > baz.pyfrom __future__ import absolute_import > > from .. import config > > > > Peter > > > > > > ---------- Forwarded message ---------- > From: "awel" > To: python-list at python.org > Date: 17 Jan 2007 11:03:15 -0800 > Subject: Re: Check a windows service > Thanks for all 'cause you've really helped me > > Just one thing in the last line for the specific service, you' ve > writted : > > > print service > > but I think it is : > > > print service.Caption > > > Tim Golden a ?crit : > > awel wrote: > > > Sorry, but could you give me an example with a real service 'cause > I've > > > tried this script but nothings happened, no error, nothings ; even if > I > > > launch it in cmd prompt. > > > > Well, as that example said, it was designed to show > > automatic services which are not running. If you don't > > have any then nothing will show. I assumed you could > > use this as a starting point. > > > > To list all services try this: > > > > > > import wmi > > > > c = wmi.WMI () > > for service in c.Win32_Service (): > > print service.Caption > > > > > > > > To show a specific service: > > > > > > import wmi > > > > c = wmi.WMI () > > for service in c.Win32_Service (Caption="Task Scheduler"): > > print service > > > > > > > > TJG > > > > > > ---------- Forwarded message ---------- > From: st911 at rock.com > To: python-list at python.org > Date: 17 Jan 2007 11:05:08 -0800 > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willing to accept an Orwellian doublespeak and enslavement world ? > > Robert Hicks wrote: > > Please, none of the real facts points to anything else except what > > actually happened. Two planes hit two towers and they came down. > > The issue is the causality of the towers coming down. > > A magician pulls appears to cast a spell > and out comes a rabbit out of his hat. There will always be fools who > will accept this causality and others who know better the laws of > conservation. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Thu Jan 4 05:22:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Jan 2007 11:22:19 +0100 Subject: array of class In-Reply-To: <1167782733.743870.228760@k21g2000cwa.googlegroups.com> References: <459ad4f7$0$293$426a34cc@news.free.fr> <1167777053.152492.3460@v33g2000cwv.googlegroups.com> <459ae31f$0$294$426a74cc@news.free.fr> <1167782733.743870.228760@k21g2000cwa.googlegroups.com> Message-ID: <459ccf34$0$308$426a74cc@news.free.fr> Podi a ?crit : >>>Or more compactly: >>> >>>words = [Word(w) for w in 'this is probably what you want'.split()] >>>print words >> >>I didn't want to introduce yet some more "confusing" stuff !-) > > > Indeed, the for loop is perfectly fine and totally readable. Let's save > the "confusing stuff" to the Perl folks. > This is not what I meant. I do like list comprehensions and use them a lot - and I don't find anything "perlish" here. From klappnase at web.de Tue Jan 16 05:03:46 2007 From: klappnase at web.de (klappnase) Date: 16 Jan 2007 02:03:46 -0800 Subject: Segfault with tktreectrl on python-2.5 on linux References: <1168884154.116074.308720@s34g2000cwa.googlegroups.com> Message-ID: <1168941826.062298.229080@51g2000cwl.googlegroups.com> Anton Hartl schrieb: > > Solutions: > > a) convince Python developers to prefix ALL new (wrt. 2.5) > global symbols with a prefix like "_PyAST_" or equivalent; > this would be consistent with how it is done anyway, > unfortunately the new AST symbols deviate from this practise > (there are symbols like "Assert", "If", "Then", ...) > > or b) apply an equivalent rule to the global symbols in > tktreectrl that are global by accident, i.e. because > of the way the library is structured and built > Anton, you're cool, actually renaming Ellipsis to Py_Ast_Ellipsis in ast.c and Python-ast.c seems to fix this. What I don't understand, isn't it very likely that such things will happen when names like "Ellipsis" or "Slice" and "Index" (which I also found in Python-ast.c) are being used, or are the treectrl people doing something they should avoid? I think the answer to this might be important when deciding to whom I should send a bug report :) Thanks and best regards Michael From gagsl-py at yahoo.com.ar Sun Jan 7 14:53:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 11:53:13 -0800 Subject: Traceback of hanged process In-Reply-To: References: Message-ID: <1168199593.403835.147360@s34g2000cwa.googlegroups.com> On 6 ene, 19:45, Hynek Hanke wrote: > please, how do I create a pythonic traceback from a python process that > hangs and is not running in an interpreter that I executed manually > or it is but doesn't react on CTRL-C etc? I'm trying to debug a server > implemented in Python, so I need some analog of 'gdb attach' for C. On Windows, Pythonwin has an option "Break into running code". Try starting the script with python -i, and send it a signal.. -- Gabriel Genellina From oliver at obeattie.com Fri Jan 5 07:14:55 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 5 Jan 2007 04:14:55 -0800 Subject: Encoding / decoding strings Message-ID: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> Hey Everyone, Was just wondering if anyone here could help me. I want to encode (and subsequently decode) email addresses to use in URLs. I believe that this can be done using MD5. I can find documentation for encoding the strings, but not decoding them. What should I do to encode =and= decode strings with MD5? Many Thanks in Advance, Oliver Beattie From greg at cosc.canterbury.ac.nz Sat Jan 27 03:31:20 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 27 Jan 2007 21:31:20 +1300 Subject: ANN: Pyrex 0.9.5 Message-ID: Pyrex 0.9.5 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Warning Elimination Extensive changes have been made in this version in an effort to eliminate most of the C compiler warnings that used to occur when compiling with distutils. There are also numerous other enhancements and bug fixes. See the CHANGES file in the distribution or on the web site for a full list. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From deets at nospam.web.de Fri Jan 12 09:40:44 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Jan 2007 15:40:44 +0100 Subject: What about this? References: <1168525050.536736.74590@i39g2000hsf.googlegroups.com> <50n9kcF1g30l4U2@mid.individual.net> <1168612073.635206.84620@s34g2000cwa.googlegroups.com> Message-ID: <50pkvcF1gecd0U1@mid.uni-berlin.de> Dr. Who wrote: > What's more amazing is that anyone would click on the link at all given > the increasing number of website that provide hidden content that tries > to deliver spyware or viruses just by getting visitors. Me LinuxBoy, me not in danger... SCNR :) Diez From http Sat Jan 13 02:37:20 2007 From: http (Paul Rubin) Date: 12 Jan 2007 23:37:20 -0800 Subject: MP3 decoder module? References: <7x4pqvste8.fsf@ruckus.brouhaha.com> Message-ID: <7x4pqv1iof.fsf@ruckus.brouhaha.com> Terry Carroll writes: > As I read the Pymedia docs, you can use it to decode frames from an > MP3, and operate on the decoded sound data. > > See http://pymedia.org/tut/dump_wav.html for a discussion. Hmm, thanks, it looks like there's more there than I thought at first, tough still pretty confusing. I'll look at it some more. Meanwhile I'm just doing a semi-manual kludge, looking at a file visually with audacity to figure out the chop point, then chopping all similar files (I have a bunch of sets of files that are related to each other and use the same chop points) with file.truncate. This is extremely fast but seems to sometimes cut an mp3 frame in the middle. So I'd like to figure out more accurately where the exact frame boundaries are. Chopping in the middle gets a harmless error message from the mpg123 software decoder but might have some worse effect with a hardware decoder. I have some cheap portable players that I can try it on but I haven't done that yet. I'm surprised there's not more code like this around. From tjreedy at udel.edu Wed Jan 10 13:21:00 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Jan 2007 13:21:00 -0500 Subject: Announcement -- ZestyParser References: <1168407920.281020.147680@k58g2000hse.googlegroups.com> Message-ID: "Adam Atlas" wrote in message news:1168407920.281020.147680 at k58g2000hse.googlegroups.com... | This has been on Cheese Shop for a few weeks now, being updated now and | then, but I never really announced it. I just now put up a real web | page for it, so I thought I'd take the opportunity to mention it here. | | ZestyParser is my attempt at a flexible toolkit for creating concise, | precise, and Pythonic parsers. None of the existing packages really met | my needs; Pyparsing came the closest, but I find it still has some | shortcomings. ZestyParser is simply an abstract implementation of how I | think about parsing; I don't expect it'll meet everyone's parsing | needs, but I hope it'll make typical parsing tasks more joyful. | | Here's the web page: | http://adamatlas.org/2006/12/ZestyParser/ | Here's the Cheese Shop page: | http://cheeseshop.python.org/pypi/ZestyParser | (I recommend you get the source package, as it includes the examples.) I would like to look at the examples online (along with the doc file) before downloading this and setuptools and installing, so I can see what it actually looks like in use. tjr From usenet at marlowa.plus.com Wed Jan 17 11:35:45 2007 From: usenet at marlowa.plus.com (Andrew Marlow) Date: Wed, 17 Jan 2007 17:35:45 +0100 (CET) Subject: cannot import libxml2 python module on windoze using activePerl or Python IDLE Message-ID: guys, I have been using libxml2 with python with no problems for just over a week but now I come to see if my script will work in someone else's environment and the libxml2 import fails. I am using the python that comes with cygwin. When I try using ActivePython (2.3) or Python IDLE (2.5) there does not seem to be a libxml2 module there. I thought libxml2 was a std python module. But it would seem not. I need help tracking it down please. I am using windoze XP (not my choice). I am not sure how python packages get installed on windoze. I can't find a file libxml2.py for activePython etc so I cannot even begin an install. I presume python's libxml builds on the C libs libxml2.dll and iconv.dll so I have installed those into the python DLL directory. I think this will be needed at some point. Please can anyone help? Regards, Andrew Marlow -- There is an emerald here the size of a plover's egg! Don't top-post http://www.catb.org/~esr/jargon/html/T/top-post.html Plain text mails only, please http://www.expita.com/nomime.html From citronelu at yahoo.com Mon Jan 8 16:01:30 2007 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 8 Jan 2007 13:01:30 -0800 Subject: Fwd: Execute binary code In-Reply-To: References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168289145.319706.199950@11g2000cwr.googlegroups.com> <4866bea60701081251we2bf7f3vb55a285ee20e91f6@mail.gmail.com> Message-ID: <1168290090.137259.324360@i15g2000cwa.googlegroups.com> Chris Mellon wrote: > Writing to a temp file will be at least 3 times as easy and twice as > reliable as any other method you come up with. I'm not disputing that, but I want to keep a piece of code (a parser for Oracle binary dumps, that I didn't wrote) out of foreign hands, as much as possible. Using a TEMP directory is not "stealth" enough. From exarkun at divmod.com Wed Jan 31 22:21:00 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Jan 2007 22:21:00 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: Message-ID: <20070201032100.25807.1381560506.divmod.quotient.5451@ohm> On 31 Jan 2007 19:12:59 -0800, Aahz wrote: >In article , >Jean-Paul Calderone wrote: >> >>You misunderstand. I wasn't expressing a lack of confidence in Python >>threads, but in the facility with which they can be used by programmers. > >Based on my admittedly limited experience, I say the same about Twisted. >Although I was able to bring up a Twisted 1.1 web server in a hurry under >extreme pressure (15 minutes before a PyCon presentation), I have never >been able to even get Twisted 2.0 installed. FWIW, this is probably even easier than when you last tried it: exarkun at kunai:~$ twistd -n web --port 8080 --path /tmp 2007-01-31 22:19:34-0500 [-] Log opened. 2007-01-31 22:19:34-0500 [-] twistd 2.5.0+r19505 (/usr/bin/python 2.4.3) starting up 2007-01-31 22:19:34-0500 [-] reactor class: 2007-01-31 22:19:34-0500 [-] twisted.web.server.Site starting on 8080 2007-01-31 22:19:34-0500 [-] Starting factory >Software is hard. But I absolutely agree with this point, anyway :) Software is _crazy_ hard. I merely dispute the claim that threads are somehow _easier_. :) Jean-Paul From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jan 10 17:59:01 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 10 Jan 2007 23:59:01 +0100 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> Message-ID: <50l9dlF1fuc1sU1@mid.individual.net> Sean Davis wrote: > The author of one of the python database clients mentioned that > using one thread to retrieve the data from the oracle database and > another to insert the data into postgresql with something like a > pipe between the two threads might make sense, keeping both IO > streams busy. IMHO he's wrong. Network interaction is quite slow compared with CPU performance, so there's no gain (maybe even overhead due to thread management and locking stuff). That's true even on multiprocessor machines, not only because there's almost nothing to compute but only IO traffic. CMIIW. Using multiplexing, you'll get good results with simple code without the danger of deadlocks. Have a look at asyncore (standard library) or the Twisted framework -- personally, I prefer the latter. Regards, Bj?rn -- BOFH excuse #194: We only support a 1200 bps connection. From pavlovevidence at gmail.com Fri Jan 5 20:45:11 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 5 Jan 2007 17:45:11 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1168041915.558354.110570@s80g2000cwa.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1167974907.497878.61070@i15g2000cwa.googlegroups.com> <1168041915.558354.110570@s80g2000cwa.googlegroups.com> Message-ID: <1168047910.987397.13860@s34g2000cwa.googlegroups.com> Fuzzyman wrote: > Carl Banks wrote: > > jeremito wrote: > > > I am writing a class that is intended to be subclassed. What is the > > > proper way to indicate that a sub class must override a method? > > > > You can't (easily). > > > > Well... > > How about not defining it on the base class, but check in the > constructor that the attribute exists and that it is of type > FunctionType ? That still delays the check until the object is created. You'd have to use metaclass programming to check this during class creation time. Carl Banks From cjw at sympatico.ca Wed Jan 31 10:32:29 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 31 Jan 2007 10:32:29 -0500 Subject: Conditional expressions - PEP 308 In-Reply-To: <1170228929.612844.153730@p10g2000cwp.googlegroups.com> References: <1170228929.612844.153730@p10g2000cwp.googlegroups.com> Message-ID: Paddy wrote: > On Jan 30, 9:51 pm, "Colin J. Williams" wrote: >> It would be helpful if the rules of the game were spelled out more clearly. >> >> The conditional expression is defined as X if C else Y. >> We don't know the precedence of the "if" operator. From the little test >> below, it seem to have a lower precedence than "or". >> >> Thus, it is desirable for the user to put the conditional expression in >> parentheses. >> >> Colin W. >> >> # condExpr.py >> # PEP 308 defines a conditional expression as X if C else Y >> # but we don't know exactly what X is supposed to be. >> # It doesn't seem to be spelled out in the syntax. >> >> def main(): >> names= ['abc', 'def', '_ghi', 'jkl', '_mno', 'pqrs'] >> res= '' >> for w in names: >> res= res + w if w[0] != '_' else '' >> z= 1 >> print 'res1:', res >> >> res= '' >> for w in names: >> res= res + (w if w[0] != '_' else '') >> z= 1 >> print 'res2:', res >> >> if __name__ == '__main__': >> main() >> >> Result: >> [Dbg]>>> >> res1: pqrs >> res2: abcdefjklpqrs > > But to give them credit though, in Whats new in Python 2.5: PEP 308, > they do mention that as a matter of style you should parenthesise the > if-expression, and the example given consistes of just a simple > assignment of the if-expr to a name. > - Paddy. > Yes, I agree. The ternary operator is a step forward. I was trying to make the point that the parentheses are necessary if X is more than a simple value. It's a pity that one finds this out by experiment rather than definition. Colin W. From mensanator at aol.com Sun Jan 21 16:38:34 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 21 Jan 2007 13:38:34 -0800 Subject: Python Windows Editors In-Reply-To: References: Message-ID: <1169415514.562496.248950@a75g2000cwd.googlegroups.com> W. Watson wrote: > I downloaded python-2.5.msi and installed it. I believe its editor is IDE. I > understand there's a Win editor called pythonwin. I believe it's in the > download pywin32-210.win32-py2.5.exe, but I'm not sure if this exe file has > just the editor or all of Python. Comments? If not how do I get the > PythonWin editor by itself? > > BTW, one of the features I did not like of IDE is the limited file Print > command. It puts everything in 16pt type, and gives no choice over what > pages should be printed. Maybe there's an option? Print your files from Notepad, after all, they're just text files. But IDLE has more usefull Formatting options. > > Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > Two laws Newton and Einstein didn't discover: > 1. Time is money. > 2. Matter will be damaged in direct proportion > to its value. > -- > Web Page: From bignose+hates-spam at benfinney.id.au Wed Jan 31 18:34:40 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 01 Feb 2007 10:34:40 +1100 Subject: Sorting a dict (was: How to sort using hash's key?) References: <1170276870.45c102069d9e6@webmail.3web.com> Message-ID: <87d54uvkhb.fsf@benfinney.id.au> JoJo writes: > I want to sort a dict via its key,but I have no idea on how to do > it. The 'dict' type is explicitly unordered. Sorting it isn't possible. (Also note that a 'hash' is something entirely different in Python.) You can create your own type, inheriting from 'dict', that has the behaviour you want. See the Python Cookbook for some examples. -- \ "I cannot conceive that anybody will require multiplications at | `\ the rate of 40,000 or even 4,000 per hour ..." -- F. H. Wales, | _o__) 1936 | Ben Finney From tiedon_jano at hotmail.com Tue Jan 16 13:06:51 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 16 Jan 2007 18:06:51 GMT Subject: A note on heapq module In-Reply-To: <1168970329.751502.57320@11g2000cwr.googlegroups.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <1168970329.751502.57320@11g2000cwr.googlegroups.com> Message-ID: <%u8rh.227$%i7.3@read3.inet.fi> bearophileHUGS at lycos.com kirjoitti: > I think the sort has to be simplified, otherwise it can't keep the heap > invariant... > > def sort(self): > self.h.sort() > > Bye, > bearophile > And __repr__ should be something like this: ========= def __repr__(self): if self.h: return "Heap(%s)" % self.h else: return "Heap()" ========== to make it compatible with versions earlier than 2.5 Cheers, Jussi From nszabolcs at gmail.com Tue Jan 30 18:54:34 2007 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 30 Jan 2007 15:54:34 -0800 Subject: data design In-Reply-To: <45bfbcc3$0$30950$426a74cc@news.free.fr> References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> <45bfbcc3$0$30950$426a74cc@news.free.fr> Message-ID: <1170201274.580256.182740@v45g2000cwv.googlegroups.com> > Hurray for yaml! A perfect fit for my need! And a swell tool! > Thanks a lot! i warn you against yaml it looks nice, but the underlying format is imho too complex (just look at their spec.) you said you don't want python source because that's too complex for the users. i must say that yaml is not easier to use than python data structures. if you want userfriedly config files then ConfigParser is the way to go. if you want somthing really simple and fast then i'd recommend s- expressions of lisp also here is an identation based xml-like tree/hierarchical data structure syntax: http://www.scottsweeney.com/projects/slip/ From universal_used at hotmail.com Mon Jan 22 15:03:58 2007 From: universal_used at hotmail.com (questions?) Date: 22 Jan 2007 12:03:58 -0800 Subject: Are there sprintf in Python??? Message-ID: <1169496238.925052.311660@l53g2000cwa.googlegroups.com> Are there any sprintf in Python? I know you can print to files(or redefine sys.stout) and later open the file content. Are there similar function to sprintf in C? Thanks From emin.shopper at gmail.com Thu Jan 11 14:12:30 2007 From: emin.shopper at gmail.com (Emin) Date: 11 Jan 2007 11:12:30 -0800 Subject: what is the idiom for copy lots of params into self? In-Reply-To: References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> <1168520386.457345.23680@i39g2000hsf.googlegroups.com> Message-ID: <1168542749.703729.308740@o58g2000hsb.googlegroups.com> Thanks, that looks like what I wanted. On Jan 11, 8:36 am, "Fredrik Lundh" wrote: > "Emin" wrote: > > What made me ask the question in my original post was not so much that > > I had to loop over the names I wanted to save, but whether it's okay to > > mess with self.__dict__ or if there is another way I should be > > assigning to self. http://effbot.org/pyref/setattr > > From mattheww at chiark.greenend.org.uk Thu Jan 25 13:08:34 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 25 Jan 2007 18:08:34 +0000 (GMT) Subject: Thoughts on using isinstance References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> <45b7b73b$0$391$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Matthew Woodcraft a ?crit : >> Adding the validation code can make your code more readable, in that >> it can be clearer to the readers what kind of values are being >> handled. > This is better expressed in the docstring. And if it's in the > docstring, you can't be blamed for misuse. I certainly agree that the description of the function's requirements on its parameters is best placed in the docstring. This is another place where the "don't validate, just try running the code anyway" approach can cause problems: what should you put in the docstring? I don't think anyone would like to be fully explicit about the requirements: you'd end up having to write things like "A string, or at least anything that's iterable and hashable and whose elements are single character strings, or at least objects which have an upper() method which ...". So in practice you end up writing "a string", and leave the rest of the 'contract' implicit. But that can lead to difficulties if people working on the code have different ideas of what that implicit contract is -- is it "a string, or anything else which works with the current implementation", or perhaps "you may pass something other than a string so long as you take responsibility for making it support all the necessary operations, even if the implementation changes", or is there some project-wide convention about how much like a string such things have to be? I think this kind of vagueness can work well within a lump of code which is maintained as a piece, but it's good to divide up programs into components with more carefully documented interfaces. And it's at that level that I think doing explicit parameter validation can be helpful. >> If you validate, you can raise an exception from the start of your >> function with a fairly explicit message. If you don't validate, >> you're likely to end up with an exception whose message is something >> like 'iteration over non-sequence', and it might be raised from some >> function nested several levels deeper in. > And what is the stack backtrace for, actually ? I'm not sure that you intended that as a serious question, but I'll answer it anyway. In an ideal world, the stack backtrace is there to help me work with code that I'm maintaining. It isn't there to help me grub around in the source of someone else's code which is giving me an unhelpful error message. Just as, in an ideal world, I should be able to determine how to correctly use someone else's code by reading its documentation rather than its source. I think this is a 'quality of implementation' issue. When you start using Python you pretty rapidly pick up the idea that a message like 'len() of unsized object' from (say) a standard library function probably just means that you didn't pass the value you intended to; but that doesn't mean it's a good error message. These things do add up to make the daily business of programming less efficient. >> The latter can be harder for the user of your function to debug (in >> particular, it may not be easy to see that the problem was an invalid >> parameter to your function rather than a bug in your function itself, >> or corrupt data elsewhere in the system). > docstrings and unit-tests should make it clear. I don't see that either of those things remove the issues I described. > Now if one want to have to declare everything three times and write > layers and layers of adapters and wrappers, well, he knows where to > find Java !-) Right. But using Python there is a position between 'writing layers and layers of adapters and wrappers' and 'never validate anything': put explicit checks in particular functions where they're likely to do most good. For example, it's often helpful to explicitly validate if you're going to store the parameters away and do the actual work with them later on. Consider what happens if you pass garbage to urllib2.install_opener(): you'll get an obscure error message later on from a urlopen() call, which will be rather less convenient to investigate than an error from install_opener() would have been. >> This might well lead to your program apparently completing >> successfully but giving the wrong result (which is usually the kind >> of error you most want to avoid). > Compared to what C or C++ can do to your system, this is still a > pretty minor bug - and probably one of the most likely to be detected > very early I disagree. What C or C++ will do, very often, is produce a segmentation fault. That may well turn out to be hard to debug, but it's considerably more likely to be detected early than a successful exit status with incorrect output. -M- From shitizb at yahoo.com Tue Jan 23 10:10:46 2007 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue, 23 Jan 2007 07:10:46 -0800 (PST) Subject: IE Toolbar (OT) In-Reply-To: <1169563580.634000.122540@v45g2000cwv.googlegroups.com> Message-ID: <812508.48255.qm@web53807.mail.yahoo.com> Hi, I need to build a toolbar for internet explorer which will have an embedded paintbrush like application. The user should be able to draw on the drawing canvas of that application and submit to post his drawings on my server. I have built up a toolbar and a standalone paintbrush app in VC++. However I am unable to embed my application into the toolbar( I want it to show as a part of ie and not a separate window). I usually work with scripting languages liek python and ruby and am new to VC++. Please advise me on any literature/pointers to solve my problem. Thanks, Shitiz --------------------------------- Cheap Talk? Check out Yahoo! Messenger's low PC-to-Phone call rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Tue Jan 30 13:33:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 30 Jan 2007 19:33:26 +0100 Subject: Help me understand this References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> <1170146755.446429.90720@v45g2000cwv.googlegroups.com> Message-ID: On 2007-01-30, Gabriel Genellina wrote: > En Tue, 30 Jan 2007 06:34:01 -0300, Beej escribi?: > >> But here's one I still don't get: >> >>>>> type(2) >> >>>>> type((2)) >> >>>>> (2).__add__(1) >> 3 >>>>> 2.__add__(1) >> File "", line 1 >> 2.__add__(1) >> ^ >> SyntaxError: invalid syntax > > It appears to be a bug, either in the grammar implementation, or in the > grammar documentation. > These are the relevant rules: > > attributeref ::= primary "." identifier > > primary ::= atom | attributeref | subscription | slicing | call > > atom ::= identifier | literal | enclosure > > literal ::= stringliteral | integer | longinteger | floatnumber | > imagnumber > > An integer is a primary so 2.__add(1) should be valid. Not if the tokenizer passes the parser a float. -- Neil Cerutti From cliff at develix.com Wed Jan 24 14:37:58 2007 From: cliff at develix.com (Cliff Wells) Date: Wed, 24 Jan 2007 11:37:58 -0800 Subject: Type casting a base class to a derived one? In-Reply-To: <4866bea60701241057t13776d34ya516c2c24e7119bb@mail.gmail.com> References: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> <1169664145.4910.22.camel@portable-evil> <4866bea60701241057t13776d34ya516c2c24e7119bb@mail.gmail.com> Message-ID: <1169667478.4910.52.camel@portable-evil> On Wed, 2007-01-24 at 12:57 -0600, Chris Mellon wrote: > > In Python, you can do this simply by re-assigning the __class__. I'm > not convinced that your type system makes sense, here though. Any > reasonable ORM should be able to persist and reload an object without > losing the type information. Perhaps it's just a blind spot in the way > I think about types. Assuming that the limitations of your ORM are > external and out of your control, I would still ensure that whatever > generic objects are being loaded from the ORM are converted into > "real" objects of the correct type as soon as possible. For example, > if you're persisting a file, you might just save the filename, and > your ORM might return a string of the filename. I would want to > convert that back into a file object ASAP, rather than writing all my > code to accept either a FLO or a string and converting then. > > If you know what to upcast something to, then you know what type it > is. If you know what type it is, then (in Python) you can simply > assume it is of that type. Probably being more specific would help in this case ;-) What I'm doing is implementing an object-publishing mechanism in my template engine (Breve). The type decision isn't known until the moment of rendering (i.e. in the template itself). Say for instance a set of records is pulled from the ORM (SQLAlchemy in this case) and that these records represent articles in a blog. These records, until they hit the template, have no real representation in HTML. The decision about how to present them is up to the template. The dispatch mechanism I referred to earlier is a way that I allow users of the template system to register how a particular object should be rendered in HTML (a "flattener"). This allows commonly represented objects to be used without a lot of template clutter. However, if you consider the case of a blog, then if the template receives a list of articles, it would seem reasonable to present those articles in at least two ways: first as a table of contents in the page gutter, and then perhaps as two or three summaries in the main part of the page. But this isn't known to the lower layers of the application, only to the template. Therefore it would be nice if the template user could register two classes with the flattener, both representations of the original object but simply with a different type. I'll give a concrete example: class Person: # assume this is something from the ORM name = "Kenny" class PersonRow ( Person ): pass def flatten_person ( p ): return "omg, you've killed %p" % p.name def flatten_personrow ( p ): return "%s" % p.name register_flattener ( PersonRow, flatten_personrow ) register_flattener ( Person, flatten_person ) Now, assuming a list of Person records were passed in as 'persons', then in the template the template author could simply use: div [ # show the first person persons [ 0 ], # show a table of all persons table [ [ PersonRow ( p ) for p in persons ] ] ] > What you're describing is a disjoint between your actual type system > (that is, the one you have in code) and your theoretical type system > (the one that you model your code around). To me, this is a huge red > warning flag. What I'm describing is a disjoint between how I want my template engine to be used (I tend to build backwards, writing the desired template code and then the engine code to support that use) and what can be easily and efficiently achieved. But yes, in a way you are correct since my theoretical type system is constrained by Python's type system (Breve templates are Python expressions). That being said, I'm certain I'll come up with a solution that doesn't bug me too much, it's just that the "obvious" solution doesn't exist (type casting). > I'm arguing against the idea that it makes sense, in Python, to > upcast. I think it's definitely a corner-case, but I'd be reluctant to claim it would never be of use. > I agree, but without a use case it's hard to understand the limits and > needs of a requirement. So if you can't think of a need for a feature, > it becomes difficult to understand how you might implement that > feature. Certainly. Several years of using Python has never suggested a use to me prior to this. Regards, Cliff From bthom at cs.hmc.edu Fri Jan 12 15:40:42 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Fri, 12 Jan 2007 12:40:42 -0800 Subject: modules...n methods In-Reply-To: <50pst9F1h5hj5U1@mid.individual.net> References: <1168620496.520506.296330@q2g2000cwa.googlegroups.com> <50pst9F1h5hj5U1@mid.individual.net> Message-ID: <36367A62-197D-4EE0-9792-379A65D00C29@cs.hmc.edu> On Jan 12, 2007, at 8:56 AM, Bjoern Schliessmann wrote: > lee wrote: > >> whats the way to read the sourcecode of methods > > Easy. Look up the .py file and open it in an editor of your choice. > Those files are, for example, in "/usr/lib/python". > >> and built in functions? This becomes a lot easier if you use IPython (which embellishes the python shell in many useful ways). For instance, I did a "dir (__builtins__)" to find out what some of the builtin functions were. One was called "zip". Here's what I do in IPython to get help on that function: In [2]: zip?? Type: builtin_function_or_method Base Class: String Form: Namespace: Python builtin Docstring [source file open failed]: zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence. Note that IPython's prompt is (by default) different than pythons--- the "In[]:". Any identifier you have a question about will produce summary info via "?" and summary + source via "??". HTH --b From peterbe at gmail.com Fri Jan 5 10:59:57 2007 From: peterbe at gmail.com (peterbe at gmail.com) Date: 5 Jan 2007 07:59:57 -0800 Subject: elementtree.SimpleXMLWriter and xmlcharrefreplace Message-ID: <1168012797.140846.159160@q40g2000cwq.googlegroups.com> I'll try to explain my problem with code. The problem is the output msg = u"S?dert?lje & Bor?s" # latin1 unicode string with a & from elementtree.SimpleXMLWriter import XMLWriter from cStringIO import StringIO out = StringIO() w = XMLWriter(out) body = w.start("body") w.element("text", msg) w.close(body) return out.getvalue() Here's the output I get: Södertälje &amp; Borås Here's what I would want and expect: Södertälje & Borås Notice that & is converted to &amp; when it should be & or &38; only. From cvanarsdall at mvista.com Wed Jan 10 16:04:34 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 10 Jan 2007 13:04:34 -0800 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Message-ID: <45A554E2.9040809@mvista.com> Just as something to note, but many HPC applications will use a combination of both MPI and threading (OpenMP usually, as for the underlying thread implementation i don't have much to say). Its interesting to see on this message board this huge "anti-threading" mindset, but the HPC community seems to be happy using a little of both depending on their application and the topology of their parallel machine. Although if I was doing HPC applications, I probably would not choose to use Python but I would write things in C or FORTRAN. What I liked about python threads was that they were easy whereas using processes and IPC is a real pain in the butt sometimes. I don't necessarily think this module is the end-all solution to all of our problems but I do think that its a good thing and I will toy with it some in my spare time. I think that any effort to making python threading better is a good thing and I'm happy to see the community attempt to make improvements. It would also be cool if this would be open sourced and I'm not quite sure why its not. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From deets at nospam.web.de Sat Jan 6 06:48:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Jan 2007 12:48:38 +0100 Subject: PDF rendering toolkit? In-Reply-To: References: Message-ID: <509gkmF1eufvtU1@mid.uni-berlin.de> > I'm looking for a tool to take an actual .pdf file and display it in a > window (I'm using wxwidgets at the moment) No idea if there is a one-shot-kills-them-all solution out there - but if you have a way to go for windows, you might checkout PyQt and PyKDE to embed a kpfd-view in a window of yours. I agree that it is less than desirable to switch toolkits - but if you _have_ to... Diez From gert.cuykens at gmail.com Sun Jan 21 18:07:48 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Mon, 22 Jan 2007 00:07:48 +0100 Subject: instancemethod In-Reply-To: <1169418918.963891.196080@m58g2000cwm.googlegroups.com> References: <1169418918.963891.196080@m58g2000cwm.googlegroups.com> Message-ID: On 21 Jan 2007 14:35:19 -0800, Nanjundi wrote: > > > > if __name__ == '__main__': > > gert=Db('localhost','root','******','gert') > > gert.excecute('select * from person') > > for x in range(0,gert.rowcount): > > print gert.fetchone() > > gert.close() > > > > gert at gert:~$ python ./Desktop/svn/db/Py/db.py > > Traceback (most recent call last): > > File "./Desktop/svn/db/Py/db.py", line 35, in > > for x in range(0,gert.rowcount): > > TypeError: range() integer end argument expected, got instancemethod. > > gert at gert:~$ > > > > Can anybody explain what i must do in order to get integer instead of > > a instance ? > > Gert, > > for x in range(0,gert.rowcount): > gert.rowcount is the method (and not a data attribute). > gert.rowcount() is the method call, which get the return value from > method. > > So try this. > for x in range( 0,gert.rowcount() ): > Doh! :) thx From Thomas.Ploch at gmx.net Sun Jan 7 11:40:50 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 17:40:50 +0100 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: <45A12292.3060701@gmx.net> W. Watson schrieb: > As I understand it, there are two files I'm after: 1. python interpreter, > and 2. a python editor. It's #2 that I'm having trouble downloading. The > link is broken. This is the python interpreter for windows: http://www.python.org/ftp/python/2.5/python-2.5.msi Here you can check for editors: http://wiki.python.org/moin/PythonEditors Here you will get the pywin32 package (also including the Win32 API, COM support, and Pythonwin): http://sourceforge.net/projects/pywin32/ I am not sure if you actually read any of our posts, because there is no 404 whatsoever. On none of the posted links in the whole thread. Thomas From cjw at sympatico.ca Sun Jan 28 08:28:32 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 28 Jan 2007 08:28:32 -0500 Subject: IP address In-Reply-To: References: Message-ID: Klaus Alexander Seistrup wrote: > Scripter47 wrote: > >> How do i get my ip address? >> >> in cmd.exe i just type "ipconfig" then it prints: >> ... >> IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 >> ... >> how can i do that in python?? > > #v+ > > python -c 'import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' > > #v- > > Cheers, > Klaus, Your one-liner doesn't work for me, with Windows XP, but the following does, within Python. *** Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32. *** >>> import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0] 69.157.68.189 >>> Colin W. From s_david_rose at hotmail.com Thu Jan 25 20:52:40 2007 From: s_david_rose at hotmail.com (s. d. rose) Date: Thu, 25 Jan 2007 20:52:40 -0500 Subject: Help extracting info from HTML source .. Message-ID: Hello All. I am learning Python, and have never worked with HTML. However, I would like to write a simple script to audit my 100+ Netware servers via their web portal. I was reading Chapter 8 of Dive into Python, which deals with this topic. In the web portal of the server, there is a section similar to this: --> clients and clever services. <-- which I took from SlashDot, but what I'm talking about is using the word 'services' to represent the link to eugenia.blogsome.com. What I'd like to do is save the two pieces of info relative to the server name. Probably in a dictionary, such as server1[link] to the page on eugenia.blogsome.com and server1[description] to 'services'. I've used the example from Dive into Python to get the actual link in the source of the HTML, but I don't know how to get the text that is the hyperlink. So in the portal, I've got a link 'Scheduled Server Reboot' going to say /ScheduledTasks/ID000000003/ on Server1, using similar to above clipped HTML source code. Can someone please help me? Sure, I could manually go to each server, but I wouldn't learn anything. I've learned some, but also have real deadlines, so I eagerly hope for any assistance & instruction. Thank you! -Dave Shelton, CT From justask at acme.com Sun Jan 21 19:05:21 2007 From: justask at acme.com (Vincent Delporte) Date: Mon, 22 Jan 2007 01:05:21 +0100 Subject: Code reformater? References: Message-ID: On Sun, 21 Jan 2007 14:15:46 +1100, Steven D'Aprano wrote: >Still, it is better not to lose the indentation in the first place. Thanks for the tips. But it does happen when copy/pasting code from either a web page or an e-mail that TABs are messed up, which is not a problem with other languages, but is a problem with Python. Too bad. From rubbishemail at web.de Tue Jan 16 10:10:32 2007 From: rubbishemail at web.de (rubbishemail at web.de) Date: 16 Jan 2007 07:10:32 -0800 Subject: arguments of a function/metaclass Message-ID: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> Hello, I have a member function with many (20) named arguments def __init__(self,a=1,b=2): self.a=a self.b=b I would like to get rid of the many redundant lines like self.a=a and set the members automatically. The list of default arguments could be given like def __init__(**kwargs): arglist={"a":1,"b":2] if this makes things easier Of course there has to be a check that raises an error in case of an unknown argument not mentioned in this list. I am sure there is an elegant way how to do this, could you give me any hints??? Many thanks Daniel From pavlovevidence at gmail.com Thu Jan 4 12:09:14 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 4 Jan 2007 09:09:14 -0800 Subject: Why is pow a builtin, anyways? In-Reply-To: References: Message-ID: <1167930554.650336.208760@q40g2000cwq.googlegroups.com> siggi wrote: > Now the test for module math with function pow(): > --------------------------------------------------- > >>> pow(9,9) > 387420489 > > Fine, but sqrt() fails: > ------------------- > >>> sqrt(9) > I get this error message > > 'Traceback (most recent call last): > File "", line 1, in > sqrt(9) > NameError: name 'sqrt' is not defined' The third argument to the builtin pow is a special usage for cryptography, and something specific like that needs no representation in the builtin namespace. The ** operator covers all other uses. Carl Banks From gigs at hi.t-com.hr Tue Jan 9 06:59:31 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 09 Jan 2007 12:59:31 +0100 Subject: Bitwise expression In-Reply-To: References: Message-ID: Hendrik van Rooyen wrote: > "Gigs_" wrote: > > >> Can someone explain me bitwise expression? >> few examples for every expression will be nice >> >> x << y Left shift >> x >> y Right shift >> x & y Bitwise AND >> x | y Bitwise OR >> x ^ y Bitwise XOR (exclusive OR) >> ~x Bitwise negation > > The short, and possibly weird, but true, answer is: > > If you have to ask this question, you should avoid > using these things. - Think of them as "Advanced Magic" > > But this is unhelpful, so a slightly longer answer is: > > Computer memory is like a long string of flip-flops that can > take on one of two states - "on" or "True" represented normally by > a digit 1, and "off" or "False" - a digit 0. Hence the term binary. > > Binary means "two valued", just like a Bicycle has two wheels. > > These flip-flops are the smallest element of memory, and one > of them is called a "bit". The plural is "bits". "plural" means > "more than one of". > > Eight bits are called a Byte. > Half a Byte is a Nibble - four bits (sometimes spelt Nybble by > people who are trying to be cute). > There is a concept called a "Word" of memory which is ill defined. > Sometimes it is one or two Bytes, sometimes three nibbles, sometimes > four, eight or sixteen bytes - depends on the hardware's bus width. > > No, I am not going to explain what a bus is. > > You can think of a python number as a word of eight bytes long, > and a python string as a number of bytes of arbitrary length. > > I am also not going to explain big and little endian representation. > Yahoo for it. > > Now the logic operators, as applied to nibbles: > > 1110 << 0111 - shifted left, filled with zero from right > (multiply by two - seven to fourteen) > 0010 >> 0100 - shifted right, filled with zero from left > (divide by two - four to two) > 0100 = 0101 & 1110 - true if both bits true, false otherwise > (used for masking, clearing bits) > 1101 = 0101 | 1100 - false if both bits false, true otherwise > (True if either bit true - used to set > bits) > 1001 = 0101 ^ 1100 - true if only one of the bits true, else false > (anything xored with itself is all zero) > (used to toggle bits, identity testing) > 1001 ~ 0110 - inversion "not" - not true is false, not false > is true > > Also yahoo for "Boolean algebra" and "De Morgan" and "IEEE floating point > representation" > > hth - Hendrik > > hey I know about bit, bits things, just didn't know how to use bitwise expression (didn't try it and didn't know what it means). so I just needed some examples. Now is all clearer thanks to mensanator at aol.com and Hendrick van Rooyen From cvanarsdall at mvista.com Wed Jan 31 14:31:41 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 31 Jan 2007 11:31:41 -0800 Subject: Any python scripts to do parallel downloading? In-Reply-To: <1170271023.955808.314010@q2g2000cwa.googlegroups.com> References: <1170260637.679856.39920@k78g2000cwa.googlegroups.com> <1170271023.955808.314010@q2g2000cwa.googlegroups.com> Message-ID: <45C0EE9D.70301@mvista.com> Michele Simionato wrote: > On Jan 31, 5:23 pm, "Frank Potter" wrote: > >> I want to find a multithreaded downloading lib in python, >> can someone recommend one for me, please? >> Thanks~ >> > > Why do you want to use threads for that? Twisted is the > obvious solution for your problem, but you may use any > asynchronous framework, as for instance the good ol > Well, since it will be io based, why not use threads? They are easy to use and it would do the job just fine. Then leverage some other technology on top of that. You could go as far as using wget via os.system() in a thread, if the app is simple enough. def getSite(site): os.system('wget %s',site) threadList =[] for site in websiteList: threadList.append(threading.Thread( target=getSite,args=(site,))) for thread in threadList: thread.start() for thread in threadList: thread.join() > Tkinter: > > """ > Example of asynchronous programming with Tkinter. Download 10 times > the same URL. > """ > > import sys, urllib, itertools, Tkinter > > URL = 'http://docs.python.org/dev/lib/module-urllib.html' > > class Downloader(object): > chunk = 1024 > > def __init__(self, urls, frame): > self.urls = urls > self.downloads = [self.download(i) for i in range(len(urls))] > self.tkvars = [] > self.tklabels = [] > for url in urls: > var = Tkinter.StringVar(frame) > lbl = Tkinter.Label(frame, textvar=var) > lbl.pack() > self.tkvars.append(var) > self.tklabels.append(lbl) > frame.pack() > > def download(self, i): > src = urllib.urlopen(self.urls[i]) > size = int(src.info()['Content-Length']) > for block in itertools.count(): > chunk = src.read(self.chunk) > if not chunk: break > percent = block * self.chunk * 100/size > msg = '%s: downloaded %2d%% of %s K' % ( > self.urls[i], percent, size/1024) > self.tkvars[i].set(msg) > yield None > self.tkvars[i].set('Downloaded %s' % self.urls[i]) > > if __name__ == '__main__': > root = Tkinter.Tk() > frame = Tkinter.Frame(root) > downloader = Downloader([URL] * 10, frame) > def next(cycle): > try: > cycle.next().next() > except StopIteration: > pass > root.after(50, next, cycle) > root.after(0, next, itertools.cycle(downloader.downloads)) > root.mainloop() > > > Michele Simionato > > -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From steve at REMOVE.THIS.cybersource.com.au Fri Jan 12 19:22:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 13 Jan 2007 11:22:47 +1100 Subject: Rational Numbers References: Message-ID: On Fri, 12 Jan 2007 17:15:56 +0000, Nick Maclaren wrote: > In article , > Facundo Batista writes: > |> Noud Aldenhoven wrote: > |> > |> > There are a (small) couple of other issues where rational numbers could be > |> > handy. That's because rational numbers are exact, irrational numbers (in > |> > python) aren't. But these issues are probably too mathematical to be used in > |> > |> For the sake of me being less ignorant, could you please point me a > |> language where irrational numbers are exact? > > Some of the algebraic languages. (2/3)^(1/5) is held as such and > manipulated appropriately. > > Yes, I know that's "cheating" :-) I see your smiley, and I still don't understand. Why on earth would you call it cheating for a language to have a data type that is suitable for the data being used? Maybe it's a form of humour I don't get -- like pointing at a car and saying "Look, a cow!". -- Steven. From letezo at fw.hu Tue Jan 30 19:17:00 2007 From: letezo at fw.hu (=?ISO-8859-1?Q?L=E9tezo?=) Date: Wed, 31 Jan 2007 01:17:00 +0100 Subject: Sorting a List of Lists References: <1170201351.881776.257790@q2g2000cwa.googlegroups.com> Message-ID: <006401c744cd$20703f00$8600a8c0@ANNA> > events = [['Event URL as String', 'Event Title as String ', Event Date > as Datetime], ...] > > I then thought I'd just go events.sort(lambda x,y: x[2] it a day. That didn't work. But then lamda functions like to be very > simple, maybe object subscripts aren't allowed (even though I didn't > get an error). So I wrote a comparison function that looks much as you > would expect: Comparision functions must return -1, 0 or 1, not a bool. You may use a key function instead in this case (requires python 2.4 or newer): events.sort(key=lambda x: x[2]) Viktor From bruno.desthuilliers at websiteburo.com Tue Jan 23 03:26:00 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Tue, 23 Jan 2007 09:26:00 +0100 Subject: instancemethod In-Reply-To: References: <45b51298$0$8289$426a74cc@news.free.fr> Message-ID: <45b5c65e$0$23047$426a74cc@news.free.fr> Gert Cuykens a ?crit : > Reading all of the above this is the most simple i can come too. > > import MySQLdb > > class Db: > > def __init__(self,server,user,password,database): > self._db=MySQLdb.connect(server , user , password , database) > self._db.autocommit(True) > self.cursor=self._db.cursor() > > def excecute(self,cmd): Just out of curiousity: is there any reason you spell it "excecute" instead of "execute" ? > self.cursor.execute(cmd) > self.rowcount=int(self.cursor.rowcount) > > def close(self): > self.cursor.close() > self._db.close() > > def __del__(self): > try: > self.close() > except: > pass > if __name__ == '__main__': > gert=Db('localhost','root','******','gert') > gert.excecute('select * from person') > for row in gert.cursor: > print row > > This must be the most simple it can get right ? Using __getattr__ is still simpler. > PS i didn't understand the __getattr__ quit well but i thought it was > just to overload the privies class The __getattr__ method is called when an attribute lookup fails (and remember that in Python, methods are -callable- attributes). It's commonly used for delegation. From ljz at asfast.com Sat Jan 6 16:53:23 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Sat, 06 Jan 2007 16:53:23 -0500 Subject: Recommended way to force a thread context switch? References: <1168103258.602286.146100@42g2000cwt.googlegroups.com> <1168104008.910681.46800@38g2000cwa.googlegroups.com> Message-ID: <87odpblt4c.fsf@asfast.com> Duncan Booth writes: > Lloyd Zusman wrote: > >> I have a python (2.5) program with number of worker threads, and I want >> to make sure that each of these does a context switch at appropriate >> times, to avoid starvation. I know that I can do a time.sleep(0.001) to >> force such a switch, but I'm wondering if this is the recommended >> method. > > The recommended method is to start a new thread rather than following up on > an existing thread with an unrelated question. I accidentally hit "a" in my mailer instead of "w" ("reply" instead of "compose"). Geez. It was an accident. I'm sorry. > Why do you think that just letting the threads run won't have the effect > you desire? Leave it to the system to schedule the threads. I can already see that they don't have the effect I desire. They are long numerical calculations in tight loops. I have to periodically put explicit time.sleep(0.001) calls in place to force the context switching, and I was wondering if that's the recommended method. -- Lloyd Zusman ljz at asfast.com God bless you. From skip at pobox.com Sat Jan 6 19:51:57 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 6 Jan 2007 18:51:57 -0600 Subject: Why less emphasis on private data? In-Reply-To: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> Message-ID: <17824.17453.290049.177914@montanaro.dyndns.org> time> Coming from a C++ / C# background, the lack of emphasis on private time> data seems weird to me. Python doesn't try to protect you from the authors of the code you use. You should be intelligent enough to use it wisely. On the flip side, the lack of truly private data and methods means the original author of a piece of code doesn't need to anticipate all future uses to which the code will be put. Here are a couple items along the lines of "we're all adults here". http://spyced.blogspot.com/2005/06/anders-heljsberg-doesnt-grok-python.html http://www.mail-archive.com/tutor at python.org/msg17806.html Skip From deets at nospam.web.de Fri Jan 5 08:15:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Jan 2007 14:15:00 +0100 Subject: Encoding / decoding strings References: <1167999295.242042.79470@s34g2000cwa.googlegroups.com> Message-ID: <5071akF1ehiaqU1@mid.uni-berlin.de> oliver at obeattie.com wrote: > Hey Everyone, > > Was just wondering if anyone here could help me. I want to encode (and > subsequently decode) email addresses to use in URLs. I believe that > this can be done using MD5. Are you by chance after a way to create URLs that contain an email which the server then can extract from them, and this to be tamperproof? There are several ways to accomplish this - your MD5-suggestion is applyable when working with a simple secret and by creating an additional parameter. If you e.g. want an url like this to be secure http://some.server/path?user_to_register=email at address you use a secret, and hash the parameters together with the secret using MD5. The result is then something like http://some.server/path?user_to_register=email at address&key= Then in the server, you perform the same step as above, without the key of course, and simply check if the MD5-sums are equal. Anything else requires the use of a encryption algorithm like blowfish or whatnot, either symetric or public key - I'm not an expert on that though. Diez From nagle at animats.com Tue Jan 30 14:57:31 2007 From: nagle at animats.com (John Nagle) Date: Tue, 30 Jan 2007 19:57:31 GMT Subject: Executing Javascript, then reading value In-Reply-To: <1170105229.984079.219180@l53g2000cwa.googlegroups.com> References: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> <1170105229.984079.219180@l53g2000cwa.googlegroups.com> Message-ID: Melih Onvural wrote: > Thanks, let me check out this route, and then I'll post the results. > > Melih Onvural > > On Jan 29, 4:04 pm, Jean-Paul Calderone wrote: > >> On 29 Jan 2007 12:44:07 -0800, Melih Onvural >> wrote: >> >> >>> I need to execute some javascript and then read the value as part of a >>> program that I am writing. I am currently doing something like >>> this:Python doesn't include a JavaScript runtime. You might look into >>> the >> >> stand-alone Spidermonkey runtime. However, it lacks the DOM APIs, so it >> may not be able to run the JavaScript you are interested in running. There >> are a couple other JavaScript runtimes available, at least. If >> Spidermonkey is not suitable, you might look into one of them. This is getting to be a common problem. One used to be able to look at web pages from a program by reading the HTML. Now you need to load the page into a browser-like environment, run at least the OnLoad JavaScript, and then start looking at the document object module. This requires a browser emulator, a browser without a renderer. Useful for spam filters and such. It's not clear if the original poster needs that much capability, though. John Nagle From deets at nospam.web.de Fri Jan 5 03:42:19 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Jan 2007 09:42:19 +0100 Subject: Problem installing MySQLdb/1.2.1_p2 with Python/2.4.1 and MySQL/5.0.18 In-Reply-To: <459e0752$0$17009$4c368faf@roadrunner.com> References: <459e0752$0$17009$4c368faf@roadrunner.com> Message-ID: <506hbbF1eqkd8U1@mid.uni-berlin.de> Sean O'Donnell schrieb: > Hi, > > I can't seem to get MySQLdb/1.2.1p2 to install on Slackware/10.2, with > Python/2.4.1, and MySQL/5.0.18. > > The following command: > > $ python setup.py build 2> setup.err > > returns the following errors: > > http://pastebin.com/851624 > > Any suggestions? Install the mysql developer package that contains the needed includefiles. Diez From fredrik at pythonware.com Fri Jan 5 04:57:12 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Jan 2007 10:57:12 +0100 Subject: checking one's type In-Reply-To: References: Message-ID: belinda thom wrote: > I've been using the following hack to determine if a type is > acceptable and I suspect there is a better way to do it: > > e.g. > > if type(s) == type("") : > print "okay, i'm happy you're a string" > > If anyone knows a better way, I'm all ears. http://preview.tinyurl.com/yjnoc5 From martin at v.loewis.de Wed Jan 10 01:50:15 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 10 Jan 2007 07:50:15 +0100 Subject: dynamic library loading, missing symbols In-Reply-To: <1168388748.024090.119530@i39g2000hsf.googlegroups.com> References: <1168388748.024090.119530@i39g2000hsf.googlegroups.com> Message-ID: <45A48CA7.3080005@v.loewis.de> dfj225 at gmail.com schrieb: > However, the linker fails at runtime here because it can't > find this symbol. The variable in question does exist in the C++ code > that in does dlopen. Did you verify, using nm -D, that the symbol is indeed present in the shared object, not just in the source code? > The reason for the complication is that I don't have control over how > the library does dlopen() or how the code that calls dlopen was > compiled. What flags are given to that dlopen call? > Is there a way to set at runtime what directories or libraries the > linker should search for these symbols? No. The dynamic linker doesn't search files to resolve symbols; instead, it searches the process' memory. It first loads the referenced shared libraries (processing the DT_NEEDED records in each one); that uses the LD_LIBRARY_PATH. Then, symbol resolution needs to find everything in the libraries that have already been loaded. There are various ways to control which subset of in-memory symbols the dynamic linker considers: the RTLD_GLOBAL/RTLD_LOCAL flags play a role, the -Bsymbolic flag given to the static linker has an impact, and so does the symbol visibility (hidden/internal/protected). Regards, Martin From kbk at shore.net Fri Jan 12 21:59:20 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 12 Jan 2007 21:59:20 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200701130259.l0D2xK59005042@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 421 open ( +3) / 3530 closed ( +8) / 3951 total (+11) Bugs : 963 open ( +4) / 6426 closed (+21) / 7389 total (+25) RFE : 255 open ( +5) / 246 closed ( +1) / 501 total ( +6) New / Reopened Patches ______________________ The Unicode "lazy strings" patches (2007-01-06) http://python.org/sf/1629305 opened by Larry Hastings fast tuple[index] by inlining on BINARY_SUBSCR (2007-01-07) CLOSED http://python.org/sf/1629718 opened by Hirokazu Yamamoto Patch to add tempfile.SpooledTemporaryFile (for #415692) (2007-01-07) http://python.org/sf/1630118 opened by Dustin J. Mitchell Implement named exception cleanup (2007-01-07) CLOSED http://python.org/sf/1630248 opened by Collin Winter Fix crash when replacing sys.stdout in sitecustomize (2007-01-08) http://python.org/sf/1630975 opened by Thomas Wouters SyntaxWarning for backquotes (2007-01-09) http://python.org/sf/1631035 opened by Anthony Baxter implement warnings module in C (2007-01-08) http://python.org/sf/1631171 opened by Neal Norwitz sre module has misleading docs (2007-01-09) http://python.org/sf/1631394 opened by Tom Lynn New exception syntax (2007-01-09) CLOSED http://python.org/sf/1631942 opened by Collin Winter from __future__ import print_function (2007-01-12) http://python.org/sf/1633807 opened by Anthony Baxter Py3k: Fix pybench so it runs (2007-01-13) http://python.org/sf/1634499 opened by Larry Hastings Patches Closed ______________ Win32: Add bytesobject.c to pythoncore.vcproj (2007-01-04) http://python.org/sf/1628062 closed by loewis Win32: Fix build when you have TortoiseSVN but no .svn/* (2007-01-04) http://python.org/sf/1628061 closed by loewis fast tuple[index] by inlining on BINARY_SUBSCR (2007-01-07) http://python.org/sf/1629718 closed by loewis #1603424 subprocess.py wrongly claims 2.2 compatibility. (2006-12-05) http://python.org/sf/1609282 closed by astrand Implement named exception cleanup (2007-01-07) http://python.org/sf/1630248 closed by collinwinter (py3k) Remove the sets module (2006-06-04) http://python.org/sf/1500611 closed by gvanrossum New exception syntax (2007-01-09) http://python.org/sf/1631942 closed by collinwinter backticks will not be used at all (2007-01-03) http://python.org/sf/1627052 closed by gbrandl New / Reopened Bugs ___________________ Python 2.5 64 bit compile fails on Solaris 10/gcc 4.1.1 (2007-01-05) http://python.org/sf/1628484 opened by Bob Atkins Pydoc sets choices for doc locations incorrectly (2007-01-05) http://python.org/sf/1628895 opened by Skip Montanaro xml.dom.minidom parse bug (2007-01-05) CLOSED http://python.org/sf/1628902 opened by Pierre Imbaud clarify 80-char limit (2007-01-05) http://python.org/sf/1628906 opened by Jim Jewett inspect trouble when source file changes (2007-01-05) http://python.org/sf/1628987 opened by phil Incorrect type in PyDict_Next() example code (2007-01-05) http://python.org/sf/1629125 opened by Jason Evans email._parseaddr AddrlistClass bug (2007-01-06) http://python.org/sf/1629369 opened by Tokio Kikuchi array.array borks on deepcopy (2006-08-24) CLOSED http://python.org/sf/1545837 reopened by nnorwitz documentation of email.utils.parsedate is confusing (2007-01-06) http://python.org/sf/1629566 opened by Nicholas Riley Backward incompatibility in logging.py (2006-10-02) CLOSED http://python.org/sf/1569622 reopened by mklaas doc error for re.sub (2007-01-08) CLOSED http://python.org/sf/1630511 opened by Keith Briggs doc misleading in re.compile (2007-01-08) http://python.org/sf/1630515 opened by Keith Briggs Seg fault in readline call. (2007-01-08) http://python.org/sf/1630794 opened by gnovak fnmatch.translate undocumented (2007-01-08) http://python.org/sf/1630844 opened by Gabriel Genellina PyLong_AsLong doesn't check tp_as_number (2007-01-08) CLOSED http://python.org/sf/1630863 opened by Roger Upole Garbage output to file of specific size (2007-01-08) http://python.org/sf/1630894 opened by Michael Culbertson email.Generators does not separates headers with "\r\n" (2005-11-05) http://python.org/sf/1349106 reopened by bwarsaw Discrepancy between iterating empty and non-empty deques (2007-01-09) CLOSED http://python.org/sf/1631769 opened by Christos Georgiou logging.config.fileConfig doesn't clear logging._handlerList (2007-01-10) CLOSED http://python.org/sf/1632328 opened by Stefan H. Holek Hangs with 100% CPU load for certain regexes (2007-01-11) CLOSED http://python.org/sf/1633583 opened by Matthias Klose using locale does not display the intended behavior (2007-01-11) http://python.org/sf/1633600 opened by Matthias Klose logging module / wrong bytecode? (2007-01-12) http://python.org/sf/1633605 opened by Matthias Klose curses should reset curses.{COLS,LINES} when term. resized (2007-01-12) http://python.org/sf/1633621 opened by Matthias Klose time.strftime() accepts format which time.strptime doesnt (2007-01-12) http://python.org/sf/1633628 opened by Matthias Klose class derived from float evaporates under += (2007-01-12) http://python.org/sf/1633630 opened by Matthias Klose incomplete numerical comparisons (2007-01-12) http://python.org/sf/1633648 opened by Matthias Klose file(file) should succeed (2007-01-12) CLOSED http://python.org/sf/1633665 opened by Matthias Klose mailbox.py _fromlinepattern regexp does not support positive (2007-01-12) http://python.org/sf/1633678 opened by Matthias Klose AIX: configure ignores $CC; problems mit C++ comments (2007-01-12) http://python.org/sf/1633863 opened by Johannes Abt for line in sys.stdin: doesn't notice EOF the first time (2007-01-12) http://python.org/sf/1633941 opened by Matthias Klose re.compile("(.*$){1,4}", re.MULTILINE) fails (2007-01-12) http://python.org/sf/1633953 opened by Matthias Klose configure problem for sem_init() on HP-UX (2007-01-12) CLOSED http://python.org/sf/1634033 opened by Johannes Abt AIX: wrong flags for ld when linking standard .so modules (2007-01-12) CLOSED http://python.org/sf/1634105 opened by Johannes Abt subprocess swallows empty arguments under win32 (2007-01-12) http://python.org/sf/1634343 opened by Patrick M?zard Bugs Closed ___________ documentation error for "startswith" string method (2007-01-04) http://python.org/sf/1627956 closed by akuchling null bytes in docstrings (2006-12-26) http://python.org/sf/1622533 closed by akuchling gzip.GzipFile is slow (2003-11-25) http://python.org/sf/849046 closed by akuchling xml.dom.minidom parse bug (2007-01-05) http://python.org/sf/1628902 closed by loewis frame->f_lasti not always correct (2006-01-18) http://python.org/sf/1409443 closed by rhettinger Undocumented implicit strip() in split(None) string method (2005-01-19) http://python.org/sf/1105286 closed by rhettinger split() description not fully accurate (2005-12-14) http://python.org/sf/1380970 closed by rhettinger Underspecified behaviour of string methods split, rsplit (2006-01-25) http://python.org/sf/1414673 closed by rhettinger 32/64bit pickled Random incompatiblity (2006-04-18) http://python.org/sf/1472695 closed by rhettinger array.array borks on deepcopy (2006-08-24) http://python.org/sf/1545837 closed by nnorwitz subprocess.py (py2.5) wrongly claims py2.2 compatibility (2006-11-27) http://python.org/sf/1603424 closed by astrand subprocess.Popen closes fds for sys.stdout or sys.stderr (2006-11-28) http://python.org/sf/1604851 closed by astrand Backward incompatibility in logging.py (2006-10-02) http://python.org/sf/1569622 closed by vsajip doc error for re.sub (2007-01-08) http://python.org/sf/1630511 closed by mwh PyLong_AsLong doesn't check tp_as_number (2007-01-08) http://python.org/sf/1630863 closed by loewis RotatingFileHandler cannot recover from failed doRollover() (2007-01-04) http://python.org/sf/1627575 closed by vsajip Discrepancy between iterating empty and non-empty deques (2007-01-09) http://python.org/sf/1631769 closed by rhettinger ctypes: Returning c_void_p from callback doesn\'t work (2006-10-10) http://python.org/sf/1574593 closed by theller logging.config.fileConfig doesn't clear logging._handlerList (2007-01-10) http://python.org/sf/1632328 closed by vsajip logging's fileConfig causes KeyError on shutdown (2006-08-04) http://python.org/sf/1534765 closed by vsajip Hangs with 100% CPU load for certain regexes (2007-01-11) http://python.org/sf/1633583 closed by niemeyer configure problem for sem_init() on HP-UX (2007-01-12) http://python.org/sf/1634033 deleted by jabt AIX: wrong flags for ld when linking standard .so modules (2007-01-12) http://python.org/sf/1634105 deleted by jabt New / Reopened RFE __________________ Show "expected" token on syntax error (2007-01-12) http://python.org/sf/1634034 opened by Oliver Gramberg RFE Closed __________ file(file) should succeed (2007-01-11) http://python.org/sf/1633665 closed by akuchling From nmm1 at cus.cam.ac.uk Mon Jan 8 09:35:42 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 8 Jan 2007 14:35:42 GMT Subject: Bizarre floating-point output References: Message-ID: In article , "Richard Brodie" writes: |> |> When you do print on a tuple it doesn't recursively |> call str(), so you get the repr representations. Ah! That explains it. I would call that reason intermediate between rational and an artifact of the way the code has evolved! Regards, Nick Maclaren. From dfj225 at gmail.com Wed Jan 10 14:51:53 2007 From: dfj225 at gmail.com (dfj225 at gmail.com) Date: 10 Jan 2007 11:51:53 -0800 Subject: dynamic library loading, missing symbols In-Reply-To: <1168439928.436359.240390@i39g2000hsf.googlegroups.com> References: <1168439928.436359.240390@i39g2000hsf.googlegroups.com> Message-ID: <1168458713.270248.165830@i56g2000hsf.googlegroups.com> So, I did some searching and using python -v to run my code, I was able to see that my module was loaded by the python interpreter using dlopen("lib", 2). 2 is the RTLD_NOW flag, meaning that RTLD_LOCAL is assumed by the system. I suppose this means that any subsequent libraries dlopened will not see any of the symbols in my module? I guess I'll have to look through the Python documentation to see if they offer any work arounds to this problem. ~Doug On Jan 10, 9:38 am, "dfj... at gmail.com" wrote: > > Did you verify, using nm -D, that the symbol is indeed present in > > the shared object, not just in the source code?Yes, the symbol is found in the shared object when using nm. > > > What flags are given to that dlopen call?dlopen(lib, RTLD_NOW | RTLD_GLOBAL); > > > No. The dynamic linker doesn't search files to resolve symbols; instead, > > it searches the process' memory. It first loads the referenced shared > > libraries (processing the DT_NEEDED records in each one); that uses > > the LD_LIBRARY_PATH. Then, symbol resolution needs to find everything > > in the libraries that have already been loaded.Ok, so if the linker is searching the process address space, then I > suppose what really comes into play here is how the Python interpreter > dynamically loaded my module, a module which is in turn calling code > that does the dlopen above. If the Python interpreter is not loading > my library as global, does that mean the linker will not find them > when subsequent libraries are loaded? > > > There are various ways to control which subset of in-memory symbols > > the dynamic linker considers: the RTLD_GLOBAL/RTLD_LOCAL flags play > > a role, the -Bsymbolic flag given to the static linker has an impact, > > and so does the symbol visibility (hidden/internal/protected).Ok, any other suggestions for things to try? Since all of the dlopen > calls happen in 3rd party code, I won't really be able to modify them. > I will try looking into more compile time flags for the linker and see > what I can come up with. Keep in mind that this code works when it is > all C++. Only when I add the Boost.Python wrapper to my code and then > import in Python do I get this symbol error. > > Thank you for your help, > ~Doug From larry.bates at websafe.com Tue Jan 9 11:57:20 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 09 Jan 2007 10:57:20 -0600 Subject: mxODBC problems In-Reply-To: <1168350572.375852.212740@i15g2000cwa.googlegroups.com> References: <1168350572.375852.212740@i15g2000cwa.googlegroups.com> Message-ID: <-vqdnaETVsDwVD7YnZ2dnUVZ_ubinZ2d@comcast.com> Sean Davis wrote: > I have just installed mxODBC on my x86_64 suse linux machine, where I > use unixODBC for connection. Running queries from isql or DataManager > works fine for the DSN that I am using. However, under mxODBC, I can > get a connection object and a cursor object, but all attempts to > execute even the simplest selects result in empty resultsets. Any > ideas on what might be wrong? > >>>> from mx.ODBC.unixODBC import * >>>> con = connect('Postgresql',user='username',password='passwd') >>>> cur = con.cursor() >>>> cur.execute('SELECT * FROM g_rif') >>>> rs = cur.execute('SELECT * FROM g_rif') >>>> rs >>>> cur.execute('SELECT * FROM g_rif').fetchall() > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'fetchall' > > Thanks, > Sean > I think you will find that there result returned by the cur.execute is None upon success. You probably meant: cur.execute('SELECT * FROM g_rif') table=cur.fetchall() Then process table. -Larry From cliff at develix.com Wed Jan 31 18:14:10 2007 From: cliff at develix.com (Cliff Wells) Date: Wed, 31 Jan 2007 15:14:10 -0800 Subject: How to sort using hash's key? In-Reply-To: <1170276870.45c102069d9e6@webmail.3web.com> References: <1170276870.45c102069d9e6@webmail.3web.com> Message-ID: <1170285250.3675.3.camel@portable-evil> On Thu, 2007-02-01 at 04:54 +0800, JoJo wrote: > I want to sort a dict via its key,but I have no idea on how to do it. > Please help me,thanks. You can't. There is, however, a recipe for an "ordered dict" on ASPN: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438823 > 3webXS HiSpeed Dial-up...surf up to 5x faster than regular dial-up alone... > just $14.90/mo...visit www.get3web.com for details You pay $15/mo for dialup??? Regards, Cliff From S.Mientki-nospam at mailbox.kun.nl Sat Jan 13 06:06:55 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 13 Jan 2007 12:06:55 +0100 Subject: Portable Python - free portable development environment ! In-Reply-To: <1168684571.205607.277920@s34g2000cwa.googlegroups.com> References: <1168533423.224355.221390@k58g2000hse.googlegroups.com> <1168639781.763133.319580@s34g2000cwa.googlegroups.com> <1168684571.205607.277920@s34g2000cwa.googlegroups.com> Message-ID: <9a6bb$45a8bd39$d443bb3a$8938@news.speedlinq.nl> > and something like Enthought edition will be there :) with even more > packages and options :) at least that is my goal for the future :) But > I must say I will also always be carefull with size of the distro :) > thats also important right? :) Coming from MatLab, that's not the most important thing ;-) > > more ideas? Embedded use of Python (e.g. Python4Delphi)... ... I can imagine it needs special requirements ? cheers, Stef From albert.wellens at gmail.com Tue Jan 16 17:17:51 2007 From: albert.wellens at gmail.com (awel) Date: 16 Jan 2007 14:17:51 -0800 Subject: Check a windows service In-Reply-To: <1168967374.568967.173690@11g2000cwr.googlegroups.com> References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> <1168967374.568967.173690@11g2000cwr.googlegroups.com> Message-ID: <1168985869.099273.13630@38g2000cwa.googlegroups.com> Sorry, but could you give me an example with a real service 'cause I've tried this script but nothings happened, no error, nothings ; even if I launch it in cmd prompt. Thanks Tim Golden a ?crit : > awel wrote: > > > I'm new in python and I would like to know if it's possible to check if > > a specific windows service is present and if it's possible how can I > > do? > > This is one way: > > http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services > > You'd have to change that example slightly, but I > hope the principal is clear enough. If not, ask again. > > TJG From horpner at yahoo.com Wed Jan 24 15:55:17 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 24 Jan 2007 20:55:17 GMT Subject: Re-thinking my if-thens - a software engineering question References: <1169668287.517657.24450@l53g2000cwa.googlegroups.com> Message-ID: On 2007-01-24, metaperl wrote: > if dict_key == 'PCN': > fields = dict_val.split("/") > mo = re.match( '(\w{2})(\d{2})(\d{2})' , fields[1] ) > if mo: > dict_val = "%s/%s%s/%s" % (fields[0], mo.group(1), mo.group(3), > fields[2][1:]) > else: > dict_val = dict_val > > Ok, so now here is what has happened. This code was based on > the assumption that dict_val would have 2 forward slashes in > it. It turns out that I need to follow a different process of > massaging when no slashes are present. A naive solution would > be something like: > > if dict_key == 'PCN': > fields = dict_val.split("/") > if fields == 3: > dict_val = pcn_three(fields) # where pcn_three > is the code above > else: > # new logic > > But I am wondering if I should abstract the flow of control > into a class or something. This is what I do in Python when a new requirement pops up: 1. Write the simplest/first thing that comes to mind to fix it. 1. a) Am I done? Probably. But maybe not. 2. Now I examine what I've written to see the lay of the code. Only after writing something new once do I usually have enough information to write it better. In other words, writing the code organizes my thoughts. I usually have to fully understand something, even to get a kludgey solution to work. The Kludgey solution informs the design of something better. 2. a) Got to 1. a) In the case above, I've tried to figure out what you're specifically doing, and failed. So I don't have more specific advice. -- Neil Cerutti From no-spam at no-spam-no-spam.invalid Tue Jan 16 06:34:30 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Tue, 16 Jan 2007 12:34:30 +0100 Subject: How to convert float to sortable integer in Python In-Reply-To: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> References: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> Message-ID: shellon wrote: > Hi all: > I want to convert the float number to sortable integer, like the > function float2rawInt() in java, but I don't know the internal > expression of float, appreciate your help! > float comparision works well enough for sorting in Python. What is the actual requirement? see also hash() and id() for keying. Robert From gonzlobo at gmail.com Sun Jan 7 16:03:07 2007 From: gonzlobo at gmail.com (gonzlobo) Date: Sun, 7 Jan 2007 14:03:07 -0700 Subject: Python cheatsheets Message-ID: Curious if anyone has a python cheatsheet* published? I'm looking for something that summarizes all commands/functions/attributes. Having these printed on a 8" x 11" double-sided laminated paper is pretty cool. * cheatsheet probably isn't the right word, but you get the idea. :) From jdvolz at gmail.com Mon Jan 8 16:39:12 2007 From: jdvolz at gmail.com (jdvolz at gmail.com) Date: 8 Jan 2007 13:39:12 -0800 Subject: Network failure when using urllib2 Message-ID: <1168292352.349983.139260@i15g2000cwa.googlegroups.com> I have a script that uses urllib2 to repeatedly lookup web pages (in a spider sort of way). It appears to function normally, but if it runs too long I start to get 404 responses. If I try to use the internet through any other programs (Outlook, FireFox, etc.) it will also fail. If I stop the script, the internet returns. Has anyone observed this behavior before? I am relatively new to Python and would appreciate any suggestions. Shuad From sturlamolden at yahoo.no Wed Jan 17 17:53:02 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 17 Jan 2007 14:53:02 -0800 Subject: How can I create a linked list in Python? In-Reply-To: <45ae8950$0$31033$426a74cc@news.free.fr> References: <45ad5104$0$393$426a74cc@news.free.fr> <1169009882.408482.43360@q2g2000cwa.googlegroups.com> <45ae8950$0$31033$426a74cc@news.free.fr> Message-ID: <1169074382.702857.313010@11g2000cwr.googlegroups.com> Bruno Desthuilliers wrote: > Have you considered using tuples ? If you go the FP way, why not use an > immutable type ? Well, good question. Tuples are immutable, which means they are immutable. So you cannot use a cursor to change an element inside the list. So instead of changing the original items, you just replace the cursor with a new reference. But it it is read only, sure, use tuples. > But how are Lisp lists implemented then ?-) They are defunct binary trees, some think they are not really lists at all :-) Actually, nesting tuples or lists doesn't really duplicate Lisp cons, as one can only create a stack-like object with the nesting. Python really need a cons type like Lisp. I think it is time to write one, in a plain C extension. From scott.daniels at acm.org Tue Jan 16 13:39:38 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 16 Jan 2007 10:39:38 -0800 Subject: A note on heapq module In-Reply-To: <45ad0f6c$1@nntp0.pdx.net> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> <45ad0f6c$1@nntp0.pdx.net> Message-ID: <45ad110c$1@nntp0.pdx.net> Scott David Daniels wrote: Sorry, I blew the __ne__: >> def __ne__(self, other): >> return not isinstance(other, Heap) or self.h != other.h > return not isinstance(other, self.__class__) and sorted( > self.h) != sorted(other.h) Should be: return not isinstance(other, self.__class__) or sorted( self.h) != sorted(other.h) --Scott David Daniels scott.daniels at acm.org From goodidea1950 at hotmail.spam.com Sat Jan 27 20:12:40 2007 From: goodidea1950 at hotmail.spam.com (AKA gray asphalt) Date: Sat, 27 Jan 2007 17:12:40 -0800 Subject: Do I need Python to run Blender correctly? References: <5%4uh.75582$wP1.6882@newssvr14.news.prodigy.net> Message-ID: "John Nagle" wrote in message news:5%4uh.75582$wP1.6882 at newssvr14.news.prodigy.net... > AKA gray asphalt wrote: >> I downloaded Blender but there was no link for python. Am I on the right >> track? > > Blender doesn't require Python, but if you have Python, you can > write plug-ins for Blender. Get "The Blender Book"; otherwise > you'll never figure Blender out. > > John Nagle Will do. Thanks. From dotancohen at gmail.com Tue Jan 2 15:25:12 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 2 Jan 2007 22:25:12 +0200 Subject: Unsubscribing from the list In-Reply-To: References: <880dece00701020605s59e45a70je871ecd89ec7f487@mail.gmail.com> Message-ID: <880dece00701021225y785be5fbn42971e1ddd30dad9@mail.gmail.com> On 02/01/07, Robert Kern wrote: > Dotan Cohen wrote: > > I need to unsubscribe from this list. I've mailed > > users-unsubscribe at python.org but that did not unsubscribe me. I've > > also gone to the list homepage and entered my user information, but > > that just sent me a message that someone had tried to resubscribe this > > username. What must one do to unsubscribe from python-list? > > Go here: > > http://mail.python.org/mailman/listinfo/python-list > > Go to the bottom of the page. Next to the button "Unsubscribe or edit options", > enter your email address. Click the button. On the next page, click > "Unsubscribe". Follow the instructions in the email that is sent to you. > Thanks. I read that page, got as far as this: (The subscribers list is only available to the list administrator.) and decided that there was no futher interest on the page for me. Thanks. Dotan Cohen http://what-is-what.com/what_is/xss.html http://lyricslist.com/lyrics/artist_albums/95/bush.html From skip at pobox.com Tue Jan 16 08:44:29 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 Jan 2007 07:44:29 -0600 Subject: Globbing files by their creation date In-Reply-To: <1168954453.954486.188680@m58g2000cwm.googlegroups.com> References: <1168954453.954486.188680@m58g2000cwm.googlegroups.com> Message-ID: <17836.54973.859482.949455@montanaro.dyndns.org> Thomas> I've used glob.glob to create a list of all files whose name Thomas> matches a substring, but I don't see how I can use it to Thomas> identify files by their creation date. Sumthin' like: files = [f for f in glob.glob(globpat) if os.path.getctime(f) > timethreshold] Define globpat and timethreshold accordingly. You sure you don't mean modification time? If so, change getctime to getmtime. Skip From S.Mientki-nospam at mailbox.kun.nl Mon Jan 22 17:37:41 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 22 Jan 2007 23:37:41 +0100 Subject: Python Windows Editors In-Reply-To: References: Message-ID: <9b1f4$45b53ca7$d443bb3a$28591@news.speedlinq.nl> Jarek Zgoda wrote: > Stef Mientki napisa?(a): > >> Any text editor is only as good as the >>> programmer who uses it. ;) >>> >> Yes but an IDE is different ;-) > > Would it make me better Fortran programmer? ;) > I can't judge for you, ... ... maybe you are already at the top ;-) I can only speak for myself ... ... for beginners an IDE is certainly much much more than an editor. cheers, Stef Mientki From deets at nospam.web.de Sat Jan 20 14:19:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 20 Jan 2007 20:19:37 +0100 Subject: confused on python rpc with apache, is it possible? In-Reply-To: References: <51ce8uF1k0tl5U1@mid.uni-berlin.de> <1169276359.477277.17930@q2g2000cwa.googlegroups.com> <51etfpF1kappuU1@mid.uni-berlin.de> Message-ID: <51f8aoF1ju2i6U1@mid.uni-berlin.de> > > well in that case I don't need apache. > can I do xml-rpc using the default libraries that come with every > python installer? Yes, and a simple look in the API docs would have convinced you of that. I suggest you start googling and reading. > is there some added advantage of using twisted? Certainly, but it comes with added burden of using and understanding a complex framework. Here also applies: read the docs. Diez From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jan 15 16:43:57 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 15 Jan 2007 22:43:57 +0100 Subject: Watch log References: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> Message-ID: <512astF1i9fgbU1@mid.individual.net> Salvatore Di Fazio wrote: > I would like wait until a new line will be write in the file. > > Something like the "watch cat Log" command on Linux os. Why not read the file continuously and only do something if a new line is complete (i. e. a newline char is detected)? > How can I check the eof and restart the reading? Why do you want to check for an EOF character? Regards, Bj?rn -- BOFH excuse #212: Of course it doesn't work. We've performed a software upgrade. From NutJob at gmx.net Thu Jan 25 09:38:28 2007 From: NutJob at gmx.net (antred) Date: 25 Jan 2007 06:38:28 -0800 Subject: Please have a look at this class Message-ID: <1169735908.009109.7460@a75g2000cwd.googlegroups.com> Hello everyone, While working on a program I encountered a situation where I'd construct a largish data structure (a tree) from parsing a host of files and would end up having to throw away parts of my newly built tree if a file turned out to contain invalid data. My first thought was 'Well, you can always make a deep copy of your tree first, then add new data to the copy and revert to the original if you need to.", but as this tree can grow very big this is not exactly efficient. So my second idea was to come up with a class that offers a very limited degree of database-like behavior, meaning you can make changes to the object and then decide whether you want to commit those changes or roll them back to get back to the original. For example: u = Unrollable() u.someValue = 3.14 u.aString = 'Hi there' # If we decide we want to keep those changes ... u.commit() # Or we could have reverted to the original. This would have restored the state prior to the last call to commit() (or simply the state at the beginning, if there hasn't been a call to commit yet). #u.rollback() The basic idea behind this is that each instance of the Unrollable class keeps an internal dictionary (which, in lieu of a better name I'm currently calling 'sand box') to which all changed attribute values are saved (attribute changes are intercepted via __setattr__). Then, with a call to commit(), all attributes are transferred to the instance's __dict__ dictionary and hence become actual attributes per se. Similarily, the rollback() function simply empties the contents of the sand box without committing them to __dict__. The rollback() function can work recursively, too, if passed some extra parameters. If so, it walks either the sand box or the __dict__ (or both) and invokes the rollback() function on any attribute members that are instances of the Unrollable class or a derived class. Finally, this works for 'private' attributes (i.e. names with two leading underscores), too, as the __setattr__ implementation mangles the name of the attribute if it detects a private name. I'm posting this for 2 reasons. Firstly, I feel that I have finally produced something that others _might_ find useful, too. Secondly, since I'm still learning Python (yeah, even after 2 years), I would be very grateful to hear people's criticisms. Are there things that could be done more efficiently? Do you spot any grave errors? Does something similar already exist that I should just have used instead? Right now I'm rather pleased with my class, but if someone tells me there is already something like this Python's library (and then it'll most likely be more efficient anyway) then I'd of course rather use that. Entire class definition + some test code attached to this post. P.S. I __LOVE__ how something like this is just barely 70 lines of code in Python! class Unrollable( object ): """Provides a very simple commit/rollback system.""" def __setattr__( self, attributeName, attributeValue ): """Changes the specified attribute by setting it to the passed value. The change is only made to the sandbox and is not committed.""" if attributeName.find( '__' ) == 0: # Mangle name to make attribute private. attributeName = '_' + self.__class__.__name__ + attributeName try: theDict = self.__dict__[ '_Unrollable__dSandBox' ] except KeyError: theDict = self.__dict__[ '_Unrollable__dSandBox' ] = {} theDict[ attributeName ] = attributeValue def __getattr__( self, attributeName ): """This method ensures an attribute can be accessed even when it hasn't been committed yet (since it might not exist in the object itself yet).""" if attributeName.find( '__' ) == 0: # Mangle name to make attribute private. attributeName = '_' + self.__class__.__name__ + attributeName try: theDict = self.__dict__[ '_Unrollable__dSandBox' ] except KeyError: # Our sandbox doesn't exist yet, therefore the requested attribute doesn't exist yet either. raise AttributeError try: return theDict[ attributeName ] except KeyError: # No such attribute in our sandbox. raise AttributeError def commitChanges( self ): """Commits the contents of the sandbox to the actual object. Clears the sandbox.""" while len( self.__dSandBox ) > 0: key, value = self.__dSandBox.popitem() self.__dict__[ key ] = value def unroll( self, bRecurseSandBox = True, bRecurseDict = False ): """Ditches all changes currently in the sandbox. Recurses all objects in the instance itself and in its sandbox and, if they're unrollable instances themselves, invokes the unroll method on them as well.""" if bRecurseSandBox: while len( self.__dSandBox ) > 0: key, value = self.__dSandBox.popitem() if isinstance( value, Unrollable ): value.unroll( bRecurseSandBox, bRecurseDict ) else: self.__dSandBox.clear() if bRecurseDict: iterator = self.__dict__.itervalues() while True: try: nextVal = iterator.next() except StopIteration: break if isinstance( nextVal, Unrollable ): nextVal.unroll( bRecurseSandBox, bRecurseDict ) def hasUncommittedChanges( self ): """Returns true if there are uncommitted changes, false otherwise.""" return len( self.__dSandBox ) > 0 if __name__ == '__main__': # With a public attribute ... u = Unrollable() print 'Before.' try: theValue = u.theValue except AttributeError: print 'u does not have a theValue attribute yet.' else: print 'u.theValue is', theValue u.theValue = 3.147634 print 'After set().' try: theValue = u.theValue except AttributeError: print 'u does not have a theValue attribute yet.' else: print 'u.theValue is', theValue u.commitChanges() print 'After commitChanges().' try: theValue = u.theValue except AttributeError: print 'u does not have a theValue attribute yet.' else: print 'u.theValue is', theValue print u.__dict__ # With a private attribute ... class MyClass( Unrollable ): def accessPrivateAttr( self ): try: theValue = self.__theValue except AttributeError: print 'self does not have a __theValue attribute yet.' else: print 'self.__theValue is', theValue anObject = MyClass() print 'Before.' anObject.accessPrivateAttr() anObject.__theValue = 6.667e-11 print 'After set().' anObject.accessPrivateAttr() #anObject.commitChanges() print 'After commitChanges().' anObject.accessPrivateAttr() anObject.subObject = Unrollable() anObject.subObject.aString = 'Yeeehaawww' print anObject.__dict__ print anObject.subObject.__dict__ anObject.unroll( True, True ) print anObject.__dict__ From kavithapython at yahoo.co.in Thu Jan 25 04:55:15 2007 From: kavithapython at yahoo.co.in (kavitha thankaian) Date: Thu, 25 Jan 2007 09:55:15 +0000 (GMT) Subject: newbie question:connecting to a database In-Reply-To: <45B490D0.8020809@portaone.com> Message-ID: <111669.72456.qm@web7812.mail.in.yahoo.com> Hi, I could solve the problem in connecting to a database,,, while configuring the daatsourcename by default it gets connected to the master table,,,so there i must specify the database which i like to connect,,,so now i can see the animals table in my database,, Thanks Eugene,,, Kavitha Eugene Antimirov wrote: kavitha thankaian wrote: > Hi, > > i wrote a simple script (which follows) to insert a table in the > database.i could execute this query and get the result in python > shell.but when i open "my sql enterprise manager" i couldnt find the > table"animals".it would be so kind of you if someone could help me,,, > > > import dbi > import odbc > conn=odbc.odbc("DSN=mydatabase;UID=xxx;PWD=yyy") > cursor=conn.cursor() > cursor.execute("Create table animals(parent char(50),child char(50))") > cursor.execute("insert into animals values('lion','cub')") > cursor.execute("insert into animals values('goat','lamb')") > cursor.execute("select * from animals") > print cursor.fetchall() > > > Rgds > Kavitha > > ------------------------------------------------------------------------ You've probably missed cursor.commit() ;) -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer support at portaone.com * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Here?s a new way to find what you're looking for - Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton.hartl at gmail.com Mon Jan 15 14:34:46 2007 From: anton.hartl at gmail.com (Anton Hartl) Date: Mon, 15 Jan 2007 19:34:46 +0000 (UTC) Subject: Segfault with tktreectrl on python-2.5 on linux References: <1168884154.116074.308720@s34g2000cwa.googlegroups.com> Message-ID: Hi, On 2007-01-15, klappnase wrote: > Some people sent me mail describing the same problem, so I think it is > not a problem with my installation of python-2.5. The treectrl widget > itself works well when running from Tcl or from python2.4, so i suspect > that it is a bug in python-2.5. > Below the output from gdb when running the dirtree demo from the > TkinterTreectrl package: > > (gdb) run > Starting program: /usr/local/bin/python2.5 > /home/pingu/projekte/TkinterTreectrl/TkinterTreectrl-0.6/demo/dirtree.py > [Thread debugging using libthread_db enabled] > [New Thread -1209842944 (LWP 21831)] > > Program received signal SIGSEGV, Segmentation fault. > [Switching to Thread -1209842944 (LWP 21831)] > block_alloc (b=0x1, size=16) at Python/pyarena.c:109 > 109 if (b->ab_offset + size > b->ab_size) { > (gdb) bt > #0 block_alloc (b=0x1, size=16) at Python/pyarena.c:109 > #1 0x080d829e in PyArena_Malloc (arena=0x82b2790, size=16) at > Python/pyarena.c:192 > #2 0x081129ca in Ellipsis (arena=0x10) at Python/Python-ast.c:1764 > #3 0xb77731ef in DisplayProcText () from > /usr/lib/treectrl2.2/libtreectrl2.2.so > > Any ideas? Yes. And a solution as well :) Here is the story: - libpython2.5.so contains a global symbol "Ellipsis"; this is new in 2.5 and came in with the new AST/compiler code - starting python2.5 loads libpython2.5.so (obviously) - now you do something like: tk.call("package", "require", "tktreectrl") this loads libtktreectrl2.2.so - libtktreectrl2.2.so contains a global symbol "Ellipsis" - and now disaster happens: references in libtktreectrl2.2.so to "Ellipsis" are NOT resolved to the "Ellipsis" symbol in libtktreectrl2.2.so but rather to the "Ellipsis" symbol in libpython2.5.so - this is not what you want, but is correct behaviour of symbol resolution in shared shared libraries (and is equivalant to the behaviour with static libs btw) Solutions: a) convince Python developers to prefix ALL new (wrt. 2.5) global symbols with a prefix like "_PyAST_" or equivalent; this would be consistent with how it is done anyway, unfortunately the new AST symbols deviate from this practise (there are symbols like "Assert", "If", "Then", ...) or b) apply an equivalent rule to the global symbols in tktreectrl that are global by accident, i.e. because of the way the library is structured and built Best Regards, Anton From cvanarsdall at mvista.com Thu Jan 25 14:12:24 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 25 Jan 2007 11:12:24 -0800 Subject: The reliability of python threads In-Reply-To: References: Message-ID: <45B90118.5010408@mvista.com> Aahz wrote: > [snip] > > My response is that you're asking the wrong questions here. Our database > server locked up hard Sunday morning, and we still have no idea why (the > machine itself, not just the database app). I think it's more important > to focus on whether you have done all that is reasonable to make your > application reliable -- and then put your efforts into making your app > recoverable. > Well, I assume that I have done all I can to make it reliable. This list is usually my last resort, or a place where I come hoping to find ideas that aren't coming to me naturally. The only other thing I thought to come up with was that there might be network errors. But i've gone back and forth on that, because TCP should handle that for me and I shouldn't have to deal with it directly in pyro, although I've added (and continue to add) checks in places that appear appropriate (and in some cases, checks because I prefer to be paranoid about errors). > I'm particularly making this comment in the context of your later point > about the bug showing up only every three or four months. > > Side note: without knowing what error messages you're getting, there's > not much anybody can say about your programs or the reliability of > threads for your application. > Right, I wasn't coming here to get someone to debug my app, I'm just looking for ideas. I constantly am trying to find new ways to improve my software and new ways to reduce bugs, and when i get really stuck, new ways to track bugs down. The exception won't mean much, but I can say that the error appears to me as bad data. I do checks prior to performing actions on any data, if the data doesn't look like what it should look like, then the system flags an exception. The problem I'm having is determining how the data went bad. In tracking down the problem a couple guys mentioned that problems like that usually are a race condition. From here I examined my code, checked out all the locking stuff, made sure it was good, and wasn't able to find anything. Being that there's one lock and the critical sections are well defined, I'm having difficulty. One idea I have to try and get a better understanding might be to check data before its stored. Again, I still don't know how it would get messed up nor can I reproduce the error on my own. Do any of you think that would be a good practice for trying to track this down? (Check the data after reading it, check the data before saving it) -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From gagsl-py at yahoo.com.ar Wed Jan 17 06:20:01 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Jan 2007 08:20:01 -0300 Subject: How to convert float to sortable integer in Python In-Reply-To: <1169015814.960023.40310@a75g2000cwd.googlegroups.com> References: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> <1169015814.960023.40310@a75g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20070117070716.04691c98@yahoo.com.ar> At Wednesday 17/1/2007 03:36, shellon wrote: >I'm sorry I mistake the function name, the function is >floatToRawIntBits(), it convert ieee 754 floating point number to >integer, e.g. if f1>f2 then floatToRawBits(f1) > floatToRawBits(f1) >I want convert floating point number to sortable string to index in >Lucene, so I want first to conver the floating point number to integer >first, and than convert the integer to sortable string? The following two functions may be useful; they do more-or-less the same thing, but returning a string instead of an integer. Note that this property: f1>f2 => floatToRawBits(f1) > floatToRawBits(f2), only holds for nonnegative numbers; this code has the same restriction. The code assumes a few things: float(repr(x))==x for 0.5<=x<1 (that is, repr(x) is exact in that range); the maximum double value has an exponent (as given by frexp) less than 5000; the minimum positive value has an exponent greater than -5000; 0 is the only number having mantissa==0; and surely I'm assuming many more but I'm not aware of them. I think it's not dependent on a particular FP hardware or representation. Beasts like denormals, INFs and NaNs are not considered at all. It appears to work OK for "normal" numbers, but I've not checked all corner cases. It was only tested on Windows XP. After such long disclaimer... I hope it's useful :) --- begin fpsrepr.py --- import math def float2srepr(f): """Convert a floating point number into a string representation which can be sorted lexicographically maintaining the original numerical order (only for numbers >= 0). That is, given f1,f2 >= 0, f1 float2srepr(f1) 1.0 and curr < prev: prev = curr curr /= 2.0 return prev def find_minf(): # smallest x such x>0 prev, curr = 1.0, 0.5 while curr > 0.0 and curr < prev: prev = curr curr /= 2 return prev eps = find_eps() print "eps=%r %r" % (eps, 1.0+eps) minf = find_minf() print "minf=%r %r" % (minf, -minf) values = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9, 1.0,1.0+eps,1.0+2*eps,1.0-eps,1.0-2*eps, 2,3,10,10.0000001,10.00000000001, 123.456,1234.567,12345.678,123456.789,1.234e10, 123412341234,123412341234123412341234.0,1.234e20, 1e100,1e200,1e300,math.pi,math.e] values += [1.0/x for x in values if x>0] + [eps, minf] values += [-x for x in values] values = sorted(values) for x in values: s = float2srepr(x) xr = srepr2float(s) print '%-30r %s' % (x, s) assert x==xr, '%r!=%r' % (x, xr) f2svalues = [float2srepr(x) for x in values if x>=0] s2fvalues = [srepr2float(x) for x in sorted(f2svalues)] assert s2fvalues == sorted(s2fvalues), s2fvalues --- end fpsrepr.py --- -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Sun Jan 28 20:41:30 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Jan 2007 22:41:30 -0300 Subject: IP address In-Reply-To: References: Message-ID: <7.0.1.0.0.20070128223459.046e4ef0@yahoo.com.ar> At Sunday 28/1/2007 10:28, Colin J. Williams wrote: >Klaus Alexander Seistrup wrote: > > > > python -c 'import re, urllib; print re.findall("Your IP: > (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' > > > >Your one-liner doesn't work for me, with Windows XP, but the following On XP you should switch the usage of " and ' (double quotes are used to enclose command arguments with embedded spaces): python -c "import re, urllib; print re.findall('Your IP: (.+?)', urllib.urlopen('http://myip.dk/').read())[0]" -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From Boris.Boutillier at gmail.com Thu Jan 25 14:46:52 2007 From: Boris.Boutillier at gmail.com (Boris.Boutillier at gmail.com) Date: 25 Jan 2007 11:46:52 -0800 Subject: Module for SVG? In-Reply-To: References: Message-ID: <1169754412.101443.280390@h3g2000cwc.googlegroups.com> Depending on the size of your project, the xist library from living logic is supporting svg xml: http://www.livinglogic.de/Python/xist/ http://www.livinglogic.de/Python/xist/ns/svg/ We've used it successfully, but later on came back to simply use the standard dom creation tools in python to reduce dependencies. Boris On Jan 25, 10:58 am, "Sebastian Bassi" wrote: > Hello, > > I foundhttp://www2.sfk.nl/svgas a Python module for writing SVG. > Last update was in 2004 and I am not sure if there is something > better. > Any recommendation for generating SVG graphics? > Best, > SB. From felipe.lessa at gmail.com Sun Jan 7 06:57:54 2007 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 7 Jan 2007 09:57:54 -0200 Subject: Why less emphasis on private data? In-Reply-To: <7x7ivz88af.fsf@ruckus.brouhaha.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> Message-ID: On 07 Jan 2007 02:01:44 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Dennis Lee Bieber writes: > > __ (two leading underscores) results in name-mangling. This /may/ be > > used to specify "private" data, but is really more useful when one is > > designing with multiple super classes: > > Trouble with this is you can have two classes with the same name, > perhaps because they were defined in different modules, and then the > name mangling fails to tell them apart. What is the chance of having to inherit from two classes from different modules but with exactly the same name *and* the same instance variable name? Of course you're being very pessimistic or extremely unlucky. -- Felipe. From gheissenberger at gmail.com Thu Jan 11 18:43:18 2007 From: gheissenberger at gmail.com (gheissenberger at gmail.com) Date: 11 Jan 2007 15:43:18 -0800 Subject: Python nuube needs Unicode help In-Reply-To: References: <1168550894.155528.295700@p59g2000hsd.googlegroups.com> Message-ID: <1168558998.056454.265720@p59g2000hsd.googlegroups.com> Yeah, that's what i don't know how to do. Chris Mellon wrote: > On 11 Jan 2007 13:28:14 -0800, gheissenberger at gmail.com > wrote: > > HELP! > > Guy who was here before me wrote a script to parse files in Python. > > > > Includes line: > > print u > > where u is a line from a file we are parsing. > > However, we have started recieving data from Brazil. If I open file to > > parse in VI, looks like: > > > > > audio="313-20070102144528.wav" grammarSet="G3" rawText="não" > > recValue="{data:CHOICE=NO;}" conf="970" rawText2="" conf2="0" > > transcribedText="não" parsableText="não"/ > > > > Clearly those "nã" are some non-Ascii characters, but how do I get > > print to understand that? > > > > I keep getting: > > "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in > > position 40: > > ordinal not in range(128)" > > > > Find out what encoding the files are in and modify the script to use it. From wolf_tracks at invalid.com Fri Jan 5 11:48:02 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Fri, 05 Jan 2007 08:48:02 -0800 Subject: Just Getting Started with Python on MS XP Pro Message-ID: What do I download to use Python with MX XP Pro on an ASUS 4 year old motherboard? I would guess a good book source for starters would be the O'Reilly book. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet ""I do not fear death. I had been dead for billions and billions of years before I was born, and had not suffered the slightest inconvenience from it." -- Mark Twain (a nod to evolution) -- Web Page: From sxn02 at yahoo.com Fri Jan 12 17:44:45 2007 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Fri, 12 Jan 2007 14:44:45 -0800 (PST) Subject: Python 2.5 install on Gentoo Linux: failed dmb and _tkinter Message-ID: <520770.90567.qm@web56014.mail.re3.yahoo.com> # ldconfig -p | grep "/usr/local/lib" libtk8.4.so (libc6) => /usr/local/lib/libtk8.4.so libtcl8.4.so (libc6) => /usr/local/lib/libtcl8.4.so Sorin ____________________________________________________________________________________ Now that's room service! Choose from over 150,000 hotels in 45,000 destinations on Yahoo! Travel to find your fit. http://farechase.yahoo.com/promo-generic-14795097 From jmike at alum.mit.edu Fri Jan 12 10:10:54 2007 From: jmike at alum.mit.edu (jmike at alum.mit.edu) Date: 12 Jan 2007 07:10:54 -0800 Subject: Command line arguments on Vista In-Reply-To: <1168613488.896113.326290@l53g2000cwa.googlegroups.com> References: <1168613362.406648.304720@11g2000cwr.googlegroups.com> <1168613488.896113.326290@l53g2000cwa.googlegroups.com> Message-ID: <1168614654.142099.90680@11g2000cwr.googlegroups.com> Some further information: perl seems to do the same thing (losing arguments). We think it may have something to do with file association. Any ideas anyone? --JMike From martin at v.loewis.de Sat Jan 27 07:34:39 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 27 Jan 2007 13:34:39 +0100 Subject: New vs Old Style Python Classes in C Extensions? In-Reply-To: References: Message-ID: <45BB46DF.7000604@v.loewis.de> Jeff Rush schrieb: > from cextension import Context > > class MyContext(Context): > > def __init__(self): > super(Context, self).__init__() > > repeatedly and reliably failed with a corrupted C data structure, while > this: > > class MyContext(Context): > > def __init__(self): > Context.__init__() > > worked without any problems. As I understand it, the former uses > new-style semantics while the latter uses old-style, This understanding is incorrect: Context is either a new-style or an old-style class (if type(Context) is type, it's a new-style class, if type(context) is named 'classobj', it's an old-style class). As you have implemented Context in an extension module, it likely is a new-style class (i.e. a type). Most likely, something is wrong with your tp_init slot. You shouldn't be able to call Context.__init__(): that should raise a type error, indicating that an object is needed for the method __init__. That should hold whether Context is a new-style or an old-style class. HTH, Martin From gandalf at designaproduct.biz Fri Jan 5 11:54:50 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 17:54:50 +0100 Subject: importing / loading a module / class dynamically In-Reply-To: <1hvnh.22241$Dy2.9812@newsfe20.lga> References: <1hvnh.22241$Dy2.9812@newsfe20.lga> Message-ID: <459E82DA.1030503@designaproduct.biz> hg ?rta: > hg wrote: > > >> Hi, >> >> I have the following problem. >> >> I find in a directory hierarchy some files following a certain sets of >> rules: >> >> .../.../../plugin/name1/name1.py >> .... >> .../.../../plugin/namen/namen.py >> >> each file will in turn have a class with the same name as the filename >> (minus .py) >> >> >> I fetch those names in a list of string and want to import the files / >> instantiate the classes. >> >> >> I block at the beginning and tried this (test.py is a real file) >> >>>>> s = 'test.py' >>>>> eval ('import ' + s) >>>>> >> and get >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> eval ('import ' + s) >> File "", line 1 >> import test.py >> >> Any clue ? >> >> Thanks >> >> hg >> > > > OK, from http://mail.python.org/pipermail/python-list/2004-July/272081.html, > I need to use exec and not eval > Well, you can also use the 'imp' module. You should read this: http://docs.python.org/lib/module-imp.html Best, Laszlo From nmm1 at cus.cam.ac.uk Tue Jan 9 15:15:06 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 9 Jan 2007 20:15:06 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> <50i49iF1fvo3rU1@mid.individual.net> Message-ID: In article , Robert Kern writes: |> > |> >> No, don't. That is about another matter entirely, |> > |> > It isn't. |> |> Actually it really is. That thread is about the difference between |> str(some_float) and repr(some_float) and why str(some_tuple) uses the repr() of |> its elements. Precisely. And it also applies to strings, which I had failed to notice: >>> print ("1","2") ('1', '2') >>> print "1", "2" 1 2 Regards, Nick Maclaren. From w.richert at gmx.net Tue Jan 23 05:28:05 2007 From: w.richert at gmx.net (Willi Richert) Date: Tue, 23 Jan 2007 11:28:05 +0100 Subject: Getting to an SSH account over a HTTP proxy In-Reply-To: <1169514995.916358.17030@11g2000cwr.googlegroups.com> References: <1169514995.916358.17030@11g2000cwr.googlegroups.com> Message-ID: <200701231128.05998.w.richert@gmx.net> Am Dienstag, 23. Januar 2007 02:16 schrieb Nanjundi: > BJ?rn Lindqvist wrote: > > I want to use Python to connect to a SSH account over a HTTP proxy to > > automate some operations. I thought paramiko would be able to do that, > > but it can not (it seems). > > > > Is there some other Python module that can do what I want? > > > > -- > > mvh Bj?rn > > Did you take a look at twisted library? > twistedmatrix.com > http://twistedmatrix.com/projects/core/documentation/howto/clients.html > > > I haven't tried to connect over port 80, but its worth a try. > > -N If you need it for automation you might want to use pexpect: http://pexpect.sourceforge.net/ It listens to the tty-stream and simulates a user typing in commands. It is very useful, e.g. if you want to start processes on many machines over ssh. If there are gateways/firewalls between - no problem just use a second "sendline('ssh user at nextmachine')" The only problem is the regular expression: If e.g. you use a custom $PS1 variable for your prompt you have to account for that. Regards, wr From bruno.desthuilliers at websiteburo.com Thu Jan 18 11:05:21 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Thu, 18 Jan 2007 17:05:21 +0100 Subject: variable scope In-Reply-To: References: Message-ID: <45af9ac4$0$290$426a34cc@news.free.fr> gonzlobo a ?crit : > Greetings, > I've been using Python to successfully parse files. When the entire > program was smaller, the variable firstMsg worked fine, but now > doesn't because it's used in function PID_MinMax. I know it's a result > of variables and their scope. > > I declare the variable 'firstMsg = 0' in the main loop, pass it to the > function 'PID_MinMax(firstMsg, PID)'. When the function increments the > variable, it doesn't pass it back to the main program. What am I doing > wrong? > > > ---- major snippage) --- > firstMsg = 0 (snip) > def PID_MinMax(firstMsg, PID): (snip) > if firstMsg != 0: if firstMsg: > tDelta = tCurrent - pLast[idx] > if tDelta > pMax[idx]: > pMax[idx] = tDelta > if tDelta < pMin[idx]: > pMin[idx] = tDelta > elif firstMsg == 0: else: > firstMsg = 1 > pLast[idx] = tCurrent > print pMin, pMax > return firstMsg > ############## main ############## (snip) > if PID in pPIDs: > PID_MinMax(firstMsg, PID) firstMsg = PID_MinMax(firstMsg, PID) You're returning firstMsg from PID_MinMax, but discarding the value... From gagsl-py at yahoo.com.ar Sun Jan 28 21:08:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 28 Jan 2007 23:08:00 -0300 Subject: socket.inet_ntop, and pton question In-Reply-To: <45bce8f7$0$334$e4fe514c@news.xs4all.nl> References: <12rpns1tkp0e34@corp.supernews.com> <45bce8f7$0$334$e4fe514c@news.xs4all.nl> Message-ID: <7.0.1.0.0.20070128230430.047092a8@yahoo.com.ar> At Sunday 28/1/2007 15:17, Irmen de Jong wrote: > > Are these functions (inet_ntop(), inet_pton()) from the socket library > > supported on Windows. > >Why didn't you just try: > >[E:\Projects]python >Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit >(Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. > >>> import socket > >>> socket.inet_aton("127.0.0.1") >'\x7f\x00\x00\x01' > >>> socket.inet_ntoa(_) >'127.0.0.1' > >>> But these are not the requested functions, inet_ntop() and inet_pton(): py> socket.inet_ntop Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'inet_ntop' -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at REMOVEME.cybersource.com.au Tue Jan 2 02:15:18 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 02 Jan 2007 18:15:18 +1100 Subject: mutable numeric type References: Message-ID: On Mon, 01 Jan 2007 19:20:21 -0800, Andreas Beyer wrote: > I am using a third party library that is performing basic numerical > operations (adding, multiplying, etc.) with objects of unknown type. Of > course, the objects must support the numerical operators. In my case the > third party library is a graph algorithm library and the assigned > objects are edge weights. I am using the library to compute node > distances, etc. > > I would like to be able to change the edge weights after creating the > edges. Otherwise, I would have to remove the edges and re-create them > with the new values, which is quite costly. You've measured it or you're guessing? Presumably the edges and/or nodes store the weights somewhere. Why not just reassign the weight directly in place? It isn't easy to judge whether your scheme is good bad or indifferent when we know so little about the graph library you are using. > Since I also didn't want to change the code of the graph library, You could subclass the graph class. Another possibility is to dynamically modify the library, without changing its source code. E.g. from GraphLibrary import GraphWalker as _gw import GraphLibrary def myGraphWalker(args): x = _gw(args) do_something_to(x) return x GraphLibrary.GraphWalker = myGraphWalker # now use GraphWalker as normal, except it has your # code instead of the original This works for class methods as well. > I came up with a mutable numeric > type, which implements all the numerical operators (instances are of > course not hashable). This allows me to change the edge weights after > creating the graph. This is another alternative, although I still don't understand why you can't just reassign the weights in place. -- Steven D'Aprano From deets at nospam.web.de Mon Jan 1 17:04:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Jan 2007 23:04:23 +0100 Subject: Writing more efficient code In-Reply-To: References: Message-ID: <4vter8F1div1lU1@mid.uni-berlin.de> gonzlobo schrieb: > Greetings, and happyNewYear to all. > > I picked up Python a few weeks ago, and have been able to parse large > files and process data pretty easily, but I believe my code isn't too > efficient. I'm hoping dictionaries will help out, but I'm not sure the > best way to implement them. > > I've been using a bunch of nested if/elif/else statements to select > slices (0317 & 03de) from a file, then parse the data (aa, hh, bb, > d2-d9) into parameters (a = airspeed, h = heading) & flags. > > #sample file contents > 0000007d 03 0317 aa aa aa aa aa hh hh hh bb bb > 0000007e 06 03de d2 d3 d4 d5 d6 d7 d8 d9 10 11 > > # some pseudo code > if PID == '03de': > flapsCmd = int(d3, 16) > if flapsCmd == 0xc0: > > elif flapsCmd == 0x03: > > if PID == '0317': > airspeed == 'combine aa for airspeed & multiply by 0.1' > heading == 'combine hh for heading' > mach == 'combine bb for mach & multiply by 0.01' > > Might dictionaries help in this case... say Label0317(parameterName, > slice (d3), scaleFactor(0.1))... I'd like to use them if they'll > replace the dozens of nested conditionals. I have roughly 75 > different parameters to decode from a file containing ~2.5 million > lines of data. > > I know my pseudo code lacks details, but hopefully I'm getting my > point across... > > (I suppose switch/select/case statements would help a bit, but python > doesn't seem to use them... not to start a religious war or anything). The dictionary approach certainly will be speedier - lookup should usually be O(1) instead of O(n) for the if-elif-chain. Diez From gftframe at gmail.com Sun Jan 28 21:57:02 2007 From: gftframe at gmail.com (GFT) Date: 28 Jan 2007 18:57:02 -0800 Subject: New internet services from MSN Yahoo! and Google are here Message-ID: <1170039422.555664.225190@l53g2000cwa.googlegroups.com> See our explain and compare about new service or feature from three search providers ; Windows Live (MSN) ,Yahoo! ,and Google. Learn more and get it today. At http://searchprovider.awardspace.com/ Thank you very much. From nmm1 at cus.cam.ac.uk Wed Jan 24 15:16:26 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 24 Jan 2007 20:16:26 GMT Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> Message-ID: In article , "Carl J. Van Arsdall" writes: |> Chris Mellon wrote: |> > |> > Logic and programming errors in user code are far more likely to be |> > the cause of random errors in a threaded program than theoretical |> > (I've never come across a case in practice) issues with the POSIX |> > standard. |> > |> Yea, typically I would think that. The problem I am seeing is |> incredibly intermittent. Like a simple pyro server that gives me a |> problem maybe every three or four months. Just something funky will |> happen to the state of the whole thing, some bad data, i'm having an |> issue tracking it down and some more experienced programmers mentioned |> that its most likely a race condition. THe thing is, I'm really not |> doing anything too crazy, so i'm having difficult tracking it down. I |> had heard in the past that there may be issues with threads, so I |> thought to investigate this side of things. I have seen that many dozens of times on half a dozen Unices, but have only tracked down the cause in a handful of cases. Of those, implementation defects that are sanctioned by the standards have accounted for about half. Note that the term "race condition" is accurate but misleading! One of the worst problems with POSIX is that it does not define how non-memory global state is synchronised. For example, it is possible for a memory update and an associated signal to occur on different sides of a synchronisation boundary. Similarly, it is possible for I/O to sidestep POSIX's synchronisation boundaries. I have seen both. Perhaps the nastiest is that POSIX leaves it unclear whether the action of synchronisation is transitive. So, if A synchronises with B, and then B with C, A may not have synchronised with C. Again, I have seen that. It can happen on Intel systems, according to the experts I know. |> Would you consider the Linux implementation of threads to be concrete? In this sort of area, Linux tends to be saner than most systems, but remember that it has had MUCH less stress testing on threaded codes than many other Unices. In fact, it was only a few years ago that Linux threads became stable enough to be worth using. Note that failures due to implementation defects and flaws in the standards are likely to show up in very obscure ways; ones due to programmer error tend to be much simpler. If you want to contact me by Email, and can describe technically what you are doing and (most importantly) what you are assuming, I may be able to give some hints. But no promises. Regards, Nick Maclaren. From martin at v.loewis.de Thu Jan 11 01:33:43 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 11 Jan 2007 07:33:43 +0100 Subject: Python 2.5 install on Gentoo Linux: failed dmb and _tkinter In-Reply-To: References: Message-ID: <45a5da47$0$32703$9b622d9e@news.freenet.de> Sorin Schwimmer schrieb: > *** WARNING: renaming "_tkinter" since importing it > failed: libtk8.4.so: cannot open shared object file: > No such file or directory > running build_scripts > > I have libtk: > > # ls -l /usr/local/lib/libtk8.4.so > -r-xr-xr-x 1 root root 906285 Jan 10 16:08 > /usr/local/lib/libtk8.4.so > > I need Tkinter for sure, and I'll like to have dbm. > How should I proceed? Did you add /usr/local/lib to /etc/ld.so.conf? Regards, Martin From nagle at animats.com Tue Jan 23 20:50:37 2007 From: nagle at animats.com (John Nagle) Date: Wed, 24 Jan 2007 01:50:37 GMT Subject: Python does not play well with others Message-ID: The major complaint I have about Python is that the packages which connect it to other software components all seem to have serious problems. As long as you don't need to talk to anything outside the Python world, you're fine. But once you do, things go downhill. MySQLdb has version and platform compatibility problems. So does M2Crypto. The built-in SSL support is weak. Even basic sockets don't quite work right; the socket module encapsulates the timeout mechanism but doesn't get it right. In the Perl, Java, PHP, and C/C++ worlds, the equivalent functions just work. That's because, in those worlds, either the development team for the language or the development team for the subsystem takes responsibility for making them work. Only Python doesn't do that. Python has been around long enough that this should have been fixed by now. John Nagle From DouhetSukd at gmail.com Sat Jan 6 01:23:19 2007 From: DouhetSukd at gmail.com (DouhetSukd at gmail.com) Date: 5 Jan 2007 22:23:19 -0800 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: <1168064599.558820.9410@42g2000cwt.googlegroups.com> Wise choice + welcome to the club. Though Python is open source and well appreciated on Linux, I think you will find that most people in this newsgroup will be fairly courteous about _your_ choice of platform. Some will not know about the weird process forking stuff on windows and helpfully suggest that 'if you were to use a real OS...'. But in reality Python is just as happy on XP as on Linux and the lack of scripting/shell alternatives on XP makes it all the more useful there. The only real XP drawback is that Python is not bundled on Windows, while it is included with OS X and most (all?) Linux distros. So, giving a *.py program to another XP user means little by itself, it needs to be either packaged in an exe (see py2exe) or you need to get your buddy to install python on their machine. In descending order of cheapness/usefullness. 1. download python + work through the tutorial. well, maybe not all of it, but with pythonwin around, you can try out significant snippets quickly. 2. use any ol' text editor that _you_ are familiar with, save to file, and python under DOS. later on you can always pick an editor. i prefer eclipse + pydev, yes, even on windows. personally, i find pythonwin _great_ to test out code interactively, mediocre to write lots of code with and occasionally handy to debug code in. if you hate typing python under DOS, then I guess you will have to run programs from pythonwin. 3. internet this newsgroup is very informative. dive into python, pretty good net resource www.diveintopython.org 4. books: Learning Python, isbn 0596002815, is pretty good. Python Programming on Win32, isbn 1565926218, is good, if a bit dated (2000, covers COM but no .Net) In depth Python - Python in a Nutshell, isbn 0596100469 5. GUI stuff. wxPython. If, like me, you hate handcoding everything and want a VB drag&drop clone you will have to look around for someone else's advice - there are several such editors that do wxPython but I have never found anything entirely to my liking. I am sure others will chime in with their recommendations. 6. Database stuff. Personally, working on MS SQL, I vouch for mxODBC - shareware, which I used for years without paying, until I decided the guy had definitely earned my $75. http://www.egenix.com/files/python/eGenix-mx-Extensions.html 7. Prepping *.py programs for distribution to users w.o. Python py2exe - www.py2exe.org/ Best o' luck. From maksim.kasimov at gmail.com Mon Jan 15 11:12:12 2007 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Mon, 15 Jan 2007 18:12:12 +0200 Subject: __getattr__ equivalent for a module Message-ID: Hi, in any python class it is possible to define __getattr__ method so that if we try to get some value of not actually exists instance attribute, we can get some default value. For example: class MyClass: def __getattr__(self, attname): if attname.startswith('a'): return "*" i = MyClass() ... i.aValue # it gives "*" if "i.aValue" will not be set before this call i need to define the same behavior for a module: import mymodule mymodule.anyattribute or from mymodule import anyattribute "anyattribute" is not actually defined in the module, but gives some attribute of the module so my question is: how to tune up a module get default attribute if we try to get access to not actually exists attribute of a module? (python 2.4 or 2.2) many thanks for help. -- Maksim Kasimov From jonc at icicled.net Sat Jan 6 05:02:25 2007 From: jonc at icicled.net (Jonathan Curran) Date: Sat, 6 Jan 2007 04:02:25 -0600 Subject: python, zlib, and fedora 64bits In-Reply-To: <94bdd2610701060147i6725e52bgdcc3d81377366ecd@mail.gmail.com> References: <94bdd2610701060147i6725e52bgdcc3d81377366ecd@mail.gmail.com> Message-ID: <200701060402.25665.jonc@icicled.net> On Saturday 06 January 2007 03:47, Tarek Ziad? wrote: > Hello, > > I am trying to compile Python on a Fedora 64bits, and I can't make zlib > work. > > a python setup.py build leads to : > > ... > building 'zlib' extension > gcc -pthread -shared > build/temp.linux-x86_64-2.4/usr/local/src/Python-2.4.4/Modules/zlibmodule.o > -L/opt/python-2.4.4/lib -L/usr/local/lib -lz -o build/lib.linux-x86_64-2.4 > /zlib.so > /usr/bin/ld: /usr/local/lib/libz.a(crc32.o): relocation R_X86_64_32 against > `a local symbol' can not be used when making a shared object; recompile > with -fPIC > /usr/local/lib/libz.a: could not read symbols: Bad value > collect2: ld gab 1 als Ende-Status zur?ck > running build_scripts > running install_lib > ... > > I've tried to recompile zlib, but didn't find any way to avoid this error > > any ideas ? > > Otherwise, does anyone has a zlib.so for fedora 64bits to send me ? > > Thx > > Tarek Tarek, I would first check and see if fedora offers python for a 64-bit environment. If so, it would be easier to get python up and running quickly. I haven't used any redhat deviant in a while, but I think the command should be: yum search python. This should bring up a list of packages that are installable. The rest should be simple as: yum install . I hope this helps. - Jonathan From bdesth.quelquechose at free.quelquepart.fr Mon Jan 8 15:38:03 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Jan 2007 21:38:03 +0100 Subject: Working with Excel inside Python In-Reply-To: <1168256052.090472.54890@s80g2000cwa.googlegroups.com> References: <1168205727.130771.257030@51g2000cwl.googlegroups.com> <1168218370.688414.171150@s80g2000cwa.googlegroups.com> <1168256052.090472.54890@s80g2000cwa.googlegroups.com> Message-ID: <45a2a563$0$291$426a74cc@news.free.fr> AleydisGP at gmail.com a ?crit : > Sorry for my little knowledge on Python. Actually my knowledge is > specific for automating geo-processing tasks within ESRI environment, > but sometimes I need to automate some other tasks (like this one) which > require more in-depth knowledge of this language. I would definitively not qualify function call syntax as "in-depth knowledge" > Lots of documentation are of no use when you don't know exactly what to > look for or have a wrong idea of what to do. http://docs.python.org/tut/tut.html From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 14:30:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 06:30:21 +1100 Subject: when format strings attack References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> <1169232233.469572.298320@a75g2000cwd.googlegroups.com> Message-ID: On Fri, 19 Jan 2007 10:43:53 -0800, John Zenger wrote: > Perhaps it is not as severe a security risk, but pure Python programs > can run into similar problems if they don't check user input for % > codes. Please don't top-post. A: Because it messes up the order that we read things. Q: Why? A: Top-posting. Q: What is the most annoying newsgroup habit? > Example: > >>>> k = raw_input("Try to trick me: ") > Try to trick me: How about %s this? >>>> j = "User %s just entered: " + k >>>> print j % "John" > Traceback (most recent call last): > File "", line 1, in ? > print j % "John" > TypeError: not enough arguments for format string That's hardly the same sort of vulnerability the article was talking about, but it is a potential bug waiting to bite. In a serious application, you should keep user-inputted strings separate from application strings, and never use user strings unless they've been made safe. See Joel Spolsky's excellent article about one way of doing that: http://www.joelonsoftware.com/articles/Wrong.html -- Steven. From manuel.graune at koeln.de Tue Jan 23 17:10:41 2007 From: manuel.graune at koeln.de (Manuel Graune) Date: Tue, 23 Jan 2007 23:10:41 +0100 Subject: Are there sprintf in Python??? References: <1169496238.925052.311660@l53g2000cwa.googlegroups.com> Message-ID: "questions?" writes: > Are there any sprintf in Python? > I know you can print to files(or redefine sys.stout) and later open the > file content. Are you looking for something like this? http://norvig.com/python-iaq.html or http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/112546 -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From tubby at bandaheart.com Mon Jan 29 09:06:27 2007 From: tubby at bandaheart.com (tubby) Date: Mon, 29 Jan 2007 09:06:27 -0500 Subject: pdf to text In-Reply-To: References: <86714$45b9254c$54d1d767$3741@news.chello.no> Message-ID: Dieter Deyke wrote: >> sout = os.popen('pdftotext "%s" - ' %f) > Your program above should read: > > sout = os.popen('pdftotext "%s" - ' % (f,)) What is the significance of doing it this way? From gherron at islandtraining.com Wed Jan 24 16:12:35 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 24 Jan 2007 13:12:35 -0800 Subject: Static variables In-Reply-To: References: Message-ID: <45B7CBC3.9030003@islandtraining.com> Florian Lindner wrote: > Hello, > does python have static variables? I mean function-local variables that keep > their state between invocations of the function. > > Thanks, > > Florian > Nope. Not really. In new versions of Python, functions and methods can have attributes that can be used like function level static variables. However, I usually use module level attributes for such things. Gary Herron From usenet200701 at tobyinkster.co.uk Sun Jan 28 09:38:08 2007 From: usenet200701 at tobyinkster.co.uk (Toby A Inkster) Date: Sun, 28 Jan 2007 14:38:08 +0000 Subject: Ip address References: <1169990510.352536.4760@a34g2000cwb.googlegroups.com> Message-ID: Steve Holden wrote: > There is absolutely no need to know the IP address of "your router" to > communicate with Internet devices. Either your IP layer is configured to > know the addresses of one or more routers, or it has discovered those > address by dynamic means, or you can't get off-net because there aren't > any routers. ... or you can't get off-net because you don't *know* the routers. -- Toby A Inkster BSc (Hons) ARCS Contact Me ~ http://tobyinkster.co.uk/contact Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux * = I'm getting there! From wise at hyperformix.com Thu Jan 11 14:32:46 2007 From: wise at hyperformix.com (Tim) Date: 11 Jan 2007 11:32:46 -0800 Subject: py2exe: zipfile=None raised ImportError Message-ID: <1168543966.212663.141840@i56g2000hsf.googlegroups.com> I'm at the end of my limited experience... I'm using py2exe to create an executable. I'm using bundle level 1. When I don't use the zipfile option, the executable and library.zip get created and the executable works correctly. When I add the zipfile=None option to put everything into the exe, the exe doesn't work. It raises an ImportError whose traceback is: File "...boot_common.py" ... no module name linecache File " ... no module named zipextimporter File "my.py" ... no module name optparse It looks like the imported modules are not being found in the zip, or something didn't get included that needed to be included. Does anybody know what's happening and how to fix it? Thanks. -- Tim From __peter__ at web.de Tue Jan 23 04:04:18 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Jan 2007 10:04:18 +0100 Subject: selective logger disable/enable References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> Message-ID: Gary Jefferson wrote: > Suppose I have 3 modules that belong to a project, 'A', 'A.a' and 'B', > and each module has its own logger, created with: > > module1logger = logging.getLogger('project.A') > > and > > module2logger = logging.getLogger('project.A.a') > > and > > module3logger = logging.getLogger('project.B') > > > And I want to selectively enable/disable these, per module (for > example, I only want logging from A and A.a, or just from B, etc). It > seems like logging.Filter is supposed to let me do this, but I can't > see how to apply it globally. Is there really no other way that to add > a addFilter(filter) call to each of these loggers individually? > > logging.basicConfig gets inherited by all loggers, but it doesn't seem > capable of giving a Filter to all loggers. Is there any way to do this? An alternative approach might be to set the 'propagate' flag: import logging def warn_all(loggers, message): for lgr in loggers: lgr.warn(message) logging.basicConfig() root = logging.getLogger() root.manager.emittedNoHandlerWarning = True loggers = [logging.getLogger(name) for name in """ alpha alpha.1 alpha.2 alpha.2.1 alpha.2.2 alpha.2.2.1 beta beta.1 beta.2 """.split()] warn_all(loggers, "all on") print "---" logging.getLogger("alpha").propagate = False warn_all(loggers, "alpha off") logging.getLogger("alpha").propagate = True print "---" logging.getLogger("alpha.2").propagate = False warn_all(loggers, "alpha.2 off") Peter From laurent.pointal at limsi.fr Thu Jan 11 03:11:20 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 11 Jan 2007 09:11:20 +0100 Subject: Print message with Colors In-Reply-To: <1168500252.143831.235250@i56g2000hsf.googlegroups.com> References: <1168500252.143831.235250@i56g2000hsf.googlegroups.com> Message-ID: prk a ?crit : > Hi Folks, > > Is there any procesure for print messages with colors. Yes, see: http://www.google.fr/search?q=python+print+color http://groups.google.fr/groups?as_q=python+print+color&num=100&as_ugroup=comp.lang.python See also ANSI escape sequences for the more general subject of color printing on terminals. From skip at pobox.com Wed Jan 31 11:41:54 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 31 Jan 2007 10:41:54 -0600 Subject: subway In-Reply-To: <5f56302b0701310802y7e45c98fmaaebe090e34d410@mail.gmail.com> References: <5f56302b0701310802y7e45c98fmaaebe090e34d410@mail.gmail.com> Message-ID: <17856.50898.477998.112022@montanaro.dyndns.org> Daniel> Does anyone know what has happened to the codebase of the subway Daniel> project? It seems the whole project has been shut down leaving Daniel> no trace of the code on net but I would be very happy to see it, Daniel> apparently it had some cool features that would be fun to look Daniel> at. Does anyone have access to the code and/or is willing to Daniel> make it publically available? No guarantee that it will have any remnants of the subway project, but the Wayback Machine might be a good place to start: http://web.archive.org/web/*/http://subway.python-hosting.com Skip From salvatore.difazio at gmail.com Mon Jan 15 15:20:16 2007 From: salvatore.difazio at gmail.com (Salvatore Di Fazio) Date: 15 Jan 2007 12:20:16 -0800 Subject: Watch log Message-ID: <1168892415.324184.273210@l53g2000cwa.googlegroups.com> Hi guys, I've an application that writes a log file. I need to write an application with python that will read this file. I would like wait until a new line will be write in the file. Something like the "watch cat Log" command on Linux os. How can I check the eof and restart the reading? From wolf_tracks at invalid.com Wed Jan 24 15:57:03 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 24 Jan 2007 20:57:03 GMT Subject: Beginners Tutorial in PDF Format? In-Reply-To: References: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net><1169415358.277431.130640@s34g2000cwa.googlegroups.com> Message-ID: Gabriel Genellina wrote: > "W. Watson" escribi? en el mensaje > news:FJTsh.36658$Gr2.32367 at newssvr21.news.prodigy.net... > Robert Hicks wrote: >> W. Watson wrote: >>> I'd like to print a tutorial in one fell swoop, but it seems most on the >>> various sites are page by page embedded descriptions in the page. Any >>> available as a pdf? >> >> http://docs.python.org/download.html >> >> http://www.diveintopython.org/ >> >> Thanks, but the first url takes me to a web page that contains the >> complete >> tutorial. Does choosing pdf (USA) in the table download a file that >> contains >> all the documents on the list below and to the left? > > Try again. The first url goes to this page: > Download Python 2.5 Documentation (19 September 2006): To download an > archive containing all the documents for this version of Python in one > of various formats [pdf included, you can choose between Letter/A4]. > Below, it says "These documents are not available for download > individually." > There is nothing there with the title "Python 2.5 Documentation". Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Depend upon it, there is nothing so unnatural as the commonplace." -- Sherlock Holmes, in "A Case of Identity" -- Web Page: From tgrav at mac.com Tue Jan 23 11:54:46 2007 From: tgrav at mac.com (Tommy Grav) Date: Tue, 23 Jan 2007 11:54:46 -0500 Subject: Reading character from keyboard Message-ID: <9936C600-45F0-4A0F-96CE-31A298DFC0DF@mac.com> A very simple question. I would like to read a single character from the keyboard (y or n). I have tried to look in my Python books and a google search, but have come up empty. I am sure the info s out there, but I guess I am unable to find the right question or search keyword :o/ Any hints or help appreciated Cheers Tommy From george.sakkis at gmail.com Thu Jan 11 12:19:30 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 11 Jan 2007 09:19:30 -0800 Subject: Fixed keys() mapping Message-ID: <1168535970.585977.317760@p59g2000hsd.googlegroups.com> I wrote an 'fkdict' dict-like class for mappings with a fixed set of keys but I'm wondering if there's a simpler way to go about it. First off, the main motivation for it is to save memory in case of many dicts with the same keys, for example when reading from a csv.DictReader or constructing dicts out of rows fetched from a database. For example, test_mem(dict) takes up around 246 MB according to the Windows task manager while test_mem(fkdict) takes around 49 MB: def test_mem(maptype): d = [(i,str(i)) for i in range(1000)] ds = [maptype(d) for i in xrange(10000)] raw_input('finished') An additional benefit is predictable ordering (e.g. fkdict.fromkeys('abcd').keys() == list('abcd')), like several ordered-dict recipes. The implementation I came up with goes like this: each fkdict instance stores only the values as a list in self._values. The keys and the mapping of keys to indices are stored in a dynamically generated subclass of fkdict, so that self._keys and self._key2index are also accessible from the instance. The dynamically generated subclasses are cached so that the second time an fkdict with the same keys is created, the cached class is called. Since the keys are determined in fkdict.__init__(), this scheme requires changing self.__class__ to the dynamically generated subclass. As much as I appreciate Python's dynamic nature, I am not particularly comfortable with objects that change their class and the implications this may have in the future (e.g. how well does this play with inheritance). Is this a valid use case for type-changing behavior or is there a better, more "mainstream" OO design pattern for this ? I can post the relevant code if necessary. George From mr.galien at gmail.com Tue Jan 23 06:05:53 2007 From: mr.galien at gmail.com (Sang Kim) Date: Tue, 23 Jan 2007 20:05:53 +0900 Subject: Try to porting Python2.5 to Zaurus Message-ID: <40bc31da0701230305p350a30b9p86dc6c8bcb317ffb@mail.gmail.com> Glad to see another Zaurus lovin' Pythonite. ;-) and also thanks to you.... -------------- next part -------------- An HTML attachment was scrubbed... URL: From tarique2006 at aol.com Mon Jan 8 10:39:10 2007 From: tarique2006 at aol.com (Tarique) Date: Mon, 08 Jan 2007 21:09:10 +0530 Subject: Books,resources.. Message-ID: Hi all! i am new to this group and starting out with python as well.i have programming experience in 'c' so can you please suggest some standard references for python considering that i have some programming experience (though c is quite unrelated i guess) From __peter__ at web.de Mon Jan 8 03:42:34 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Jan 2007 09:42:34 +0100 Subject: how to find the longst element list of lists References: <45a1b4da$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Dan Sommers wrote: >> ... >> longest_list, longest_length = list_of_lists[ 0 ], len( longest_list >> ) for a_list in list_of_lists[ 1 : ]: >> a_length = len( a_list ) >> if a_length > longest_length: >> longest_list, longest_length = a_list, a_length >> will run faster than sorting the list just to pick off one element (O(n) >> vs. O(n log n) for all of you Big-Oh notation fans out there; you know >> who you are!). > > Or, more succinctly, after: > list_of_lists = [["q", "e", "d"], > ["a", "b"], > ["a", "b", "c", "d"]] > You can find the longest with: > maxlength, maxlist = max((len(lst), lst) for lst in list_of_lists) > or (for those pre-2.5 people): pre-2.4 > maxlength, maxlist = max([(len(lst), lst) for lst in list_of_lists]) With the caveat that if there are lists of equal length their items will be compared: >>> max((len(lst), lst) for lst in [[1], [1j]]) Traceback (most recent call last): File "", line 1, in TypeError: no ordering relation is defined for complex numbers So if you want the first out of the lists with equal length on a python where Steve's enhancement is not yet available (pre-2.5): >>> max_len, dummy, max_list = max((len(lst), -i, lst) for i, lst in enumerate([[1], [1j]])) >>> max_len, max_list (1, [1]) Peter From nono at hotmail.com Mon Jan 1 12:38:14 2007 From: nono at hotmail.com (Osiris) Date: Mon, 01 Jan 2007 18:38:14 +0100 Subject: BOOST again: how to proceed from here.... Message-ID: I'm trying to work with Boost, trying to use my C-code from Python.. So now I have generated a C_test2.dll and a C_test2.lib with Visual C++ 2005, from code like this: =============== #include #include namespace { // Avoid cluttering the global namespace. int my_int; /* a global integer: or outside namespace ? */ double calc ( double f) { my_int = (int) (f/2); // printf( "Half of %f is %d\n", f, my_int ); return f/2; } } #include using namespace boost::python; BOOST_PYTHON_MODULE( half ) { def("calc", calc ); } ===================== Now I want to use calc from Python. I have my Python in c:\python24\ (IDLE system, version 2.4.4) Where do I put the dll and lib ? in c:\python24\libs and c:\python24\DLLs ? and do I import like: import C_test2.dll ? because now I get this: Traceback (most recent call last): File "", line 1, in -toplevel- import C_test2.dll ImportError: DLL load failed: The specified module could not be found. From martin at v.loewis.de Sun Jan 7 19:16:40 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 08 Jan 2007 01:16:40 +0100 Subject: (newbie) Is there a way to prevent "name redundancy" in OOP ? In-Reply-To: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> References: <72c2a$459ea268$d443bb3a$20196@news.speedlinq.nl> Message-ID: <45A18D68.5020308@v.loewis.de> Stef Mientki schrieb: > Can this be achieved without redundancy ? You can use the registry design to use the object's name also to find the object. In the most simple way, this is registry = {} class pin: def __init__(self, name): registry[name] = self self.name = name pin('aap') print registry['aap'] Using computed attribute names, you can reduce typing on attribute access: class Registry: pass registry = Registry() class pin: def __init__(self, name): setattr(registry, name, self) self.name = name pin('aap') print registry.aap If you want to, you can combine this with the factory/singleton patterns, to transparently create the objects on first access: class Registry: def __getitem__(self, name): # only invoked when attribute is not set r = pin(name) setattr(self, name, r) return r registry = Registry() class pin: def __init__(self, name): self.name = name print registry.aap HTH, Martin From Barry.Carroll at psc.com Fri Jan 5 19:27:04 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 5 Jan 2007 16:27:04 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A64@eugsrv400.psc.pscnet.com> Greetings: Please forgive me if this is the wrong place for this post. I couldn't find a more acceptable forum. If there is one, please point me in the right direction. I am part of a small team writing a table-driven automated testing framework for embedded software. The tables, which contain rows of keywords and data that drive the testing, are stored as plain-text "Comma-Separated Value" or .csv files. Each table can call other tables, which means that multiple files may be open at a time. The framework includes a Parser class. The program takes the name of the top-level table as a parameter, creates an instance of the Parser and passes the table name to it. The Parser instance opens the .csv file with that name, reads each line of the file (row of the table) and takes the appropriate action. When it encounters a row referencing another table, it creates a new Parser instance and passes it the name of the new table, suspending its own operation until the new Parser instance completes. In this way, a tree of Parser instances is created, each with a single open file object. (BTW, recursive and circular references are not allowed.) When each Parser instance comes to the end of its table, the instance is explicitly destroyed, presumably destroying any objects it holds, AND closing its open file. Because of the nature of the framework and the testing we do, this Parser tree never gets very tall: four or five levels at the most. The same table may be invoked dozens or hundreds of times, however, with different sets of data each time. This is where things go wrong. After about 500 table invocations, the framework starts refusing to process any more tables, responding with the following error: [Errno 24] Too many open files: 'HostCommandDevNotReady.csv' We can correct the behavior by explicitly closing each Parser's table file object before exiting the Parser code. This indicates that Python is failing to free up some file-related internal resource when the Parser object is destroyed. This behavior occurs on Python 2.3 and 2.4 for Windows, but not on Python 2.3 for Linux, and not on the Windows version of Python2.5. This is why I didn't just post a report to Bug Tracker: the problem seems to have been fixed. I did search through the archive of Windows related bugs, but found no mention of this type of a bug. What I want to know is: * has anyone else encountered a problem like this, * how was the problem corrected, * can the fix be retro-fitted to 2.5 and 2.4? Thanks in advance for any information you can provide. Regards, ? Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From no-spam at no-spam-no-spam.invalid Wed Jan 3 14:55:53 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 03 Jan 2007 20:55:53 +0100 Subject: A python library to convert RTF into PDF ? In-Reply-To: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> References: <1167846487.943390.192130@a3g2000cwd.googlegroups.com> Message-ID: leonel.gayard at gmail.com wrote: > Hi, > > Does anyone know a good python library to convert a RTF file into PDF ? > > This should be done automaticaly: I have a web page that takes some > values and inserts them into a RTF template, resulting in an RTF file. > However, I cannot send the output back to the user in RTF, it must be > sent in PDF instead, so I need to convert the result. > > So, what library can I use to convert from RTF to PDF ? GPL / BSD > Libraries are welcome. > Don't know a mere self-contained job. But probably then you are on a Windows - print the RTF through Word (win32com/ctypes) or through a RichEdit control into a .ps then convert via ghostscript/ps2pdf into a pdf. (gs obviously doesn't know RTF by default or at all...) Robert From http Wed Jan 17 16:46:29 2007 From: http (Paul Rubin) Date: 17 Jan 2007 13:46:29 -0800 Subject: Units of measurement Message-ID: <7x8xg1xr62.fsf_-_@ruckus.brouhaha.com> I'm sure this has been done before, but it just struck my fancy, an example of Python's "emulating numeric types", inspired by the old Unix "units" utility, and the Frink language. The language reference for these features is somewhat unclear and I'll enter some sourceforge items. Maybe I'll write a calculator-with-units around it. If I were really industrious, I'd attempt a Frink-like interpreter, but don't hold your breath. ================================================================ try: set except NameError: from sets import Set as set # python 2.3 ... class Unit: def __init__(self, coef, dimensions): self.dimensions = dimensions self.coef = coef def __add__(self, other): if self.dimensions != other.dimensions: raise TypeError, ('dimension mismatch', self, other) return Unit(self.coef + other.coef, self.dimensions) def __sub__(self,other): return self + (-1.0) * other def __rmul__(self, x): return x*self def __rdiv__(self, x): return x/self def __mul__(self, other): pc = self.coef * other.coef sd, od = self.dimensions, other.dimensions basis = set(sd.keys()) | set(od.keys()) pa = [(d, sd.get(d,0)+od.get(d,0)) for d in basis] pd = dict([(d,a) for d,a in pa if a != 0]) return Unit(pc, pd) def __repr__(self): a = [repr(self.coef)] for d,c in self.dimensions.iteritems(): s = str(d) if c != 1: s += '^'+str(c) a.append(s) return '*'.join(a) def __div__(self, other): od = other.dimensions inv = Unit(1.0 / other.coef, dict([(d, -od[d]) for d in od])) return self * inv def __pow__(self, n): n = n.coef if self.dimensions and type(n) not in (int,long): raise TypeError, ('exponent must be integer', self,n) cn = self.coef ** n sd = self.dimensions return Unit(self.coef ** n, dict([(d,sd[d]*n) for d in sd])) def __coerce__(self, other): if isinstance(other, Unit): return self, other return self, Unit(other, {}) def __float__(self): if self.dimensions: raise TypeError, ('unit must be dimensionless for float cast', self) return float(self.coef) def __int__(self): return int(float(self)) def base_unit(name): return Unit(1.0, {name : 1}) meter = base_unit('m') second = base_unit('s') kg = base_unit('kg') coulomb = base_unit('coulomb') centimeter = meter / 100 inch = 2.54 * centimeter foot = ft = 12 * inch mile = 5280*foot minute=60*second hour=60*minute speed_limit = 55 * mile / hour furlong = mile / 8 day = 24 * hour fortnight = 14 * day # could include more units but you get the idea c = 186282*mile/second print 'speed of light =', c/(furlong/fortnight), 'furlongs per fortnight' # ... From tubby at bandaheart.com Thu Jan 25 16:54:15 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 25 Jan 2007 16:54:15 -0500 Subject: pdf to text In-Reply-To: <86714$45b9254c$54d1d767$3741@news.chello.no> References: <86714$45b9254c$54d1d767$3741@news.chello.no> Message-ID: David Boddie wrote: > The pdftotext tool may do what you want: > > http://www.foolabs.com/xpdf/download.html > > Let us know how you get on with it. I have used this tool. However, I need PDF read ability on Windows and Linux and in the future Macs. pdftotext works great on Linux, but poorly on Windows (100% sustained CPU usage, etc). Thank you for the suggestion. I'll keep hammering away at a simple Python solution to this. Over the years, I have come to loath Adobe's Portable Document Format! From martin at v.loewis.de Thu Jan 4 03:28:56 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 04 Jan 2007 09:28:56 +0100 Subject: When argparse will be in the python standard installation In-Reply-To: References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> <459C008D.5040404@v.loewis.de> Message-ID: <459CBAC8.9060007@v.loewis.de> Steven Bethard schrieb: > If someone has an idea how to include argparse features into optparse, > I'm certainly all for it. But I tried and failed to do this myself, so I > don't know how to go about it. It's not necessary that the implementation is retained, only that the interface is preserved. So if you can come up with an implementation that supports all optparse applications, and adds the additional features, your implementation could replace the current optparse. If you need to make incompatible changes, it would be best if you could produce a list of such changes, so that optparse users can review them to find out whether they are affected. Regards, Martin From larry.bates at websafe.com Thu Jan 11 18:33:17 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 11 Jan 2007 17:33:17 -0600 Subject: Newbie question: SMTP -> SQL Server In-Reply-To: References: <1168529572.873867.207730@k58g2000hse.googlegroups.com> <1168531934.015865.177100@i56g2000hsf.googlegroups.com> Message-ID: <45A6C93D.4060605@websafe.com> Steve Holden wrote: > jrpfinch wrote: >> Thank you. I have just realised I completely misunderstand how SMTP >> servers work. From what I can tell, when you run the cookbook script >> it listens locally on port 8025. >> >> You then have to configure a Linux (in my case) account with a username >> and password so my external piece of software (on another Windows >> machine) can log in and use the SMTP server. >> >> Then I write the some code in the cookbook example to redirect any mail >> content to the MS SQL server database. >> >> Note that the external piece of software can only talk SMTP - this is >> why I am having to develop this script. >> >> Does this sound sensible? Any tips on how to configure my Linux box (I >> don't have much experience with Linux either)? >> >> Many thanks >> >> Jon >> > Presumably you can configure the external piece of software at least to > the extent of setting the email address it delivers to? > > In that case it will be *much* simpler to set up an account on a mail > server to receive these emails. That way the server will be available > whenever the SMTP-based sender wants or needs to send mail, and you can > use Python to collect the emails in batched using the POP protocol, as a > client. > > Once you receive the email messages then yes, it's perfectly practical > to save the content in a SQL server database. mxODBC is one possible > driver package (though it requires you to purchase a license for > commercial use), and I seem to remember there's another one called > adodbapi that is open source. There are almost certainly others, but > it's a while since I used SQL Server with Python. > > regards > Steve Good advice. BTW-You can use dbi and odbc modules to work with SQL server without purchasing anything. From http Tue Jan 2 10:37:19 2007 From: http (Paul Rubin) Date: 02 Jan 2007 07:37:19 -0800 Subject: Newbie query about secure embedded python References: Message-ID: <7xbqlhh234.fsf@ruckus.brouhaha.com> Richard Dwan writes: > My question is; is there a secure python interpreter > that prevents malicious code from using C/C++ modules > or built-in functions from causing damage to a users > system. You mean like a java sandbox? There used to be one in Python (the rexec/Bastion modules) but they were removed for security reasons (i.e. they weren't secure and there was no way to fix the holes). There seems to currently be no really reliable way to do what you're asking. Your best bet may be either a small JVM, or a very limited special purpose language that you could implement in Python. From massimo.scamarcia at gmail.com Wed Jan 31 04:24:27 2007 From: massimo.scamarcia at gmail.com (skam) Date: 31 Jan 2007 01:24:27 -0800 Subject: data design In-Reply-To: <1170183985.871094.155720@q2g2000cwa.googlegroups.com> References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> Message-ID: <1170235467.666502.270250@l53g2000cwa.googlegroups.com> On Jan 30, 8:06 pm, "Paddy" wrote: > > Google for YAML and JSON formats too > YAML and JSON are good when used as data-interchange format, not as configuration files. These formats are too complex for non-programmers, so they will ask aid for every editing ;) I suggest ini-like files, parsed using ConfigParser, but you should have a look to ConfigObj that has got automatic type conversion and other interesting features From buzzard at urubu.freeserve.co.uk Mon Jan 15 22:57:14 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 16 Jan 2007 03:57:14 +0000 Subject: Python web app. (advice sought) In-Reply-To: <45aae51b.0@entanet> References: <45aae51b.0@entanet> Message-ID: <45ac5225.0@entanet> Thanks all. It's looking like Turbogears at the moment (unless my boss makes an executive decision). Cheers. Duncan From gagsl-py at yahoo.com.ar Thu Jan 25 00:35:46 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Jan 2007 02:35:46 -0300 Subject: Using Timing function problem..... In-Reply-To: <1169699160.119721.9750@v45g2000cwv.googlegroups.com> References: <1169699160.119721.9750@v45g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070125023344.04521b08@yahoo.com.ar> At Thursday 25/1/2007 01:26, kevin wrote: >Hi... I'm having a few problems here... >I want to input in my function different values and then time each one >to see how long it took to run the function... so right now it doesn't >like the "i" inside my function fibonacci(i) but if I put a constant >it's fine.... You have to build the right *string* to be evaluated... >for i in (range(1,30)): > mytime1 = timeit.Timer( 'fibonacci(i)', 'from prl1 import >fibonacci' ) for i in (range(1,30)): mytime1 = timeit.Timer( 'fibonacci(%d)' % i, 'from prl1 import fibonacci' ) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nanjundi at gmail.com Mon Jan 22 20:16:35 2007 From: nanjundi at gmail.com (Nanjundi) Date: 22 Jan 2007 17:16:35 -0800 Subject: Getting to an SSH account over a HTTP proxy In-Reply-To: References: Message-ID: <1169514995.916358.17030@11g2000cwr.googlegroups.com> BJ?rn Lindqvist wrote: > I want to use Python to connect to a SSH account over a HTTP proxy to > automate some operations. I thought paramiko would be able to do that, > but it can not (it seems). > > Is there some other Python module that can do what I want? > > -- > mvh Bj?rn Did you take a look at twisted library? twistedmatrix.com http://twistedmatrix.com/projects/core/documentation/howto/clients.html I haven't tried to connect over port 80, but its worth a try. -N From gagsl-py at yahoo.com.ar Fri Jan 26 02:57:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Jan 2007 04:57:17 -0300 Subject: Prefered install method? In-Reply-To: References: Message-ID: <7.0.1.0.0.20070126044434.044f1bf8@yahoo.com.ar> At Friday 26/1/2007 04:27, Tina I wrote: >So my question is; What is the preferred/ common way to install a python >application so it's not really distro specific? And are there any good >resources on this on the web? distutils, included in the standard Python library. You surely have the docs installed, anyway you can read it online at http://docs.python.org/dist/dist.html For the simplest case (your app only contains python modules) just write a setup.py file on the top directory of you application: from distutils.core import setup setup(name='appname', version='1.0', py_modules=['foo', 'bar'], ) and execute: python setup.py sdist -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From pierre at saiph.com Tue Jan 30 10:52:43 2007 From: pierre at saiph.com (Imbaud Pierre) Date: Tue, 30 Jan 2007 16:52:43 +0100 Subject: data design In-Reply-To: <45BF5CC5.5060306@websafe.com> References: <45bf5763$0$22792$426a34cc@news.free.fr> <45BF5CC5.5060306@websafe.com> Message-ID: <45bf69cb$0$31452$426a74cc@news.free.fr> Larry Bates a ?crit : > Imbaud Pierre wrote: > >>The applications I write are made of, lets say, algorithms and data. >>I mean constant data, dicts, tables, etc: to keep algorithms simple, >>describe what is peculiar, data dependent, as data rather than "case >>statements". These could be called configuration data. >> >>The lazy way to do this: have modules that initialize bunches of >>objects, attributes holding the data: the object is somehow the row of >>the "table", attribute names being the column. This is the way I >>proceeded up to now. >>Data input this way are almost "configuration data", with 2 big >>drawbacks: >> - Only a python programmer can fix the file: this cant be called a >> configuration file. >> - Even for the author, these data aint easy to maintain. >> >>I feel pretty much ready to change this: >>- make these data true text data, easier to read and fix. >>- write the module that will make python objects out of these data: >>the extra cost should yield ease of use. >> >>2 questions arise: >>- which kind of text data? >> - csv: ok for simple attributes, not easy for lists or complex >> data. >> - xml: the form wont be easier to read than python code, >> but an xml editor could be used, and a formal description >> of what is expected can be used. >>- how can I make the data-to-object transformation both easy, and able >> to spot errors in text data? >> >>Last, but not least: is there a python lib implementing at least part >>of this dream? > > > Use the configurations module. It was built to provide a way to parse > configuration files that provide configuration data to program. It is > VERY fast so the overhead to parse even thousands of lines of config > data is extremely small. I use it a LOT and it is very flexible and > the format of the files is easy for users/programmers to work with. > > -Larry Bates U mean configParser? Otherwise be more specific (if U dont mind...) From sturlamolden at yahoo.no Fri Jan 19 08:40:12 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 19 Jan 2007 05:40:12 -0800 Subject: how to mimik a main() function to start a program with entry point? In-Reply-To: References: Message-ID: <1169214012.583356.193160@v45g2000cwv.googlegroups.com> krishnakant Mane wrote: > I have a set of modules in my package and out if which one is my > actual starting point to my entire program. say for example I have an > entire database application ready and I want a main (as in java or c) > to initiate the program and may be bring up a login screen and then > pass the control on to the main window. > if I am giving raw source code that is easy because I will tell user > to run the command ./xyz.py which has that function. > but if I freze it into an executable with py2exe for example , how do > I solve this problem? If you cannot figure that out, you should not selling software. if __name__ == '__main__': #whatever From nogradi at gmail.com Tue Jan 16 03:37:48 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 16 Jan 2007 09:37:48 +0100 Subject: installing/maintaining modules for multiple versions of python In-Reply-To: <1168924613.732835.83570@l53g2000cwa.googlegroups.com> References: <1168924613.732835.83570@l53g2000cwa.googlegroups.com> Message-ID: <5f56302b0701160037n66e849a2kd7cbae5c9be75570@mail.gmail.com> > I have a suse box that has by default python 2.4 running and I have a > 2.5 version installed > in /reg/python2.5. How do I install new modules for only 2.5 without > disturbing the 2.4 default > installation. If you do 'python2.5 setup.py install' on a new module supporting distutils it will only effect the 2.5 installation. If the new module has no setup.py you can just copy it to /reg/python2.5/site-packages and it will also only effect the 2.5 installation. HTH. From me at privacy.net Mon Jan 1 22:13:31 2007 From: me at privacy.net (Dan Sommers) Date: Mon, 01 Jan 2007 22:13:31 -0500 Subject: OO question References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> <1167639280.181587.242490@s34g2000cwa.googlegroups.com> <1167700159.792649.61210@a3g2000cwd.googlegroups.com> Message-ID: On 1 Jan 2007 17:09:19 -0800, fejkadress at hushmail.com wrote: > Lets say I have those two classes, Person and Address. How would one > implement the relationship between them? First, a Person can have one > or more addresses (or none), that could be represented as a list of > Addresses, right? But then, if I have an Address I want to see which > persons who live there, then I would have a list of Persons in each > Address. > Is this doubly-linked way of doing it a good way of doing it, or is > there a better "OO way" I haven't learned yet? I don't know about "a better OO" way, but one way is to model the various relationships as a list of (person, address) pairs: persons = [ Person( ), Person( ), Person( ) ] addresses = [ Address( ), Address( ), Address( ), Address( ) ] livesat = ((person[ 1 ], address[ 1 ]), (person[ 2 ], address[ 1 ]), (person[ 2 ], address[ 2 ])) worksat = ((person[ 1 ], address[ 3 ]), (person[ 2 ], address[ 4 ])) Then the list of people who live at address[ 1 ] is: [ (person, address) for (p, a) in livesat if a is address[ 1 ] ] But what about all the various relationships (lives at, works at, is known to have vandalized, etc.)? livesat = Relationship( "lives at" ) worksat = Relationship( "works at" ) vandalized = Relationship( "vandalized" ) information = ((person[ 1 ], address[ 1 ], livesat), (person[ 2 ], address[ 1 ], livesat), (person[ 2 ], address[ 2 ], livesat), (person[ 1 ], address[ 3 ], worksat), (person[ 2 ], address[ 4 ], worksat), (person[ 1 ], address[ 4 ], vandalized)) Now the list of people who live at address[ 1 ] is: [ (person, address) for (p, a, r) in information if a is address[ 1 ] and r is livesat ] (There are other ways, too, such as capturing one person and one address right inside a Relationship; someone with a more comp-sci-theoretical background than I have can probably tell you why or when one way might be better than the other.) The definitions of Person, Address, and Relationship, as well as the user-interface(s) and the persistent storage mechanism(s), are left as exercises to the interested reader. ;-) Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From duncan.booth at invalid.invalid Mon Jan 15 03:47:22 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Jan 2007 08:47:22 GMT Subject: How naive is Python? References: Message-ID: Roy Smith wrote: > All of those just move around pointers to the same (interned) string. Correct about the pointers, but the string is not interned: Steven D'Aprano wrote: >>>> s1 = foo() >>>> s2 = foo() >>>> s1 == s2, s1 is s2 > (True, True) > > So the string "This is a test" within foo is not copied each time the > function is called. However, the string "This is a test" is duplicated > between foo and foo2 (the two functions don't share the same string > instance): > >>>> s3 = foo2() >>>> s3 == s1, s3 is s1 > (True, False) > In this specific example the two functions don't share the same string, but that won't always be the case: if the string had been interned this would have printed (True, True). e.g. Removing all the spaces from the string produces a string which is interned. >>> def foo(): s = "Thisisatest" return s >>> def foo2(): return "Thisisatest" >>> s1 = foo() >>> s2 = foo2() >>> s1 is s2 True Bottom line, never make assumptions about when two literal strings will share the same object and when they won't. From paul at eventuallyanyway.com Sat Jan 27 01:03:07 2007 From: paul at eventuallyanyway.com (Paul Hummer) Date: Sat, 27 Jan 2007 06:03:07 +0000 Subject: help with subscription to a process In-Reply-To: <1169866318.333371.238530@a34g2000cwb.googlegroups.com> References: <1169866318.333371.238530@a34g2000cwb.googlegroups.com> Message-ID: <45BAEB1B.5040801@eventuallyanyway.com> The Python socket module, although lightweight, can be used to quickly establish a socket between client and server for the purpose of feeding data. I've done this once or twice with XML. If you are looking for something a bit more robust, might I suggest reading up on the Twisted libraries? Paul elrondrules at gmail.com wrote: > Hi > > I am new to python and hence need some help > > i have a process A that posts events as XML docs. > I need to create a listener to this process that subscribes to the > process A and as and when a XML doc is posted parse it. > I have creted an interface where if I specify the port number on which > the listener is running the process A will automatically start posting > events. > > The place I need help is to create a listener and a way of parsing the > XML docs. If you can give me some starting points or docs/resources > that will be great.. > > Thanks > > From Thomas.Ploch at gmx.net Fri Jan 5 12:55:03 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 18:55:03 +0100 Subject: Dividing integers...Convert to float first? In-Reply-To: <12pt3f3kc1jmcf8@corp.supernews.com> References: <1168017342.255981.134400@11g2000cwr.googlegroups.com> <459E8B5C.6020804@gmx.net> <12pt3f3kc1jmcf8@corp.supernews.com> Message-ID: <459E90F7.6080209@gmx.net> Grant Edwards schrieb: > On 2007-01-05, Jonathan Smith wrote: > >>>>> from __future__ import division >>>>> 1/2 >> 0.5 > > $ python > Python 2.4.3 (#1, Dec 10 2006, 22:09:09) > [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> from __future__ import LotteryNumbers > File "", line 1 > SyntaxError: future feature LotteryNumbers is not defined > >>> > > Damn. > > I guess it's back to work then. > You are working as an oracle? :-) Thomas From richardmartindwan at yahoo.co.uk Tue Jan 2 09:41:34 2007 From: richardmartindwan at yahoo.co.uk (Richard Dwan) Date: Tue, 2 Jan 2007 14:41:34 +0000 (GMT) Subject: Newbie query about secure embedded python Message-ID: <20070102144134.11373.qmail@web27612.mail.ukl.yahoo.com> (Originally incorrectly posted to C++ SIG mailing list) Hello, First let me apologise if this question is obvious - I've never embedded python before and I am deciding of it meets my needs. My question is; is there a secure python interpreter that prevents malicious code from using C/C++ modules or built-in functions from causing damage to a users system. My objective is to have an embedded interpreted language to drive all non CPU intensive application behaviour with user / downloadable scripts to customise the UI / scripting processing. My concern with a simply embedding python is that this would give arbitrary scripts the ability to make system level changes (e.g. destructive abilities using file access). As I wish to encourage scripts to be shared across the Internet this could not be tolerated. Python provides a very good script language to which I can expose application specific functions/objects using the already documented methods. To use Python with the above security restrictions I would need to be able to disable all file / system built-ins when running the interpreter across user scripts. In addition, importing C/C++ functions would have to be disabled as well. As a complication, a set of 'approved C/C++ functions' such as numpy would need to be supported in order to allow the user to do 'useful processing' within the scripts driving the application. My naive solution would be to customise the 'PyImport_Import' and 'PyObject_CallObject' routines used with user scripts so that: --- an imported C/C++ module would be checked against an approved list to prevent arbitrary C/C++ code from being executed --- built-in function calls would be checked against an approved list to prevent system damaging calls from being made --- the application API that is exposed to the user code must not expose to scripts a way of damaging anything more than the data currently being 'processed' --- the application would have to ensure that user code is only executed within the secure interpreter scope (e.g. not use callbacks to user script code outside the secure interpreter) Has the necessary secure python interpreter already been created / a work in progress? Many thanks for any advice you can give me, Richard Send instant messages to your online friends http://uk.messenger.yahoo.com From goodepic at gmail.com Thu Jan 4 16:37:50 2007 From: goodepic at gmail.com (goodepic) Date: 4 Jan 2007 13:37:50 -0800 Subject: Problem Running Working Code on Mac In-Reply-To: <1167946511.531632.41750@11g2000cwr.googlegroups.com> References: <1167946511.531632.41750@11g2000cwr.googlegroups.com> Message-ID: <1167946670.792574.151620@q40g2000cwq.googlegroups.com> Also, if it makes a difference, the lines quoted in the error message were actually written automatically by wxGlade. From __peter__ at web.de Wed Jan 31 11:00:43 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 Jan 2007 17:00:43 +0100 Subject: Regex with ASCII and non-ASCII chars References: <1170243969.504255.134100@v33g2000cwv.googlegroups.com> <1170257547.041535.20770@a75g2000cwd.googlegroups.com> Message-ID: TOXiC wrote: > Thx it work perfectly. > If I want to query a file stream? > > file = open(fileName, "r") > text = file.read() > file.close() Convert the bytes read from the file to unicode. For that you have to know the encoding, e. g. file_encoding = "utf-8" # replace with the actual encoding text = text.decode(file_encoding) > regex = re.compile(u"(???????)", re.IGNORECASE) > match = regex.search(text) > if (match): > result = match.group() > print result > WritePatch(fileName,text,result) > else: > result = "No match found" > print result > > It return "no match found" (the file contain the string "???????" > but...). > Thanks in advance for the help! Peter From nachogomez at gmail.com Fri Jan 26 22:05:59 2007 From: nachogomez at gmail.com (=?UTF-8?Q?Ra=C3=BAl_G=C3=B3mez_C.?=) Date: Fri, 26 Jan 2007 23:05:59 -0400 Subject: Getting the output from a console command while it's been generated! Message-ID: <684b0a740701261905o76ca3a9av6425b88cd1c3b9fc@mail.gmail.com> Hi everyone, I'm trying to make my apps more informative to the user, so I want to know if its possible to get the output of the execution of a console command while it's been generated, I mean, I want to get the output from commands.getstatusoutput('CMD') while CMD it's been executed and not wait until CMD have finished (because CMD take very long time to). Thanks for all Raul -------------- next part -------------- An HTML attachment was scrubbed... URL: From icius at comcast.net Sun Jan 21 03:11:31 2007 From: icius at comcast.net (icius) Date: 21 Jan 2007 00:11:31 -0800 Subject: SOAPpy and ArrayOfString Message-ID: <1169367091.902030.197480@m58g2000cwm.googlegroups.com> Hello all, I am trying to use a web services API with Python and SOAPpy as a client. Some of the method paramters in this web service's WSDL are asking for an "ArrayOfString" type. Here is my code so far: #!/usr/bin/python from SOAPpy import WSDL wsdlFile = 'http://localhost:8080/axis/services/USD_R11_WebService?WSDL' server = WSDL.Proxy(wsdlFile) server.soapproxy.config.dumpSOAPOut = 1 server.soapproxy.config.dumpSOAPIn = 1 SID = server.login('srvcdesk', 'xxxxxxxx') contacts = server.doSelect(SID, 'cnt', "userid = 'abeju01'", 1, ['last_name', 'first_name', 'userid']) I tried using a simple Python list for the argument that wants "ArrayOfString". Python generates the following XML for the last argument of the "doSelect" command above: last_name first_name userid The web service does not like this at all and returns the following error: SOAPpy.Types.faultType: class usdjws65.ArrayOfString): > I know in Perl I had to do some special gyrations to pass the right structue for ArrayOfString to this same web service. Is there any way to force a type in Python or any other ideas on how to do this? From mail at microcorp.co.za Mon Jan 8 06:12:37 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 8 Jan 2007 13:12:37 +0200 Subject: where is python on linux? References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com><45a157a0$0$289$426a74cc@news.free.fr> Message-ID: <01f801c73316$3d5dc100$03000080@hendrik> "rzed" wrote: >mmmmmmm... sloppy joes .... > >-- >rzed > >"A sandwich is a sandwich, but a Manwich is a meal." You eat people? - Hendrik From kj7ny at nakore.com Thu Jan 11 13:46:06 2007 From: kj7ny at nakore.com (kj7ny) Date: 11 Jan 2007 10:46:06 -0800 Subject: Is there a good example on instantiating, calling, using, an API from Python on Windows? Message-ID: <1168541166.457806.133320@p59g2000hsd.googlegroups.com> Is there a good example on instantiating, calling, using, etc., an API from Python? I need to use Python to talk to another system through that system's API's on Windows XP. Can you point me to documentation and/or a good example of Python using 3rd party API's? (Preferably a good example rather than just documentation.) And, can I do this from Python 2.4.# or should I try to learn how to use Iron Python? (By the way, if the examples could be for python 2.4.# it would be preferable.) Thanks, From wojciech_mula at poczta.null.onet.pl.invalid Mon Jan 8 13:55:10 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Mon, 8 Jan 2007 18:55:10 +0000 (UTC) Subject: More Efficient fnmatch.fnmatch for multiple patterns? References: <1168279822.921033.267210@v33g2000cwv.googlegroups.com> Message-ID: abcd wrote: > I am using fnmatch.fnmatch to find some files. The only problem I have > is that it only takes one pattern...so if I want to search using > multiple patterns I have to do something like.... > > patterns = ['abc*.txt', 'foo*'] > > for p in patterns: > if fnmatch.fnmatch(some_file_name, p): > return True > > ...is there a built-in function that will match using multiple patterns? import re pats = re.compile('|'.join(fnmatch.translate(p) for p in patterns)) if pats.match(some_file_name): return True w. From bborcic at gmail.com Thu Jan 25 19:22:03 2007 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 26 Jan 2007 01:22:03 +0100 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: <4866bea60701251102o6af055e1j2d85de2f30b64c64@mail.gmail.com> References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> <4866bea60701240736v837d246w187ecb1ccb90eefd@mail.gmail.com> <4866bea60701250609u61e72d30q21dd11c8c8fd9bcd@mail.gmail.com> <4866bea60701251102o6af055e1j2d85de2f30b64c64@mail.gmail.com> Message-ID: Chris Mellon wrote: >> Maybe. In any case, color separation solves my (sub)problem : the blue layer >> from the wx generated model matches the green layer from the app's window, pixel >> for pixel (at least with antialiasing and cleartype on, while writing black on >> white). >> > > That's... extremely interesting. Difficult to believe, you mean :) Well, you are right, somehow I mixed up layer colors; in the end I compare just the blue layers and it does what I wanted. Cheers, BB From adam at atlas.st Fri Jan 12 00:41:26 2007 From: adam at atlas.st (Adam Atlas) Date: 11 Jan 2007 21:41:26 -0800 Subject: Announcement -- ZestyParser In-Reply-To: <1168407920.281020.147680@k58g2000hse.googlegroups.com> References: <1168407920.281020.147680@k58g2000hse.googlegroups.com> Message-ID: <1168580486.921117.317630@v45g2000cwv.googlegroups.com> Thanks for the responses; you're right, and I have now posted the examples online. I just released version 0.6.0, by the way, which has several worthwhile improvements and much better documentation. It also includes an example for parsing RDF Notation3, to demonstrate a parsing task a bit more complex than the other examples. That's all posted at now. From 3dbernard at gmail.com Fri Jan 19 15:11:15 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 19 Jan 2007 15:11:15 -0500 Subject: pywin32 for Windows x64 Message-ID: <61d0e2b40701191211k6acce9ddvcf56f471214bfa6f@mail.gmail.com> Hello, Softimage has gracefully released an x64 build of the pywin32 extension, free for download. http://webrel2.softimage.com/open/products/xsi/v6/pywin32-207.win64-py2.4.exe (if that link doesn't work, go to http://www.softimage.com/downloads/XSI6_EssAdv/default.aspx, and look for Python 64) Cheers Bernard From steve at REMOVEME.cybersource.com.au Mon Jan 29 00:46:54 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 29 Jan 2007 16:46:54 +1100 Subject: sending a class as an argument References: <1170044663.163303.131930@v45g2000cwv.googlegroups.com> Message-ID: On Sun, 28 Jan 2007 20:24:23 -0800, manstey wrote: > Hi, > > Our class has its attributes set as classes, as in > > MyClass.Phone.Value='34562346' > MyClass.Phone.Private=True The Python convention is that classes have initial capitals (MyClass), instances do not, and nor do attribute names. I'm thinking you're doing this: class Phone: pass class MyClass: pass # now set a _class_ attribute -- all instances share this attribute MyClass.Phone = Phone() # attribute name is the same as a class Why do all instances of MyClass share the same phone number? I think that's a bad design. You should probably do this: # now set an _instance_ attribute instance = MyClass() instance.phone = Phone() Of course, in practice you'd do this in an __init__ method rather than as two separate lines: instance = MyClass() # automatically creates instance.phone Of course, I could be wrong -- you haven't really given enough information for me to be sure what you're doing. > Inside the MyClass definition we have a function like this: The word is "method", not function. Methods live in classes, functions outside. > def MyFunc(self,clsProperty): > if clsProperty.Private: > print 'Private property' > else: > print ClsProperty.Value If you have a whole lot of attributes with the same attribute (in this case, private), you should really be thinking about a more object-oriented design. As it stands now, your MyClass needs to know all the fundamental workings of your Phone class, your Name class, your Address class, etc. That's bad design. Your MyClass should just say "give me your value" and the Phone class should know that if it is private, it returns "private property". Etc. > In our code, we then call >>>> MyClass.MyFunc(MyClass.Phone) > > We want to be able in our code instead simply to call: >>>> MyClass.MyFunc(Phone) or MyClass.MyFunc('Phone') > > But we can't get it to work. If we rewrite the function as follows: > > def MyFunc(self,attr): > if self.attr.Private: > print 'Private' > else: > print self.attr.Value > > we get an error. Oooh, no don't tell us what it is, let me guess! I love guessing games! Does it crash your PC? Here's how I would do it. Each attribute should know how to "MyFunc" itself: give it a myfunc method. class Phone: def __init__(self, number, private=False): self.phonenumber = number self.private = private def myfunc(self): if self.private: return "private" else: return str(self.phonenumber) Now you can simplify your MyFunc method: def myfunc(self, attrname): """Delegate myfunc to the named attribute.""" return getattr(self, attrname).myfunc() Or not even bother, and just write MyClass.phone.myfunc(). -- Steven D'Aprano From NutJob at gmx.net Thu Jan 25 10:16:53 2007 From: NutJob at gmx.net (antred) Date: 25 Jan 2007 07:16:53 -0800 Subject: Python email parser In-Reply-To: <1169738001.643280.140880@a75g2000cwd.googlegroups.com> References: <1169738001.643280.140880@a75g2000cwd.googlegroups.com> Message-ID: <1169738213.327156.289200@l53g2000cwa.googlegroups.com> Hmm, I'm not sure whether I'd call 30 secs for 110 MB particularly slow. I mean that *IS* a lot of data. From bearophileHUGS at lycos.com Tue Jan 16 12:58:50 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Jan 2007 09:58:50 -0800 Subject: A note on heapq module In-Reply-To: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> Message-ID: <1168970329.751502.57320@11g2000cwr.googlegroups.com> I think the sort has to be simplified, otherwise it can't keep the heap invariant... def sort(self): self.h.sort() Bye, bearophile From James.w.Howard at gmail.com Fri Jan 19 12:42:04 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: 19 Jan 2007 09:42:04 -0800 Subject: Asyncore select statement problem In-Reply-To: References: <1169075120.491855.103200@q2g2000cwa.googlegroups.com> Message-ID: <1169228524.810461.51160@a75g2000cwd.googlegroups.com> Thank you for the responses. I have learned considerably more about how Asyncore works because of it. The problem that I see is that Asyncore's poll function does not seem to be thread safe. From what I can tell, I am calling dispatcher.close() properly and the dispatchers are removed from asyncore's global map (all except the server itself). However, it seems like the error happens when the poll function gets the file descriptors to run select on and then the thread ticks and removes them from the global map. After this the select call is made, but the file descriptors are not valid anymore. I guess I have two questions as a result. First, is this a problem that anyone else has had and second is there a fix for it? I have tried looking for Asyncore thread safe topics in Google, but without much luck. If needed I think making the poll function atomic in the asyncore module might fix this problem, but I wanted to see what other people thought first. Thanks again for the help, Jim Howard Gabriel Genellina wrote: > "JamesHoward" escribi? en el mensaje > news:1169075120.491855.103200 at q2g2000cwa.googlegroups.com... > > >I have a problem with python's asyncore module throwing a bad file > > descriptor error. The code might be difficult to copy here, but the > > problem is essentially: > > > > The server wants to sever the connection of an open Asyncore socket. > > Calling the socket.close() nor the socket.shutdown(2) calls seem to > > work. The only way I can close the connection without creating the > > error below is to have the client close the connection. > > You have to use the dispatcher's close() method, else, the asyncore map > won't be updated, keeping a reference to the closed socket. > > -- > Gabriel Genellina From nagle at animats.com Wed Jan 24 19:15:16 2007 From: nagle at animats.com (John Nagle) Date: Wed, 24 Jan 2007 16:15:16 -0800 Subject: The reliability of python threads In-Reply-To: References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> Message-ID: Carl J. Van Arsdall wrote: > Chris Mellon wrote: > >> On 24 Jan 2007 18:21:38 GMT, Nick Maclaren wrote: >> >> >>> [snip] >>> >>> >> >> >> I'm aware of the issues with the POSIX threading model. I still stand >> by my statement - bringing up the problems with the provability of >> correctness in the POSIX model amounts to FUD in a discussion of >> actual problems with actual code. >> >> Logic and programming errors in user code are far more likely to be >> the cause of random errors in a threaded program than theoretical >> (I've never come across a case in practice) issues with the POSIX >> standard. >> > > Yea, typically I would think that. The problem I am seeing is > incredibly intermittent. Like a simple pyro server that gives me a > problem maybe every three or four months. Just something funky will > happen to the state of the whole thing, some bad data, i'm having an > issue tracking it down and some more experienced programmers mentioned > that its most likely a race condition. Right. You're at MonteVista, which does real-time Linux systems and support. There will be people there who thoroughly understand thread issues. (I've used QNX for real time, but MonteVista has made progress since in recent years.) The Python thread documentation is kind of vague about how well the Python primitives are protected against concurrency problems. For example, do you have to protect basic types like lists and hashes against concurrent access? Is "pop" atomic? (It is in "dequeue", but what about regular lists?) Can you crash Python from within Python via concurrency errors? Does the garbage collector run concurrently or does it freeze all threads? What's different depending upon whether you're using real OS threads or simulated Python threads? John Nagle From george.sakkis at gmail.com Wed Jan 24 02:59:40 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 23 Jan 2007 23:59:40 -0800 Subject: numpy or _numpy or Numeric? In-Reply-To: References: Message-ID: <1169625580.411463.216040@s48g2000cws.googlegroups.com> On Jan 24, 2:24 am, auditory wrote: > I am a newbie here > > I am trying to read "space separated floating point data" from file > > I read about csv module by searching this group, > but I couldn't read space separated values with csv. > (which may be matter of course..) > > I also read about numpy.fromfile(file, sep=' ') which i can use. > but on my machine(ubuntu linux) numpy is unknown module, > which I didn't install by myself. > > While trying to install numpy accroding to its homepage. > (http://numpy.scipy.org/numpydoc/numdoc.htm). > i am quite confused. > > it's talking about the Numerical Python, > and it says to test whether it is installed or not, > try import Numeric instead of numpy. > > I got Nurmeric modules and > as a matter of fact i got a file named '_numpy.so' in lib directory. > > I can import _numpy but _numpy does not have 'fromfile' method > > My question is: > 1. Do i need to install numpy module? > 2. Then Is it different from Numeric module? > 3. Then where can i get it? > > 4. Or what is general way to read 'space separated values' from file? > > Thanks in advance. If *all* you need is to read a space-separated file with floating point values, installing numpy (or Numeric or numarray..) is an overkill; you can do it in one line in pure Python: matrix = [map(float, line.split()) for line in open('my_space_separated_file.txt')] This stores the values as a list of lists, each list corresponding to a row in the file. Depending on what you plan to do next with these numbers, this may or may not be the best way to go about it, but since you only mentioned the file reading part, we can't assume much. George From nmm1 at cus.cam.ac.uk Sat Jan 13 04:59:49 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 13 Jan 2007 09:59:49 GMT Subject: Rational Numbers References: Message-ID: In article , Steven D'Aprano writes: |> > |> > Some of the algebraic languages. (2/3)^(1/5) is held as such and |> > manipulated appropriately. |> > |> > Yes, I know that's "cheating" :-) |> |> I see your smiley, and I still don't understand. Why on earth would you |> call it cheating for a language to have a data type that is suitable for |> the data being used? Maybe it's a form of humour I don't get -- like |> pointing at a car and saying "Look, a cow!". Oh, because it's not a proper data type! The data type is an expression, and is held in a structured form, of which such powers may be one level. This is better regarded as an optimisation of a common case than a true data type. Now, there MAY be such a language that supports such things as a proper data type, but I don't know of one. Regards, Nick Maclaren. From GatlingGun at gmail.com Wed Jan 31 06:46:09 2007 From: GatlingGun at gmail.com (TOXiC) Date: 31 Jan 2007 03:46:09 -0800 Subject: Regex with ASCII and non-ASCII chars Message-ID: <1170243969.504255.134100@v33g2000cwv.googlegroups.com> Hello everybody. How I can do a regex match in a string with ascii and non ascii chars for example: regex = re.compile(r"(???????ty)", re.IGNORECASE) match = regex.search("???????ty") if match: result = match.group() print result else: result = "No match found" print result it return "no match found" even if the two string are equal. Help me please! Thx in advance :) From mal at egenix.com Thu Jan 11 18:04:44 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 12 Jan 2007 00:04:44 +0100 Subject: Summarizing data by week In-Reply-To: <1168372624.543712.149070@77g2000hsv.googlegroups.com> References: <1168372624.543712.149070@77g2000hsv.googlegroups.com> Message-ID: <45A6C28C.6020007@egenix.com> On 2007-01-09 20:57, Mike Orr wrote: > What's the best way to summarize data by week? I have a set of > timestamped records, and I want a report with one row for each week in > the time period, including zero rows if there are weeks with no > activity. I was planning to use ISO weeks because datetime has a > convenient .isocalendar() method, but I want each output row to have a > label like this: > > 2006 week 5 (Feb) > > However, to get the month (of the Thursday of that week) I have to > convert it back to an actual date,and I don't see a method to do that > in datetime or dateutil or mx.DateTime. You probably want to use mx.DateTime.ISO.WeekTime(): def WeekTime(year,isoweek=1,isoday=1,hour=0,minute=0,second=0.0): """Week(year,isoweek=1,isoday=1,hour=0,minute=0,second=0.0) Returns a DateTime instance pointing to the given ISO week and day. isoday defaults to 1, which corresponds to Monday in the ISO numbering. The time part is set as given. """ The ISO submodule has more APIs related to ISO weeks and the ISO date format in general: http://www.egenix.com/files/python/mxDateTime.html#ISO -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jan 12 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From aahz at pythoncraft.com Tue Jan 30 19:19:30 2007 From: aahz at pythoncraft.com (Aahz) Date: 30 Jan 2007 16:19:30 -0800 Subject: how to "free" an object/var ? References: Message-ID: In article , Stef Mientki wrote: > >If I create a large array of data or class, how do I destroy it (when >not needed anymore) ? You should be aware that releasing memory may not cause the size of your process to shrink -- many OSes keep memory assigned to an application for its lifetime. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From gh at ghaering.de Thu Jan 25 11:36:48 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 25 Jan 2007 17:36:48 +0100 Subject: sqlite user-defined functions & unicode issue In-Reply-To: <6282abf10701232123p306a85adq9ddf49f9ad2d56b8@mail.gmail.com> References: <6282abf10701232123p306a85adq9ddf49f9ad2d56b8@mail.gmail.com> Message-ID: Ben Wolfson wrote: > I've got a db some of whose elements have been created automatically > from filesystem data (whose encoding is iso-8859-1). If I try to > select one of those elements using a standard SQL construct, things > work fine: > [...] > > How can I get around this? I really want to be able to search by > regexp, and not just the standard SQL %-pattern. Looks like SQLite does not want to pass non-UTF8 strings to functions. The attached script shows that it does work with unicode and buffer (BLOB) parameters, but not with non-UTF8 strings. Text has to be encoded in UTF-8 in SQLite, it's just not enforced usually. Looks like SQLite enforces it here, though. Kind of ... -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: test_func.py Type: text/x-python Size: 650 bytes Desc: not available URL: From http Fri Jan 12 18:53:33 2007 From: http (Paul Rubin) Date: 12 Jan 2007 15:53:33 -0800 Subject: MP3 decoder module? References: <7x4pqvste8.fsf@ruckus.brouhaha.com> Message-ID: <7xac0ng5tu.fsf@ruckus.brouhaha.com> Paul Rubin writes: > Basically I want to write a program that takes an mp3 audio file and > finds the silent frames, with the idea of chopping the file into > segments at those points automatically, or compressing the silences > out of spoken audio to make it play faster without chipmunking up the > pitch, etc. Of course if you know of something that does this stuff > already, that can help too. I should add: I prefer not to expand the entire file to WAV and crunch on that. This is partly because I want to look for silences in specific places in the mp3 without having to decode the whole file, partly because I still need to know where the original mp3 frames are in the file. For the actual files I want to crunch, I don't need to handle VBR, but it would be nice to support it just from the point of view of doing things right. From e0427417 at student.tuwien.ac.at Tue Jan 9 13:37:36 2007 From: e0427417 at student.tuwien.ac.at (Mathias Panzenboeck) Date: Tue, 09 Jan 2007 19:37:36 +0100 Subject: Yield In-Reply-To: References: <1163610839.649860.263850@f16g2000cwb.googlegroups.com> <455b4f9f$1@usenet01.boi.hp.com> <1163659530.752607.120880@m73g2000cwd.googlegroups.com> <455c15ca$1@news.eftel.com> <455c1ddf@news.eftel.com> <1163691173.737911.130410@i42g2000cwa.googlegroups.com> Message-ID: <45a3e096$0$8024$3b214f66@tunews.univie.ac.at> Fredrik Lundh schrieb: > Danny Colligan wrote: > >> Carsten mentioned that generators are more memory-efficient to use when >> dealing with large numbers of objects. Is this the main advantage of >> using generators? Also, in what other novel ways are generators used >> that are clearly superior to alternatives? > > the main advantage is that it lets you decouple the generation of data > from the use of data; instead of inlining calculations, or using a pre- > defined operation on their result (e.g printing them or adding them to a > container), you can simply yield them, and let the user use whatever > mechanism she wants to process them. i.e. instead of > > for item in range: > calculate result > print result > > you'll write > > def generate(): > for item in range: > yield result > > and can then use > > for item in generate(): > print item > > or > > list(process(s) for s in generate()) > > or > > sys.stdout.writelines(generate()) > > or > > sum(generate()) > > etc, without having to change the generator. > > you can also do various tricks with "endless" generators, such as the > following pi digit generator, based on an algorithm by Python's grand- > father Lambert Meertens: > > def pi(): > k, a, b, a1, b1 = 2, 4, 1, 12, 4 > while 1: > # Next approximation > p, q, k = k*k, 2*k+1, k+1 > a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 > # Yield common digits > d, d1 = a/b, a1/b1 > while d == d1: > yield str(d) > a, a1 = 10*(a%b), 10*(a1%b1) > d, d1 = a/b, a1/b1 > > import sys > sys.stdout.writelines(pi()) > > > or fibonacci: def fib(): a, b = 0, 1 while True: yield a a, b = b, a+b now get the first 10 ones: >>> from itertools import * >>> list(islice(fib(),10)) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] or primes: def primes(): yield 1 yield 2 p = 3 psofar = [] smallerPrimes = lambda: takewhile(lambda x: x+x <= p,psofar) while True: if all(p % n != 0 for n in smallerPrimes()): psofar.append(p) yield p p += 2 etc. From dan.jakubiec at gmail.com Mon Jan 22 23:39:52 2007 From: dan.jakubiec at gmail.com (dan.jakubiec at gmail.com) Date: 22 Jan 2007 20:39:52 -0800 Subject: Passing Python socket objects to child processes in Windows Message-ID: <1169527192.554878.260640@38g2000cwa.googlegroups.com> I'm trying to write a Python app which accepts a socket connection and then spawns another Python process to handle it. I need it to run under both Linux and Windows. I have it working under Linux, but am having problems with the Windows implementation. My app uses the subprocess.Popen class to spawn the child process. The first problem I ran into was that Windows Python won't let you pass a socket object via the Popen stdin argument (it results in a "bad file descriptor" error). File object work okay, but sockets seem to be handled differently. After some searching, I found something of a work-around in this post: http://mail.python.org/pipermail/python-list/2004-October/287742.html. This workaround uses pywin32 to duplicate the original socket handle via the Win32 API. It almost works, in the sense that I now have a file stream in my child process which corresponds to the original socket object in the parent. But I can't find a way to convert the resulting Windows file handle into a Python socket object (there does not appear to be a Windows-equivalent of the socket.fromfd() function). My app needs the socket object in order to control TCP stuff. So I'm a bit stuck. Is there a better way (or any way?) to pass a socket to a child process in Windows, and to actually end up with a Python socket object in the child process? Thanks in advance for any help. -- Dan Jakubiec From grante at visi.com Sat Jan 6 01:35:35 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 06 Jan 2007 06:35:35 -0000 Subject: Just Getting Started with Python on MS XP Pro References: <1168064599.558820.9410@42g2000cwt.googlegroups.com> Message-ID: <12pugpnf0fchj97@corp.supernews.com> On 2007-01-06, DouhetSukd at gmail.com wrote: > The only real XP drawback is that Python is not bundled on > Windows, while it is included with OS X and most (all?) Linux > distros. While it's true that Microsoft doesn't bundle Python with Windows, a _lot_ of XP computers do come with Python installed. My IBM ThinkPad came out of the box with Python installed. I've read that a few other large PC vendors (HP/Compaq?) also ship Python pre-installed on their machines. However, it's not usually installed in a manner that makes it conveniently usable by the end-user... -- Grant Edwards grante Yow! NOW, I'm supposed at to SCRAMBLE two, and HOLD visi.com th' MAYO!! From bdesth.quelquechose at free.quelquepart.fr Sun Jan 7 17:40:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 07 Jan 2007 23:40:46 +0100 Subject: Working with Excel inside Python In-Reply-To: <1168205727.130771.257030@51g2000cwl.googlegroups.com> References: <1168205727.130771.257030@51g2000cwl.googlegroups.com> Message-ID: <45a170ae$0$310$426a74cc@news.free.fr> AleydisGP at gmail.com a ?crit : > I have a .plt file (which is a tab delimited ASCII file) and I want to > format it to get a .dbf with data in rows and columns, detele some > rows/columns and substitute decimal '.' with ','. All this using Python Then you may want to have a look here: http://docs.python.org/lib/module-csv.html and here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 > (I'm using Pythonwin). > > The .plt file looks like this: > > * ISCST3 (02035): Tersa > * MODELING OPTIONS USED: > * CONC URBAN ELEV DFAULT > > * PLOT FILE OF ANNUAL VALUES FOR SOURCE GROUP: ALL > * FOR A TOTAL OF 400 RECEPTORS. > * FORMAT: (3(1X,F13.5),1X,F8.2,2X,A6,2X,A8,2X,I8.8,2X,A8) > * X Y AVERAGE CONC ZELEV > * ___________ ___________ ___________ ______ > 430342.00000 4580537.00000 0.25426 19.28 > 430842.00000 4580537.00000 0.27233 14.72 > 431342.00000 4580537.00000 0.30566 2.84 > 431842.00000 4580537.00000 0.30379 0.21 > 432342.00000 4580537.00000 0.27413 1.13 > 432842.00000 4580537.00000 0.25462 0.00 > 433342.00000 4580537.00000 0.25114 0.00 > 433842.00000 4580537.00000 0.28779 0.00 > 434342.00000 4580537.00000 0.29707 0.00 > 434842.00000 4580537.00000 0.31067 0.00 > .... > > I recorded a macro in Excel with the whole process, but when trying to > translate it into Python I get syntax errors which I don't know how to > solve. > > This is my python code: > ## ------------------------------------------ > import win32com.client > excel = win32com.client.Dispatch("Excel.Application") > excel.Visible = 0 > workbook=excel.Workbooks.Open('D:\AN00GALL.plt') > excel.Columns("A:A").Select > excel.Selection.Replace What:=".", Replacement:=",", LookAt:=xlPart, _ > SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ > ReplaceFormat:=False Ok. Where is your attempt to "translate" to Python, exactly ? So far, except for the first 2 lines, it's vb code, not Python. Please start by learning Python, then start doing the translation - and then we'll be glad to help you. (snip vb code) > Any ideas on what am I doing wrong? Yes : trying to feed vb code to the Python interpreter. From nmm1 at cus.cam.ac.uk Sat Jan 13 05:13:09 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 13 Jan 2007 10:13:09 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> In article , "Hendrik van Rooyen" writes: |> |> *grin* - I was around at that time, and some of the inappropriate habits |> almost forced by the lack of processing power still linger in my mind, |> like - "Don't use division if you can possibly avoid it, - its EXPENSIVE!" |> - it seems so silly nowadays. Yes, indeed, but that one is actually still with us! Integer division is done by software on a few systems, and floating-point division is often not vectorisable or pipelines poorly. But, except for special cases of little relevance to Python, it is not the poison that it was back then. |> As an old slide rule user - I can agree with this - if you know the order |> of the answer, and maybe two points after the decimal, it will tell you |> if the bridge will fall down or not. Having an additional fifty decimal |> places of accuracy does not really add any real information in these |> cases. Its nice of course if its free, like it has almost become - but |> I think people get mesmerized by the numbers, without giving any |> thought to what they mean - which is probably why we often see |> threads complaining about the "error" in the fifteenth decimal place.. Agreed. But the issue is really error build-up, and algorithms that are numerically 'unstable' - THEN, such subtle differences do matter. You still aren't interested in more than a few digits in the result, but you may have to sweat blood to get them. |> > [*] Assuming signed magnitude, calculate the answer truncated towards |> > zero but keep track of whether it is exact. If not, force the last |> > bit to 1. An old, cheap approximation to rounding. |> > |> This is not so cheap - its good solid reasoning in my book - |> after all, "something" is a lot more than "nothing" and should |> not be thrown away... The "cheap" means "cheap in hardware" - it needs very little logic, which is why it was used on the old, discrete-logic, machines. I have been told by hardware people that implementing IEEE 754 rounding and denormalised numbers needs a horrific amount of logic - which is why only IBM do it all in hardware. And the decimal formats are significantly more complicated. What I don't know is how much precision this approximation loses when used in real applications, and I have never found anyone else who has much of a clue, either. Regards, Nick Maclaren. From martin at v.loewis.de Sat Jan 20 05:29:23 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 20 Jan 2007 11:29:23 +0100 Subject: PQueue and Python 2.5 In-Reply-To: <1169216890.617239.209170@51g2000cwl.googlegroups.com> References: <1169216890.617239.209170@51g2000cwl.googlegroups.com> Message-ID: <45B1EF03.9020406@v.loewis.de> Berteun Damman schrieb: > I haven't got a clue how to investigate this, but I would be willing to > help if someone has any ideas. There are a number of problems in this code; the most significant one is the incorrect usage of memory management API. In pqueue_dealloc, the call PyMem_DEL(pqp) should read PyObject_DEL(pqp), as the object was allocated with PyObject_NEW. Because this was a common error once, Python up to 2.4 detected that error and silently corrected it (at some runtime cost); Python 2.5 now has removed this work-around. I'll contact the author. Regards, Martin From Barry.Carroll at psc.com Tue Jan 9 18:31:33 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 9 Jan 2007 15:31:33 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A6D@eugsrv400.psc.pscnet.com> John et al: I've spent about a day investigating our "too many open files" error. I found the following: 1. Windows XP allows a Python 2.5 script to open 509 concurrent files. 2. RedHat Fedora Core 1 allows a Python 2.3 script to open 1022 concurrent files. 3. The Python 2.5 release notes and the "What's New in Python 2.5" doc do not mention any changes to the way in which file objects of reference counts are handled. 4. Other features of the framework also fail when this limit is reached. Specifically, our debugger subsystem suffers a fatal error if invoked near the point where the file errors start to occur. So more than just file objects are affected here. I've spent all the time I can spare chasing this bug. The lead programmer is convinced (I think) that we have a reference count problem somewhere, so perhaps he will persue it. If any more useful information comes up on this subject, I'll post it here. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From horpner at yahoo.com Thu Jan 11 09:01:48 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Jan 2007 15:01:48 +0100 Subject: Type casting a base class to a derived one? References: Message-ID: On 2007-01-11, Frederic Rentsch wrote: > If I derive a class from another one because I need a few extra > features, is there a way to promote the base class to the > derived one without having to make copies of all attributes? > > class Derived (Base): > def __init__ (self, base_object): > # ( copy all attributes ) > ... > > This looks expensive. Moreover __init__ () may not be available > if it needs to to something else. > > Thanks for suggestions How does it make sense to cast a base to a derived in your application? -- Neil Cerutti I'm traveling to all 51 states to see who can stop 85. --Chad Johnson From rpdooling at gmail.com Mon Jan 22 10:38:57 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 22 Jan 2007 07:38:57 -0800 Subject: GetBoundingMetrics In-Reply-To: <1169477592.377844.324590@v45g2000cwv.googlegroups.com> References: <1169477592.377844.324590@v45g2000cwv.googlegroups.com> Message-ID: <1169480337.039535.300260@11g2000cwr.googlegroups.com> BartlebyScrivener wrote: > I don't get it if I just launch > firefox from the commandline. Only when I use the Python module. I spoke too soon. I do get it from the command line if firefox is not already running. Same is true with the Python script. Must be a Gnome or Debian thing. Sorry for the distraction. rd From paul.rudin at ntlworld.com Sat Jan 13 04:49:10 2007 From: paul.rudin at ntlworld.com (Paul Rudin) Date: Sat, 13 Jan 2007 09:49:10 +0000 Subject: mod_python and Content-Type Message-ID: <8764bbb6jt.fsf@rudin.co.uk> I'm have a little experiment with mod_python. I'm trying to figure out how to get hold of the original Content-Type header. In my config file I have: AddHandler mod_python .py PythonHandler atomserv PythonDebug On PythonAutoReload On The file atomserv.py in that directory has a function called handler that gets called as I expect, but on entry to that function req.content_type is "text/x-python" whereas my test client sent a different Content-Type header. So, how can I either persuade the apache/mod_python machinery to preserve the original content_type, or else how can I get hold of it? From sturlamolden at yahoo.no Wed Jan 10 17:59:07 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 Jan 2007 14:59:07 -0800 Subject: Python - C# interoperability In-Reply-To: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> References: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> Message-ID: <1168469947.133549.111070@77g2000hsv.googlegroups.com> mc wrote: > Is there an easy way to compile a Python class (or set of classes) into > a .DLL that a C# program can call? Or otherwise to use an existing > library of Python classes from a C# program as seamlessly as possible? One way is to use IronPython if you don't need modules written for CPython. Another option is to use a COM wrapper, e.g. using win32com in Python. A third option is to embed a Python interpreter in your C# app. From wolf_tracks at invalid.com Sat Jan 6 02:57:21 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 06 Jan 2007 07:57:21 GMT Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: Ah, I misread wiki as wikpedia. Nevertheless, wikipedia surprises me, as well as just wiki sites. From codecraig at gmail.com Wed Jan 24 11:32:51 2007 From: codecraig at gmail.com (abcd) Date: 24 Jan 2007 08:32:51 -0800 Subject: Thoughts on using isinstance In-Reply-To: References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> Message-ID: <1169656371.689791.216360@v33g2000cwv.googlegroups.com> Well my example function was simply taking a string and printing, but most of my cases would be expecting a list, dictionary or some other custom object. Still propose not to validate the type of data being passed in? Thanks. From martin at v.loewis.de Tue Jan 9 17:53:25 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Jan 2007 23:53:25 +0100 Subject: What does the -O flag do? In-Reply-To: <1168381174.638428.168500@k58g2000hse.googlegroups.com> References: <1168381174.638428.168500@k58g2000hse.googlegroups.com> Message-ID: <45a41ce5$0$30389$9b622d9e@news.freenet.de> Sard schrieb: > "Optimize generated bytecode (also PYTHONOPTIMIZE=x). Asserts are > suppressed." > > Is removing asserts all it does, where can I find more details? I'm > guessing it's not very useful as I hardly ever see it mentioned. It somewhat depends on the Python version. To find out precisely what it does, search the source code for Py_OptimizeFlag. In 2.5, it - causes the interpreter to load .pyo files, not .pyc files (in .zip files, just makes .pyo preferred over .pyc) - causes __debug__ to have a value of 0 - ignores assert statements in source code - treats __debug__ statically as being 0 - causes the byte code generator to save .pyo files, not .pyc HTH, Martin From facundo at taniquetil.com.ar Wed Jan 17 11:57:33 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 17 Jan 2007 16:57:33 +0000 (UTC) Subject: how to write unicode to a txt file? References: <1169051293.848769.163860@s34g2000cwa.googlegroups.com> Message-ID: Frank Potter wrote: > But it seems that python can't directly write unicode to a file, You need to use the method open from module codecs: >>> import codecs >>> a = codecs.open("pru_uni.txt", "w", "utf-8") >>> txt = unicode("campe?n\n", "utf-8") >>> a.write(txt) >>> a.close() >>> So, then, from command line: facundo at expiron:~$ file pru_uni.txt pru_uni.txt: UTF-8 Unicode text :) Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From CRhode at LacusVeris.com Thu Jan 18 09:54:10 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Thu, 18 Jan 2007 08:54:10 -0600 Subject: PythonTidy 1.10 Message-ID: <20070118145410.GF1352@loki> PythonTidy cleans up, regularizes, and reformats the text of Python scripts. It is released under the GNU General Public License. Python scripts are usually so good looking that no beautification is required. However, from time to time, it may be necessary to alter the style to conform to changing standards. This script converts programs in a consistent way. It abstracts the pretty presentation of the symbolic code from the humdrum process of writing it and getting it to work. This is an upgrade. There was a big problem with earlier versions: Canonical values were substituted for strings and numbers. For example, decimal integers were substituted for hexadecimal, and escaped strings for raw strings. Authors of Python scripts usually use peculiar notations for peculiar purposes, and doing away with the peculiarity negatively impacts the readability of the code. This version preserves the original constants (parsed by *tokenize*) in a literal pool indexed by the value they evaluate to. The canonical values (output by *compiler*) are then translated back (when possible) to the original constants by looking them up in the literal pool. --

PythonTidy 1.10 - Cleans up, regularizes, and reformats the text of Python scripts. (18-Jan-07)

.. Chuck Rhode, Sheboygan, WI, USA .. mailto:CRhode at LacusVeris.com?subject=PythonTidy .. Weather: http://LacusVeris.com/WX .. 20? ? Wind WNW 13 mph From fuzzyman at gmail.com Fri Jan 5 19:05:15 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2007 16:05:15 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167974907.497878.61070@i15g2000cwa.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1167974907.497878.61070@i15g2000cwa.googlegroups.com> Message-ID: <1168041915.558354.110570@s80g2000cwa.googlegroups.com> Carl Banks wrote: > jeremito wrote: > > I am writing a class that is intended to be subclassed. What is the > > proper way to indicate that a sub class must override a method? > > You can't (easily). > Well... How about not defining it on the base class, but check in the constructor that the attribute exists and that it is of type FunctionType ? Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From hg at nospam.org Thu Jan 4 10:19:15 2007 From: hg at nospam.org (hg) Date: Thu, 04 Jan 2007 16:19:15 +0100 Subject: Problem Running Working Code on Mac References: <1167946511.531632.41750@11g2000cwr.googlegroups.com> Message-ID: goodepic wrote: > I'm newish to python and just got my first mac, so sorry if this is > stupid. I have a little app developed by someone else in wxGlade that > implements a complex stats package and language package, all in python. > It works fine on my work PC, but not on my laptop. I have a new > macbook 2ghz core duo, running os x 10.4.8 with python 2.5 installed (I > didn't erase the base 2.3, just put /usr/local/bin at the start of > $PATH), along with the latest wxPython, can't remember the version > number. I need to add a few more components from the stats package, > and I'd like eventually to pretty up the cheap GUI I was given, but > that'd be icing. When I try either python or pythonw > , I get this error: > > WARNING:root:Could not import module "PyPar", defining sequential > interface > WARNING:root:No MySQLdb module available > WARNING:root:No pgdb module (PostgreSQL) available > Traceback (most recent call last): > File "febrlgui.py", line 513, in > frame_1 = MyFrame(None, -1, "") > File "febrlgui.py", line 198, in __init__ > self.__set_properties() > File "febrlgui.py", line 355, in __set_properties > self.a_box1.SetSelection(-1) > File > "//Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/wx-2.8-mac-ansi/wx/_core.py", > line 11487, in SetSelection > return _core_.ItemContainer_SetSelection(*args, **kwargs) > wx._core.PyAssertionError: C++ assertion "IsValid(n)" failed at > /BUILD/wxPython-src-2.8.0.1/src/mac/carbon/choice.cpp(242) in > GetString(): wxChoice::GetString(): invalid index > > Of course I'm traveling soon and need to be able to work on this on my > macbook, so it's down to panic time. Any help is GREATLY appreciated. > > Thanks, > Matt I'd get rid of the warnings first by installing the correct librairies (PyPar, MySQLDB, pgdb) .... who knows what the side effect are ? hg From goodidea1950 at hotmail.spam.com Sun Jan 28 03:08:00 2007 From: goodidea1950 at hotmail.spam.com (AKA gray asphalt) Date: Sun, 28 Jan 2007 00:08:00 -0800 Subject: Do I need Python to run Blender correctly? References: <5%4uh.75582$wP1.6882@newssvr14.news.prodigy.net> Message-ID: <9TYuh.3468$4W5.752@newsfe10.phx> "John Nagle" wrote in message news:ssTuh.36083$QU1.26111 at newssvr22.news.prodigy.net... > AKA gray asphalt wrote: >> "John Nagle" wrote in message >> news:5%4uh.75582$wP1.6882 at newssvr14.news.prodigy.net... >> >>>AKA gray asphalt wrote: >>> >>>>I downloaded Blender but there was no link for python. Am I on the right >>>>track? >>> >>> Blender doesn't require Python, but if you have Python, you can >>>write plug-ins for Blender. Get "The Blender Book"; otherwise >>>you'll never figure Blender out. >>> >>>John Nagle >> >> >> I'm thinking about not upgrading "Strata 3D" because it still doesn't >> export textures with obj files and it just created an undo of more than >> one action, believe it or not... Am I expectiong too much of a $400+ >> program, to export textures with obj files? Does Blender do this? I see >> the BBook on Amazon for $30. That's probably my best bet, no? > > Blender has considerable power, but ease of use is a problem. The > hotkey listing in the manual is 29 pages. Is the manual you refer to the group project on blender.org or the $ manual like the one on Ebay? From bj_666 at gmx.net Sat Jan 27 04:21:46 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 27 Jan 2007 10:21:46 +0100 Subject: python+ncurses: I can't display accents References: <45ba3573$0$16171$426a34cc@news.free.fr> <45ba50c7$0$31432$426a74cc@news.free.fr> <45ba77a2$0$26693$426a74cc@news.free.fr> Message-ID: In <45ba77a2$0$26693$426a74cc at news.free.fr>, Fabrice DELENTE wrote: > As support for 8-bit (and even unicode) is important for my script, is there > any hope? Should I switch to slang instead of curses? Take a look at urwid: http://excess.org/urwid/ Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Sat Jan 13 00:11:19 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 13 Jan 2007 05:11:19 GMT Subject: how to clean sys.path References: Message-ID: "siggi" wrote: > >or in plain DOS: > >C:\Documents and Settings\User\My Documents\My Python files >C:\Documents and Settings\User\My Documents\Python25\Lib\idlelib >C:\Documents and Settings\User\My Documents\Python25\python25.zip >C:\Documents and Settings\User\My Documents\Python25\DLLs >C:\Documents and Settings\User\My Documents\Python25\lib >C:\Documents and Settings\User\My Documents\Python25\lib\plat-win >C:\Documents and Settings\User\My Documents\Python25\lib\lib-tk >C:\Documents and Settings\User\My Documents\Python25 >C:\Documents and Settings\User\My Documents\Python25\lib\site-packages >C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\PIL >C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\win32 >C:\Documents and Settings\User\My >Documents\Python25\lib\site-packages\win32\lib >C:\Documents and Settings\User\My >Documents\Python25\lib\site-packages\Pythonwin >C:\Documents and Settings\User\My >Documents\Python25\lib\site-packages\wx-2.8-msw-ansi > >...it just looked horrible to me at first sight! It looks horrible to me, too. That's why I install applications like that in "\Apps" instead of a document off of Documents and setings. This looks much better: C:\Documents and Settings\User\My Documents\My Python files C:\Apps\Python25\Lib\idlelib C:\Apps\Python25\python25.zip C:\Apps\Python25\DLLs C:\Apps\Python25\lib C:\Apps\Python25\lib\plat-win C:\Apps\Python25\lib\lib-tk C:\Apps\Python25 C:\Apps\Python25\lib\site-packages C:\Apps\Python25\lib\site-packages\PIL C:\Apps\Python25\lib\site-packages\win32 C:\Apps\Python25\lib\site-packages\win32\lib C:\Apps\Python25\lib\site-packages\Pythonwin C:\Apps\Python25\lib\site-packages\wx-2.8-msw-ansi Searching these doesn't really take very long. Remember that it doesn't have to read all the files -- it only has to read the directories. >'C:\Documents and Settings\User\My Documents\My Python files', 'C:\Documents >and Settings\User\My Documents\My Python files\wxDemos'. Now \wxDemos\ is >being searched very early. > >... no way! After running AnalogClock.py again, this error message appears: > >------------------------------------------ >Traceback (most recent call last): > File "C:\Documents and Settings\My Documents\My Python >files\wxAnalogClock.py", line 14, in > import wx >ImportError: No module named wx. >------------------------------------------ > >Very strange! Because all this wx stuff IS IN the directory 'C:\Documents >and Settings\User\My Documents\My Python files\wxDemos'. And AnalogClock.py >does work when residing in that directory. wxDemos contains the demos. The "wx" module lives in site-packages\wx-2.8-msw-ansi. Did you leave that in? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From arkanes at gmail.com Wed Jan 24 14:55:20 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 13:55:20 -0600 Subject: Type casting a base class to a derived one? In-Reply-To: <1169667478.4910.52.camel@portable-evil> References: <4866bea60701110641n5eb4cc57uf5967aebcfd7790d@mail.gmail.com> <1169664145.4910.22.camel@portable-evil> <4866bea60701241057t13776d34ya516c2c24e7119bb@mail.gmail.com> <1169667478.4910.52.camel@portable-evil> Message-ID: <4866bea60701241155q43fedd8yea8efc1b410a69ec@mail.gmail.com> On 1/24/07, Cliff Wells wrote: > On Wed, 2007-01-24 at 12:57 -0600, Chris Mellon wrote: > > > > > In Python, you can do this simply by re-assigning the __class__. I'm > > not convinced that your type system makes sense, here though. Any > > reasonable ORM should be able to persist and reload an object without > > losing the type information. Perhaps it's just a blind spot in the way > > I think about types. Assuming that the limitations of your ORM are > > external and out of your control, I would still ensure that whatever > > generic objects are being loaded from the ORM are converted into > > "real" objects of the correct type as soon as possible. For example, > > if you're persisting a file, you might just save the filename, and > > your ORM might return a string of the filename. I would want to > > convert that back into a file object ASAP, rather than writing all my > > code to accept either a FLO or a string and converting then. > > > > If you know what to upcast something to, then you know what type it > > is. If you know what type it is, then (in Python) you can simply > > assume it is of that type. > > Probably being more specific would help in this case ;-) > > What I'm doing is implementing an object-publishing mechanism in my > template engine (Breve). The type decision isn't known until the moment > of rendering (i.e. in the template itself). Say for instance a set of > records is pulled from the ORM (SQLAlchemy in this case) and that these > records represent articles in a blog. These records, until they hit the > template, have no real representation in HTML. The decision about how > to present them is up to the template. The dispatch mechanism I > referred to earlier is a way that I allow users of the template system > to register how a particular object should be rendered in HTML (a > "flattener"). This allows commonly represented objects to be used > without a lot of template clutter. > However, if you consider the case of a blog, then if the template > receives a list of articles, it would seem reasonable to present those > articles in at least two ways: first as a table of contents in the page > gutter, and then perhaps as two or three summaries in the main part of > the page. But this isn't known to the lower layers of the application, > only to the template. Therefore it would be nice if the template user > could register two classes with the flattener, both representations of > the original object but simply with a different type. > > I'll give a concrete example: > > class Person: # assume this is something from the ORM > name = "Kenny" > > class PersonRow ( Person ): > pass > > def flatten_person ( p ): > return "omg, you've killed %p" % p.name > > def flatten_personrow ( p ): > return "%s" % p.name > > register_flattener ( PersonRow, flatten_personrow ) > register_flattener ( Person, flatten_person ) > > > Now, assuming a list of Person records were passed in as 'persons', then > in the template the template author could simply use: > > div [ > # show the first person > persons [ 0 ], > > # show a table of all persons > table [ > [ PersonRow ( p ) for p in persons ] > ] > ] > > > > What you're describing is a disjoint between your actual type system > > (that is, the one you have in code) and your theoretical type system > > (the one that you model your code around). To me, this is a huge red > > warning flag. > > What I'm describing is a disjoint between how I want my template engine > to be used (I tend to build backwards, writing the desired template code > and then the engine code to support that use) and what can be easily and > efficiently achieved. But yes, in a way you are correct since my > theoretical type system is constrained by Python's type system (Breve > templates are Python expressions). > > That being said, I'm certain I'll come up with a solution that doesn't > bug me too much, it's just that the "obvious" solution doesn't exist > (type casting). > When I look at this, I don't see type casting as the obvious solution - PersonRow isn't a subclass of Person, it's a subclass of Row. The way you actually write it (constructing a PersonRow with a person) is exactly how I would actually implement it though, except I wouldn't see it as a "typecast" any more than I see creating a file object from a filename as a typecast. I see it as a construction. I might implement PersonRow as: class PersonRow(Row): def __init__(person): self.person = person #assumed to be a Person object def flatten(self): return "%s>" % self.person.name Of course, when types are just callables that return instances the distinction between construction and typecasting becomes purely semantic. So the real confusion here may simply be how one refers to an operation, rather than the operation itself. From __peter__ at web.de Wed Jan 10 05:20:33 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 Jan 2007 11:20:33 +0100 Subject: convert binary data to int References: <1168424278.193439.216770@k58g2000hse.googlegroups.com> Message-ID: rubbishemail at web.de wrote: > I need to convert a 3 byte binary string like > "\x41\x00\x00" to 3 int values ( (65,0,0) in this case). > The string might contain characters not escaped with a \x, like > "A\x00\x00" >>> [ord(c) for c in "A\x00\x41"] [65, 0, 65] For more complex conversions look into the struct module. Peter From garyjefferson123 at yahoo.com Thu Jan 25 01:54:46 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 24 Jan 2007 22:54:46 -0800 Subject: selective logger disable/enable In-Reply-To: <1169546484.370874.253890@a75g2000cwd.googlegroups.com> References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> <1169349399.938121.238430@38g2000cwa.googlegroups.com> <1169395276.181654.160810@a75g2000cwd.googlegroups.com> <1169437763.213781.163660@38g2000cwa.googlegroups.com> <1169442596.209314.162410@s34g2000cwa.googlegroups.com> <1169531341.221067.205500@11g2000cwr.googlegroups.com> <1169546484.370874.253890@a75g2000cwd.googlegroups.com> Message-ID: <1169708086.661248.142390@j27g2000cwj.googlegroups.com> So maybe I don't have all this figured out quite as well as I thought. What I really want to do is set an environment variable, MYDEBUG, which contains a list of wildcarded logger names, such as "a.*.c a.d" (which becomes ['a.*.c', 'a.d'], and then selectively crank the loglevel up to DEBUG for those that match. In order to do that, I think I need something kind of like filters, but for logger name... I'm not seeing how to do this, even after playing with variations of test15, 18, and 21. What I do have working at the moment is passing a list of non-wildcard logger names, i.e., doing the wildcard expansion manually such as "['a.b.c', 'a.c.c', 'a.f.c', 'a.d']. Is there anyway to automate this dynamically? BTW, I do understand that 'a.d' is essentially equivalent to 'a.d.*', but I'm dealing with a hierarchy that doesn't always tidy up like that. For example, I have top.network.server.http, top.network.server.smtp, top.network.client.http, and top.network.client.smtp. Obviously, if I only want server or client DEBUG msgs, this is easy. And sometimes that's exactly what I want. Other times, I want only smtp DEBUG msgs, and the hierarchy won't help me get that (unless I break it for just getting client or server msgs), etc. So I would really like to figure out how to do 'a.*.c'. Any ideas? Thanks again, Gary On Jan 23, 3:01 am, "Vinay Sajip" wrote: > Glad the tests/examples (log_testxx.py) helped. When I get a > chance, I will try to work some of them into the docs... > > Best regards, > > Vinay Sajip From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 12 11:56:09 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 12 Jan 2007 17:56:09 +0100 Subject: modules...n methods References: <1168620496.520506.296330@q2g2000cwa.googlegroups.com> Message-ID: <50pst9F1h5hj5U1@mid.individual.net> lee wrote: > whats the way to read the sourcecode of methods Easy. Look up the .py file and open it in an editor of your choice. Those files are, for example, in "/usr/lib/python". > and built in functions? Get your python interpreter's source code and look up the functions there. Regards, Bj?rn -- BOFH excuse #370: Virus due to computers having unsafe sex. From skip at pobox.com Fri Jan 12 17:38:42 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 12 Jan 2007 16:38:42 -0600 Subject: Portable Python - free portable development environment ! In-Reply-To: <1168639781.763133.319580@s34g2000cwa.googlegroups.com> References: <1168533423.224355.221390@k58g2000hse.googlegroups.com> <1168639781.763133.319580@s34g2000cwa.googlegroups.com> Message-ID: <17832.3570.698257.111981@montanaro.dyndns.org> perica> but this is first release and I have big plans ;) Including maybe other platforms than Windows? Skip From danielkleinad at gmail.com Fri Jan 19 12:03:33 2007 From: danielkleinad at gmail.com (Daniel Klein) Date: Fri, 19 Jan 2007 17:03:33 GMT Subject: Match 2 words in a line of file References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> <1169172954.107365.133950@51g2000cwl.googlegroups.com> <1169175299.490994.244700@51g2000cwl.googlegroups.com> Message-ID: On 18 Jan 2007 18:54:59 -0800, "Rickard Lindberg" wrote: >I see two potential problems with the non regex solutions. > >1) Consider a line: "foo (bar)". When you split it you will only get >two strings, as split by default only splits the string on white space >characters. Thus "'bar' in words" will return false, even though bar is >a word in that line. > >2) If you have a line something like this: "foobar hello" then "'foo' >in line" will return true, even though foo is not a word (it is part of >a word). 1) Depends how you define a 'word'. 2) This can be resolved with templine = ' ' + line + ' ' if ' ' + word1 + ' ' in templine and ' ' + word2 + ' ' in templine: Dan From ptmcg at austin.rr._bogus_.com Mon Jan 1 19:43:32 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 1 Jan 2007 18:43:32 -0600 Subject: Writing more efficient code References: Message-ID: <4599aab4$0$18074$4c368faf@roadrunner.com> "gonzlobo" wrote in message news:mailman.2185.1167676577.32031.python-list at python.org... > Greetings, and happyNewYear to all. > > I picked up Python a few weeks ago, and have been able to parse large > files and process data pretty easily, but I believe my code isn't too > efficient. I'm hoping dictionaries will help out, but I'm not sure the > best way to implement them. > > I've been using a bunch of nested if/elif/else statements to select > slices (0317 & 03de) from a file, then parse the data (aa, hh, bb, > d2-d9) into parameters (a = airspeed, h = heading) & flags. > > #sample file contents > 0000007d 03 0317 aa aa aa aa aa hh hh hh bb bb > 0000007e 06 03de d2 d3 d4 d5 d6 d7 d8 d9 10 11 > > # some pseudo code > if PID == '03de': > flapsCmd = int(d3, 16) > if flapsCmd == 0xc0: > > elif flapsCmd == 0x03: > > if PID == '0317': > airspeed == 'combine aa for airspeed & multiply by 0.1' > heading == 'combine hh for heading' > mach == 'combine bb for mach & multiply by 0.01' > > Might dictionaries help in this case... say Label0317(parameterName, > slice (d3), scaleFactor(0.1))... I'd like to use them if they'll > replace the dozens of nested conditionals. I have roughly 75 > different parameters to decode from a file containing ~2.5 million > lines of data. > > I know my pseudo code lacks details, but hopefully I'm getting my > point across... > > (I suppose switch/select/case statements would help a bit, but python > doesn't seem to use them... not to start a religious war or anything). > > Any help (or encouragement) is appreciated. First, your data is so regularly formatted, I suspect you are using the split() method of string to get at the pieces. Good, this keeps things simple. It *would* help if you posted actual data lines, instead of aa's, and bb's. So I took a guess that these were hex representations of characters representing decimal numbers. Instead of switch/case, I selected a dict that creates a dispatch table, selecting one of several object classes whose __init__ constructors are written to pick apart the relevant fields from the 10-element list following the 4-digit selection code. I then just created an object dumping method to show what objects were created from what lines of data, and perhaps you can take it from there. -- Paul test = """\ 0000007d 03 0317 30 33 32 38 38 32 37 35 34 31 0000007e 06 03de af c0 fe d5 d6 d7 d8 d9 10 11 0000007e 06 junk af c0 fe d5 d6 d7 d8 d9 10 11 0000007f 06 03de af 03 fe d5 d6 d7 d8 d9 10 11""" hex2int = lambda hh : int(hh,16) class AirspeedHeadingMach(object): def __init__(self,datalist): self.airspeed = int("".join(map(chr,map(hex2int,datalist[:5]))))*0.1 self.heading = "".join(map(chr,map(hex2int,datalist[5:8]))) self.mach = int("".join(map(chr,map(hex2int,datalist[8:]))))*0.01 UP,DOWN = 0,1 class FlapsStatus(object): def __init__(self,datalist): self.flaps = { 0xc0:UP, 0x03:DOWN } [ int(datalist[1],16) ] class UnknownRec(object): def __init__(self,code,datalist): self.code = code self.datalist = datalist[:] def dump(o): print o.__class__.__name__ print o.__dict__ print recCodeTypeMap = { '0317' : AirspeedHeadingMach, '03de' : FlapsStatus, } for line in test.split("\n"): toks = line.split() code = toks[2] datalist = toks[3:] if code in recCodeTypeMap: dataObject = recCodeTypeMap[code](datalist) else: dataObject = UnknownRec(code,datalist) dump(dataObject) Prints: AirspeedHeadingMach {'mach': 0.41000000000000003, 'airspeed': 328.80000000000001, 'heading': '275'} FlapsStatus {'flaps': 0} UnknownRec {'datalist': ['af', 'c0', 'fe', 'd5', 'd6', 'd7', 'd8', 'd9', '10', '11'], 'code': 'junk'} FlapsStatus {'flaps': 1} From pwatson at redlinepy.com Wed Jan 3 22:23:11 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Wed, 03 Jan 2007 21:23:11 -0600 Subject: Cannot build 2.5 on FC6 x86 In-Reply-To: <459c0ac1$0$28366$9b622d9e@news.freenet.de> References: <502e72F1eh7ngU1@mid.individual.net> <459c0ac1$0$28366$9b622d9e@news.freenet.de> Message-ID: <503a8vF1d8dn2U1@mid.individual.net> Martin v. L?wis wrote: > Paul Watson schrieb: >> ./configure >> make >> make test >> >> The result appears to hang after the test_tkl... line. I had to kill >> the 'make test' process which terminated it. Any suggestions? > > There isn't (or shouldn't be) any "test_tkl..." line. What precisely > was the line, and how long did you wait until you thought it hangs? > > Regards, > Martin Sorry, I mis-typed. It is not test_tkl. It was test_tcl... The last line output was as shown below my mistyping. I let it sit overnight one time. From weekender_ny at yahoo.com Sat Jan 13 23:49:39 2007 From: weekender_ny at yahoo.com (John) Date: 13 Jan 2007 20:49:39 -0800 Subject: Threaded for loop In-Reply-To: <7xr6ty8ugv.fsf@ruckus.brouhaha.com> References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> <7xr6ty8ugv.fsf@ruckus.brouhaha.com> Message-ID: <1168750177.856791.85730@s34g2000cwa.googlegroups.com> Damn! That is bad news. So even if caclulate is independent for (i,j) and is computable on separate CPUs (parts of it are CPU bound, parts are IO bound) python cant take advantage of this? Surprised, --Tom Paul Rubin wrote: > "John" writes: > > I want to do something like this: > > > > for i = 1 in range(0,N): > > for j = 1 in range(0,N): > > D[i][j] = calculate(i,j) > > > > I would like to now do this using a fixed number of threads, say 10 > > threads. What is the easiest way to do the "parfor" in python? > > It won't help in terms of actual parallelism. Python only lets one > thread run at a time, even on a multi-cpu computer. From danb_83 at yahoo.com Thu Jan 11 22:44:06 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 11 Jan 2007 19:44:06 -0800 Subject: dot operations In-Reply-To: References: <1168511200.252193.132340@p59g2000hsd.googlegroups.com> Message-ID: <1168573446.592441.245490@38g2000cwa.googlegroups.com> On Jan 11, 10:21 am, "Steven W. Orr" wrote: > On Thursday, Jan 11th 2007 at 11:41 +0100, quoth robert: > > =>jm.sur... at no.spam.gmail.com wrote:=>> Hi, > =>> Frequently I get to do like this: > =>> a = (1, 2, 3, 4) # some dummy values > =>> b = (4, 3, 2, 1) > =>> import operator > =>> c = map(operator.add, a, b) > =>> > =>> I am finding the last line not very readable especially when I combine > =>> couple of such operations into one line. Is it possible to overload > =>> operators, so that, I can use .+ for element wise addition, as, > =>> c = a .+ b > =>> which is much more readable. > =>> > =>> Similarly, I want to use .- , .*, ./ . Is it possible to do? > => > =>import numpy > => > =>You'll not even need dots > > I'm very new so my plea to be gentle is still on. > > I just looked at the numpy package. Seems very cool, but for the life of > me I didn't understand the method by which python allows for creation of > infix operators. Can someone please explain or point me to a reference? Python doesn't allow the creation of new operators, but you can overload the existing ones (except for "and" and "or"). This is done by implementing the methods __add__, __sub__, __mul__, etc. http://docs.python.org/ref/specialnames.html From deets at nospam.web.de Tue Jan 30 02:54:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 Jan 2007 08:54:52 +0100 Subject: Executing Javascript, then reading value In-Reply-To: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> References: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> Message-ID: <528bv4F1n73scU1@mid.uni-berlin.de> Melih Onvural schrieb: > I need to execute some javascript and then read the value as part of a > program that I am writing. I am currently doing something like this: > > import htmllib, urllib, formatter > > class myparser(htmllib.HTMLParser): > insave = 0 > def start_div(self, attrs): > for i in attrs: > if i[0] == "id" and i[1] == "pr": > self.save_bgn() > self.insave = 1 > > def end_div(self): > if self.insave == 1: > print self.save_end() > self.insave = 0 > > parser = myparser(formatter.NullFormatter()) > > #def getPageRank(self, url): > try: > learn_url = "http://127.0.0.1/research/getPageRank.html?q=http:// > www.yahoo.com&" > pr_url = urllib.urlopen(learn_url) > parser.feed(pr_url.read()) > except IOError, e: > print e > > but the result is the javascript function and not the calculated > value. Is there anyway to get the javascript to execute first, and > then return to me the value? thanks in advance, Do it in a browser. There are ways to automate one, for example the webbrowser module, and others. Then rework your script to work with AJAX. Diez From streamservenl at gmail.com Wed Jan 31 09:25:35 2007 From: streamservenl at gmail.com (jvdb) Date: 31 Jan 2007 06:25:35 -0800 Subject: Help needed on config files In-Reply-To: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> References: <1170237893.930122.138300@v45g2000cwv.googlegroups.com> Message-ID: <1170253533.873819.115130@p10g2000cwp.googlegroups.com> Yes! That does the trick, thanks, both of you! From stephan.diehl at gmx.net Mon Jan 29 12:32:23 2007 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 29 Jan 2007 18:32:23 +0100 Subject: next berlin python-group meeting fr., 2.2. In-Reply-To: References: Message-ID: Stephan Diehl wrote: > http://starship.python.net/cgi-bin/mailman/listinfo/python-berlin argghhh, wrong link. please try http://starship.python.net/mailman/listinfo/python-berlin From gagsl-py at yahoo.com.ar Fri Jan 26 05:34:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Jan 2007 07:34:52 -0300 Subject: how to remove c++ comments from a cpp file? In-Reply-To: <1169805244.879280.235660@v45g2000cwv.googlegroups.com> References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com> <1169805244.879280.235660@v45g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070126071436.0455d118@yahoo.com.ar> At Friday 26/1/2007 06:54, Frank Potter wrote: >[CODE] >import re > >f=open("show_btchina.user.js","r").read() >f=unicode(f,"utf8") > >r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE) >f_new=r.sub(ur"",f) > >open("modified.js","w").write(f_new.encode("utf8")) >[/CODE] > >And, the problem is, it seems that only the last comment is removed. >How can I remove all of the comments, please? Note that it's not as easy as simply deleting from // to end of line, because those characters might be inside a string literal. But if you can afford the risk, this is a simple way without re: f = open("show_btchina.user.js","r") modf = open("modified.js","w") for line in f: uline=unicode(line,"utf8") idx = uline.find("//") if idx==0: continue elif idx>0: uline = uline[:idx]+'\n' modf.write(uline.encode("utf8")) modf.close() f.close() -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From saluk64007 at gmail.com Sat Jan 6 14:13:34 2007 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sat, 6 Jan 2007 11:13:34 -0800 Subject: still struggling, howto use a list-element as a name ? In-Reply-To: References: Message-ID: You would use setattr to bind a name that you don't know: for pin in self.pin: setattr(self,pin.Name,pin.Value) However, I'm not sure why you're using a dictionary in this way. I don't totally understand the context, so I may be wrong, but I would code it more like this: class Power_Supply(device): pins = {'GND':(_DIG_OUT,_par2),'VCC':(_DIG_OUT,_par33)} def __init__(self): for pin in pins.items(): #pin will be key,value setattr(self,pin[0],pin[1]) or even: class Power_Supply(device): pins = {'GND':(_DIG_OUT,_par2),'VCC':(_DIG_OUT,_par33)} def __init__(self): self.__dict__.update(pins) #self.__dict__ is the name mapping for any object, update will insert any new values from a new dictionary into the old one -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com Thu Jan 11 18:37:41 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 11 Jan 2007 17:37:41 -0600 Subject: Is there a good example on instantiating, calling, using, an API from Python on Windows? In-Reply-To: <1168541166.457806.133320@p59g2000hsd.googlegroups.com> References: <1168541166.457806.133320@p59g2000hsd.googlegroups.com> Message-ID: <45A6CA45.3000300@websafe.com> kj7ny wrote: > Is there a good example on instantiating, calling, using, etc., an API > from Python? > > I need to use Python to talk to another system through that system's > API's on Windows XP. > > Can you point me to documentation and/or a good example of Python using > 3rd party API's? (Preferably a good example rather than just > documentation.) > > And, can I do this from Python 2.4.# or should I try to learn how to > use Iron Python? (By the way, if the examples could be for python > 2.4.# it would be preferable.) > > Thanks, > When you say API what EXACLY do you mean. Is it a .DLL that you need to call (if so see ctypes module) or a COM API (if so see win32 module)? Other APIs could use sockets, pipes, etc. you will need to give us more to be able to help. -Larry From metsakuri at gmail.com Thu Jan 4 04:35:38 2007 From: metsakuri at gmail.com (tonisk) Date: 4 Jan 2007 01:35:38 -0800 Subject: pow() works but sqrt() not!? In-Reply-To: References: <1167899693.759071.51450@31g2000cwt.googlegroups.com> Message-ID: <1167903337.816250.196540@51g2000cwl.googlegroups.com> > >if you want math functions to your current namespace use: > >>> from math import *What is a "namespace" and what is the difference between ">>>import math" > and ">>>from math import *" ? for namespaces read this http://www.network-theory.co.uk/docs/pytut/tut_68.html import math creates new namespace "math" for names in that module, so you can acess them by prefixing them with "math", like math.sqrt(9). from math import * imports all names to your local scope, so you do not have to prefix them, sqrt(9) -- T?nis From gagsl-py at yahoo.com.ar Thu Jan 18 21:29:07 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Jan 2007 23:29:07 -0300 Subject: More M2Crypto issues In-Reply-To: References: Message-ID: <7.0.1.0.0.20070118225626.01d2f6f8@yahoo.com.ar> At Thursday 18/1/2007 04:41, John Nagle wrote: > I've been running M2Crypto successfully using Python 2.4 on Windows 2000, >and now I'm trying to get it to work on Python 2.3.4 on Linux. > > Attempting to initialize a context results in > >Traceback (most recent call last): > File "/www/htdocs/sitetruth.com/cgi/ratingdetails.cgi", line 46, in ? > DetailsPageBuilder.detailspage(kdbfile,ktemplatefile,url) # check and >display domain or URL as web page > File "./sitetruth/DetailsPageBuilder.py", line 70, in detailspage > sitecert = InfoSSL2.Certificate(siteinfo, kverifylocations, verbose) > File "./sitetruth/InfoSSL2.py", line 147, in __init__ > self.ctx = createsslcontext(trustedcafile, verbose) # > Generate general SSL >context > File "./sitetruth/InfoSSL2.py", line 40, in createsslcontext > ctx = > SSL.Context('sslv3') > # Create context with SSL params > File "/home/sitetruth/lib/python/M2Crypto/SSL/Context.py", line > 43, in __init__ > map()[long(self.ctx)] = self >ValueError: invalid literal for long(): _480e1008_p_SSL_CTX On a previous version of M2Crypto that line said: map()[self.ctx] = self, and that failed too ("unhashable object", I think). I changed the class _ctxmap (the map() above returns an instance of it) to use str(key) in the 3 places it was used. (That would be equivalent to use str(self.ctx) everywhere, instead of long(self.ctx) as your traceback is showing). All I can say is that no error happened afterwards, but I don't know if that broke something. (and I didn't care at the moment, I only needed a Zope instance running on Windows with SSL for less than a week - and if it were "cheating SSL" it was OK for me then) > which, when I look at the code and try some test cases, seems >legitimate. The cacheing code is trying to convert a reference to an >object (a C object, in fact) into a "long". Python 2.4 on Windows >will do that. Python 2.3.4 on Linux converts it to a string first, >gets "_480e1008_p_SSL_CTX", and then tries to convert that to an >integer, which fails. So using str() appears, at least on the surface, to be reasonable. But someone with more intimate knowledge of the library should confirm that. I don't even understand what's the point for the _ctxmap singleton - it's the same thing as a global dictionary, isn't it? -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From http Sun Jan 7 10:27:22 2007 From: http (Paul Rubin) Date: 07 Jan 2007 07:27:22 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> Message-ID: <7x3b6mzwkl.fsf@ruckus.brouhaha.com> Thomas Ploch writes: > Me neither, although I have to say that the '__' prefix comes pretty > close to being 'private' already. It depends on the definition of > private. For me, private means 'not accessible from outside the > module/class'. class A: __x = 3 class B(A): __x = 4 # ok class C(B): __x = 5 # oops! Consider that the above three class definitions might be in separate files and you see how clumsy this gets. From facundo at taniquetil.com.ar Fri Jan 26 11:16:28 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 26 Jan 2007 16:16:28 +0000 (UTC) Subject: Right-Justifying Numeric Output References: Message-ID: Rich Shepard wrote: > print '%2d $%11.2f $%10.2f $%9.2f $%9.2f' %(nper, pv, diff, ten, bonus) > > and I would like to have the output right justified in the specified field. >>> "%7.2f..%5d" % (2.3, 78) ' 2.30.. 78' >>> "%-7.2f..%-5d" % (2.3, 78) '2.30 ..78 ' Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From steve at REMOVEME.cybersource.com.au Mon Jan 29 20:52:02 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 30 Jan 2007 12:52:02 +1100 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170064302.264009.12650@p10g2000cwp.googlegroups.com> <7xveiqapwi.fsf@ruckus.brouhaha.com> <1170082420.420688.109910@l53g2000cwa.googlegroups.com> Message-ID: On Mon, 29 Jan 2007 16:24:18 +0100, Laszlo Nagy wrote: > NoName ?rta: >> Hmmm.. >> In the Perl example password generates after user hit ENTER not >> continously like in Python you wrote... :) >> >> i want see various ways to generate passwords even if they some >> indirect like using BASE64 >> > I copied this from a recipe, I do not remember which one. I like it very > much because it creates password that are easy to type in. You can type > every odd letter with your left hand and every even letter with your > right hand. That weakens the password significantly. For a six character alpha-numeric password with no special characters, you have (26*2+10)**6 possible passwords, or 56,800,235,584. Using your password generator, you have: >>> righthand = '23456qwertasdfgzxcvbQWERTASDFGZXCVB' >>> lefthand = '789yuiophjknmYUIPHJKLNM' >>> len(righthand) 35 >>> len(lefthand) 23 and therefore only: 35*23*35*23*35*23 = (35*23)**3 = 521,660,125 possible passwords. That's about one percent of the earlier figure, so you lose about 99% of the strength of the password. For eight character passwords the difference is even more dramatic: you reduce the strength of the password by a factor of roughly 99,999,995/100,000,000. In my opinion, if you're going to accept such a drastic reduction in password strength, better to go for a password that is easier to memorise than a hard-to-memorise-but-easy-to-type weak password. Here's one such algorithm: * think of a meaningful phrase you won't forget: e.g. "Snow White and the Seven Dwarves" * take the first letter of each word: "swatsd" * mix up the capitals and make it leet: "5Wat7D" * add some special characters if you can: "5W&t7D" * if it is not long enough, add a suffix or prefix or both: "p5W&t7D." And now you have a strong password that you can remember but is unlikely to be guessed. -- Steven D'Aprano From cjw at sympatico.ca Fri Jan 26 02:55:48 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 26 Jan 2007 02:55:48 -0500 Subject: how to unistall a Python package? In-Reply-To: <000601c74094$4d514e20$1400a8c0@mytomato> References: <000601c74094$4d514e20$1400a8c0@mytomato> Message-ID: With Windows, a few packages, eg. PythonWin, also modify the registry. numpy, the elaboration of numarray/numeric, and PythonWin have RemoveXXX.exe in C:\Python25. I don't know whether this is the standard approach. There doesn't seem to be a reference to Removal in the distutils document. Colin W. Wang Shuhao wrote: > Third party packages are put into $PYTHONHOME\Lib\site-packages after been installed, so to uninstall them, just go there and delete the directory contains all files of your package. > > > ----- Original Message ----- > From: "siggi" > Newsgroups: comp.lang.python > To: > Sent: Thursday, January 25, 2007 10:02 PM > Subject: how to unistall a Python package? > > >> Hi all, >> >> installing a package with 'setup.py' is easy. But how do I uninstall the >> package, once I want to get rid of it again? >> >> Thanks, >> >> siggi >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From jstroud at mbi.ucla.edu Tue Jan 30 19:49:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 30 Jan 2007 16:49:20 -0800 Subject: data design In-Reply-To: <1170201274.580256.182740@v45g2000cwv.googlegroups.com> References: <45bf5763$0$22792$426a34cc@news.free.fr> <1170183985.871094.155720@q2g2000cwa.googlegroups.com> <45bfbcc3$0$30950$426a74cc@news.free.fr> <1170201274.580256.182740@v45g2000cwv.googlegroups.com> Message-ID: Szabolcs Nagy wrote: >>Hurray for yaml! A perfect fit for my need! And a swell tool! >>Thanks a lot! > > > i warn you against yaml > it looks nice, but the underlying format is imho too complex (just > look at their spec.) > > you said you don't want python source because that's too complex for > the users. > i must say that yaml is not easier to use than python data structures. > > if you want userfriedly config files then ConfigParser is the way to > go. > > if you want somthing really simple and fast then i'd recommend s- > expressions of lisp > > also here is an identation based xml-like tree/hierarchical data > structure syntax: > http://www.scottsweeney.com/projects/slip/ > I've been spending the last 2 days weighing ConfigParser and yaml, with much thought and re-organizing of each file type. The underlying difference is that, conceptually, ini files are an absurdly limited subset of yaml in that ini files are basically limited to a map of a map. For instance, I have a copy_files section of a configuration. In order to know what goes with what you have to resort to gymnastics with the option names [copy_files] files_dir1 = this.file that.file path_dir1 = /some/path files_dir2 = the_other.file yet_another.file path_dir2 = /some/other/path In yaml, it might look thus. copy_files : - files : [this.file, that.file] path : /some/path - files : [the_other.file, yet_another.file] path : /some/other/path Both are readable (though I like equals signs in appearance over colons), but yaml doesn't require a lot of string processing to group the files with the paths. I don't even want to think the coding gymnastics required to split all of the option names and then group those with common suffixes. Now if the config file were for copying only, ini would be okay, because one could just have sections that group paths and dirs: [dir1] files = this.file, that.file path = /some/path [dir2] ... But if you need different kinds of sections, you have outgrown ini. In essence, ini is limited to a single dictionary of dictionaries while yama can express pretty much arbitrary complexity. James From kloro2006 at gmail.com Sun Jan 28 16:14:48 2007 From: kloro2006 at gmail.com (kloro) Date: 28 Jan 2007 13:14:48 -0800 Subject: working model of a microcoded computer Message-ID: <1170018888.634619.289950@s48g2000cws.googlegroups.com> This is somewhat off topic, but I think many programmers would be interested to look at a working model of a microcoded computer at: tomspages.com click on the link for 'Hack the Com puter Model.' It conveys among other things the physical events that underlie execution of a microcode instruction and, by extension, of machine language. I would like very much to get people's feedback on the thing. Thanks, tom arnall north spit, ca usa From ajsiegel at optonline.com Mon Jan 8 10:40:59 2007 From: ajsiegel at optonline.com (ajsiegel at optonline.com) Date: 8 Jan 2007 07:40:59 -0800 Subject: Xah's Edu Corner: Introduction to 3D Graphics Programing References: <1166836083.084101.25870@73g2000cwn.googlegroups.com> <458d7899$0$8725$ed2619ec@ptn-nntp-reader02.plus.net> <1167208399.089326.213540@a3g2000cwd.googlegroups.com> <1167230356.551596.193550@73g2000cwn.googlegroups.com> <1167255574.202660.176530@48g2000cwx.googlegroups.com> Message-ID: <1168270858.969940.282070@42g2000cwt.googlegroups.com> Xah Lee wrote: > Here's their license: > http://www.vpython.org/webdoc/visual/license.txt > > I read it wrong before. > Thanks for correction. > > This is superb! I'll be looking into vpython! > > Xah Of course it does what it does by resort to OpenGL and C++, so is part of the problem ;) I am looking forward to your tutorial efforts, and hoping those efforts can be accessed without exposure to too much polemics. Though if that is the price of admission, that is the price of admission. BTW, VPython is most of the way through a 4.xxx release which provides some nice additional functionality to the 3.xx series core - like transparency and texturing. Problem being the the lead developer has graduated and moved on, and the NSF funding that had supported the effort has run out. And the core folks around the project are either science educators or Python folks - there is little C++ expertise currently involved with the project. The project is looking for help. Anyone willing to jump in should perhaps reply here or at: visualpython-users at lists.sourceforge.net Art From dwoogle at gmail.com Wed Jan 3 18:46:55 2007 From: dwoogle at gmail.com (dwelden) Date: 3 Jan 2007 15:46:55 -0800 Subject: Sorting on multiple values, some ascending, some descending In-Reply-To: <1167852652.416990.158610@k21g2000cwa.googlegroups.com> References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> <1167852652.416990.158610@k21g2000cwa.googlegroups.com> Message-ID: <1167868015.112325.219410@i80g2000cwc.googlegroups.com> > The simplest way is to take advantage of sort-stability and do > successive sorts. For example, to sort by a primary key ascending and > a secondary key decending: > > L.sort(key=lambda r: r.secondary, reverse=True) > L.sort(key=lambda r: r.primary) > Excellent! That looks just like what I needed. > A less general technique is to transform fields in a way that reverses > their comparison order: > > L.sort(key=lambda r: (-r.age, r.height)) # sorts descending age > and ascending height This one I had figured out, but could not see how to get it to work for strings. Much obliged. From fredrik at pythonware.com Thu Jan 11 08:36:04 2007 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Jan 2007 14:36:04 +0100 Subject: what is the idiom for copy lots of params into self? References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com><1168481112.291651.89300@i39g2000hsf.googlegroups.com> <1168520386.457345.23680@i39g2000hsf.googlegroups.com> Message-ID: "Emin" wrote: > What made me ask the question in my original post was not so much that > I had to loop over the names I wanted to save, but whether it's okay to > mess with self.__dict__ or if there is another way I should be > assigning to self. http://effbot.org/pyref/setattr From Barry.Carroll at psc.com Fri Jan 19 18:59:11 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 19 Jan 2007 15:59:11 -0800 Subject: OT Annoying Habits (Was: when format strings attack) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A9D@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: Aahz [mailto:aahz at pythoncraft.com] > Sent: Friday, January 19, 2007 3:29 PM > To: python-list at python.org > Subject: Re: OT Annoying Habits (Was: when format strings attack) > > In article , > Carroll, Barry wrote: > > > >Secondly, can someone point me to the Standard Usenet Convention that > >mandates against top-posting. This is not sarcasm; I would really like > >to see it. <> > > Funny, I've been on Usenet for more than fifteen years, continuously > (and long-windedly -- but that's another matter) and I've never seen a > Usenet group where top-posting was standard. Anyway, here's a good > resource: > > http://www.xs4all.nl/%7ewijnands/nnq/nquote.html > -- > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ > > Help a hearing-impaired person: http://rule6.info/hearing.html My thanks to Aahz and the others who responded. I also did some Googling on my own. I found out that top-posting is the norm in the e-mail world. Bottom- and inline-posting are the norm in the newsgroup world. So I concede the point, and I'm bottom-posting like a good citizen. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From kylotan at gmail.com Thu Jan 11 07:16:39 2007 From: kylotan at gmail.com (Ben Sizer) Date: 11 Jan 2007 04:16:39 -0800 Subject: Ref count oddness with embedded Python... memory leak? Message-ID: <1168517799.771866.144660@77g2000hsv.googlegroups.com> Here's my test-case: #include int main(int argc, char *argv[]) { Py_Initialize(); Py_Finalize(); Py_Initialize(); Py_Finalize(); Py_Initialize(); Py_Finalize(); Py_Initialize(); Py_Finalize(); Py_Initialize(); Py_Finalize(); return 1; } Here's my output, with Python 2.5 built in debug mode on WinXP, no modifications: [7438 refs] [7499 refs] [7550 refs] [7601 refs] [7652 refs] Is this normal? It doesn't look very promising to me. -- Ben Sizer From tomas at fancy.org Wed Jan 3 13:30:53 2007 From: tomas at fancy.org (Tom Plunket) Date: Wed, 03 Jan 2007 10:30:53 -0800 Subject: list/dictionary as case statement ? References: <71pmp2tq1klma5urhkfiv8bpq6u8sgtj06@4ax.com> <501r8sF1dp76aU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Intels aren't RISC, are they? Not the ones in PCs. The OP didn't specify the CPU that's being used, however. -tom! -- From persed at princeton.edu Mon Jan 22 14:44:01 2007 From: persed at princeton.edu (Per B.Sederberg) Date: Mon, 22 Jan 2007 19:44:01 +0000 (UTC) Subject: Program eating memory, but only on one machine? (Solved, sort of) References: Message-ID: Per B.Sederberg princeton.edu> writes: > I'll see if I can make a really small example program that eats up memory on > our cluster. That way we'll have something easy to work with. Now this is weird. I figured out the bug and it turned out that every time you call numpy.setmember1d in the latest stable release of numpy it was using up a ton of memory and never releasing it. I replaced every instance of setmember1d with my own method below and I have zero increase in memory. It's not the most efficient of code, but it gets the job done... def ismember(a,b): ainb = zeros(len(a),dtype=bool) for item in b: ainb = ainb | (a==item) return ainb I'll now go post this problem on the numpy forums. Best, Per From arkanes at gmail.com Tue Jan 16 12:31:35 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 16 Jan 2007 11:31:35 -0600 Subject: Check a windows service In-Reply-To: <1168967374.568967.173690@11g2000cwr.googlegroups.com> References: <1168966952.965088.17740@l53g2000cwa.googlegroups.com> <1168967374.568967.173690@11g2000cwr.googlegroups.com> Message-ID: <4866bea60701160931g324777e1w7e5b0198a0cd24f4@mail.gmail.com> On 16 Jan 2007 09:09:34 -0800, Tim Golden wrote: > awel wrote: > > > I'm new in python and I would like to know if it's possible to check if > > a specific windows service is present and if it's possible how can I > > do? > > This is one way: > > http://tgolden.sc.sabren.com/python/wmi_cookbook.html#automatic_services > > You'd have to change that example slightly, but I > hope the principal is clear enough. If not, ask again. > > TJG > Here's some code cut & pasted from the demos included in the win32 module: import win32service import win32con def EnumServices(): resume = 0 accessSCM = win32con.GENERIC_READ accessSrv = win32service.SC_MANAGER_ALL_ACCESS #Open Service Control Manager hscm = win32service.OpenSCManager(None, None, accessSCM) #Enumerate Service Control Manager DB typeFilter = win32service.SERVICE_WIN32 stateFilter = win32service.SERVICE_STATE_ALL statuses = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter) for (short_name, desc, status) in statuses: print short_name, desc, status From martinglobal at gmail.com Mon Jan 29 16:42:16 2007 From: martinglobal at gmail.com (Martin Global) Date: 29 Jan 2007 13:42:16 -0800 Subject: We sell to everyone!!! Government, Wholesalers, Distributers, Entreprenuers.....www.martin-global.com Message-ID: <1170106936.496876.230580@q2g2000cwa.googlegroups.com> Martin Global is one of North America's leading importers of goods manufactured and produced throughout Asia. We are distinctively unique from other importers, as we have one of North America's largest networks linking our organization directly to thousands of manufacturers and suppliers in Asia and throughout the world. We at Martin Global are proud of our reputation for excellence: a reputation based on our commitment to the highest manufacturing and ethical standards. At Martin Global, all of our business relationships with customers, suppliers, manufacturers and employees rest on a foundation of integrity and trust. Mission Statement Martin Global puts the needs of its clients first! We strive to establish long-term personal relationships built upon clients' trust in our ability to provide superior products at competitive prices. Whether you're a large corporation, government entity or a sole proprietor, we take these relationships very seriously and we believe that our success is measured by the success of our clients and their return business. Inquiries always welcomed. Your message will responded to within 8 hours. Regards, Donovan Martin Martin Global www.martin-global.com From hg at nospam.org Wed Jan 24 03:05:22 2007 From: hg at nospam.org (hg) Date: Wed, 24 Jan 2007 09:05:22 +0100 Subject: My python programs need a GUI, wxPython or PyQt4? References: <45B76FE8.5080701@codebykevin.com> Message-ID: Kevin Walzer wrote: > Kevin Walzer wrote: > >> >> Tablelist: http://www.nemethi.de/ >> Tabelist for Tkinter (with Tile support): >> http://tkinter.unpythonic.net/wiki/TableListTileWrapper >> > > Additionally, here is a link to some screenshots for Tablelist: > > http://www.nemethi.privat.t-online.de/tablelist/screenshots.html > > > -- > Kevin Walzer > Code by Kevin > http://www.codebykevin.com Just for info - one of the reasons I stopped using Tkinter a few years ago was for the lack of print support (preview ...) - is there such an extension today ? hg From mateushenriquebrum at gmail.com Sun Jan 7 19:20:43 2007 From: mateushenriquebrum at gmail.com (mateushenriquebrum at gmail.com) Date: 7 Jan 2007 16:20:43 -0800 Subject: Table Message-ID: <1168215643.745782.34050@s80g2000cwa.googlegroups.com> Hello Someone know how do I get the collunm's number of a gkt.Table ? From bignose+hates-spam at benfinney.id.au Tue Jan 30 01:46:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Jan 2007 17:46:51 +1100 Subject: parent-child object design question References: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> Message-ID: <87hcu9xb8k.fsf@benfinney.id.au> "manstey" writes: > I have two classes. The first one wraps around an old-style class > called oref > > Class CacheClass(object): > def __init__(self, obj): > self.__data = obj > def __getattr__(self, attr): > return getattr(self.__data, attr) I presume the 'obj' argument to this class's __init__ method contains the 'oref' instance. It's a little confusing to call the argument to __getattr__ "attr", since it's actually the *name* of the attribute to be accessed, not the attribute itself. > The second class is much the same, also wrapping, but has some > attributes. > > class CacheProperty(object): > def __init__(self, obj, dicProperties={}): Setting a container class as a default argument is prone to error; the default argument gets created once, when the 'def' statement is executed. Better to default to None, and trigger on that inside the function. > self.__data = obj > lisProperties=[] > for key, val in dicProperties.iteritems(): > setattr(self, key, val) > lisProperties.append(key) > self.Properties = lisProperties The name of this class doesn't really tell me what an instance of the class *is*. Is it a "cache property", as the name seems to indicate? If so, why does a "cache property" instance itself contain a list of properties? > def __getattr__(self, attr): > return getattr(self.__data, attr) > > Here is my code: > > >>> MyClass = CacheClass(oref) This is a confusing example; MyClass implies that the object is a class, but this is now an instance of CacheClass, not a class. Also, it's conventional in Python to name classes in TitleCase, but to name instances (and functions) starting with lowercase. > >>> MyProperty = CacheProperty(oref2,{'Name':'Surname', 'Value':'Peter'}) > >>> setattr(MyClass,MyProperty.Name,MyProperty) This might be a good approach if you didn't know you were going to associate the object MyClass with the object MyProperty at the creation of MyProperty. However: > Now, the problem is that I want a method MyClass.MyProperty.Save() > to save the value of MyClass.MyProperty to the database backend on > disk, but the code for this is part of the wrapped oref code, and > thus is invoked only by > MyClass.set(MyProperty.Name,MyProperty.Value). This implies that there's a definite "each CacheProperty instance is associated with exactly one CacheClass instance" invariant. If that's true, the best thing to do is to pass MyClass to the constructor for the CacheProperty class, and have each instance set the relationship in the __init__ method. I don't know what a descriptive term for the relationship between the CacheClass instance and the CacheProperty instance is, so I'm going to use "parent"; you should choose something more descriptive. class CacheProperty(object): def __init__(self, obj, parent, properties=None): self.__data = obj self._bind_to_parent(parent) if properties is None: properties = {} self._accumulate_properties(properties) def _bind_to_parent(self, parent): setattr(parent, self.Name, self) def _accumulate_properties(self, properties): self.properties = [] for key, val in properties.iteritems(): setattr(self, key, val) self.properties.append(key) def __getattr__(self, name): return getattr(self.__data, name) -- \ "Marriage is a wonderful institution, but who would want to | `\ live in an institution." -- Henry L. Mencken | _o__) | Ben Finney From icetortoise at gmail.com Wed Jan 31 03:56:15 2007 From: icetortoise at gmail.com (Andy Wu) Date: 31 Jan 2007 00:56:15 -0800 Subject: Retrieve keywords a internet domain name Message-ID: <1170233775.215834.14340@a34g2000cwb.googlegroups.com> Hi All, I've been working on a domain parking project where we need to analyze a domain name, say "bookhotel", and get keywords(book, hotel) out of it, then use these keywords to do some search. There are two ways to do this as far as I can see, longest match and quickest match. Longest match: bookhotel -> check with a dictionary -> False bookhote -> dictionary -> False ... book -> dictionary -> True, kw1 = book then try the rest of the domain name hotel -> dictionary -> True, kw2 = hotel While quickest match starts with 'b'. The keywords sure will not be perfect, but I think these two will work for us at the moment. Any comments/suggestions on this? Also, does anyone know where I can find a decent dictionary that I can use to verify if a word is a valid English word? From garylinux at gmail.com Wed Jan 3 22:22:23 2007 From: garylinux at gmail.com (garylinux at gmail.com) Date: 3 Jan 2007 19:22:23 -0800 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> Message-ID: <1167880942.102299.241940@q40g2000cwq.googlegroups.com> I find that I can often live with a 0-60 sec. pause. and set command in a queue like then have a cron that runs once a min as the user you need to run this on that looks at the queue and sees if there are any pending I often use a sql database for this From ronrsr at gmail.com Tue Jan 2 00:57:39 2007 From: ronrsr at gmail.com (ronrsr) Date: 1 Jan 2007 21:57:39 -0800 Subject: Special Characters (Unicode, Ascii) in Python and MySQL Message-ID: <1167717459.802890.96740@n51g2000cwc.googlegroups.com> I have an MySQL database called zingers. The structure is: zid - integer, key, autoincrement keyword - varchar citation - text quotation - text I am having trouble storing text, as typed in latter two fields. Special characters and punctuation all seem not to be stored and retrieved correctly. Special apostrophes and single quotes from Microsoft Word are causing a special problem, even though I have ''ed all 's perhaps the encoding of the database itself should be different? it is currenlty latin_swedish_ci Input and output is through a browser. I think my problem may be that I need to encode the string before saving it in the databse. Can anyone point me in the right direction here? here's the error message: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 95: ordinal not in range(128) args = ('ascii', "update zingers set keywords = 'a;Action;b;Religi... \n \n \n ' where zid = 422", 95, 96, 'ordinal not in range(128)') encoding = 'ascii' end = 96 object = "update zingers set keywords = 'a;Action;b;Religi... \n \n \n ' where zid = 422" reason = 'ordinal not in range(128)' start = 95 the characters I am trying to add are startquote and endquote copied and pasted from Microsoft Word. Can anyone help me on this? bests, -rsr- From hg at nospam.org Thu Jan 25 10:30:07 2007 From: hg at nospam.org (hg) Date: Thu, 25 Jan 2007 16:30:07 +0100 Subject: Right-Justifying Numeric Output References: Message-ID: Rich Shepard wrote: > I have this print statement in a function: > > print '%2d $%11.2f $%10.2f $%9.2f $%9.2f' %(nper, pv, diff, ten, > bonus) > > and I would like to have the output right justified in the specified > field. My trials using .rjust(n) have produced that string in the output, > not the intended results. Is there a way of right justifying numeric > output? > > Thanks, > > Rich > > -- > Richard B. Shepard, Ph.D. | The Environmental Permitting > Applied Ecosystem Services, Inc. | Accelerator(TM) > Voice: 503-667-4517 Fax: > 503-667-8863 assuming max size = 10 #with spaces >> '% 10d' % 11 ' 11' #with zeros >>'%010d' % 11 '0000000011' hg From ocollioud at gmail.com Thu Jan 25 13:10:38 2007 From: ocollioud at gmail.com (olive) Date: 25 Jan 2007 10:10:38 -0800 Subject: ANN: Dejavu 1.5.0RC1 In-Reply-To: References: Message-ID: <1169748635.912754.191720@j27g2000cwj.googlegroups.com> Looks interesting... Do you consider a StorageManagers for Oracle ? Olive. On Jan 24, 11:57 pm, "Robert Brewer" wrote: > The Dejavu Object-Relational Mapper (version 1.5.0RC1) is now available > and in the public domain. Get it athttp://projects.amor.org/dejavu, > or from PyPI:http://www.python.org/pypi/Dejavu/1.5.0RC1. > > Dejavu is an Object-Relational Mapper for Python applications. It is > designed to provide the "Model" third of an MVC application. Dejavu > avoids making decisions in the framework which are better left to > developers, and avoids forcing developers to make decisions which are > better left to deployers. In particular, deployers are allowed to mix > and match storage mechanisms, including how and when to cache objects in > memory, making it easier for deployers to tune applications to their > particular environment. > > Dejavu provides: > > Modeling Layer > 1. A base Unit class for persisting objects to storage. > 2. A base UnitProperty class for persistent object attributes. > 3. ID Sequencers. > 4. Associations between Unit classes. > 5. Unit Engines, Rules, and Collections. > 6. Aggregation and analysis tools. > > Application Layer > 1. Expressions: pure Python lambda querying. This is perhaps the most > appealing feature of Dejavu. > 2. Sandboxes, which serve as Identity Maps, transaction boundaries, > and per-connection caches. > 3. An Arena class for application-level data. > > Storage Layer > 1. A base StorageManager class and specification. Unlike many ORMs, > Dejavu does not require you to have complete control of the back end. > 2. Specific StorageManagers for: > a. Microsoft SQL Server/MSDE > b. Microsoft Access (Jet) > c. PostgreSQL > d. MySQL > e. SQLite > f. Shelve > g. Firebird > h. RAM > i. Filesystem > > What's New in 1.5:http://projects.amor.org/dejavu/wiki/WhatsNewIn15 > > * Native ID sequencing. > * Distributed transactions and tested isolation levels. > * Complete database introspection and auto discovery. > > * New Firebird support. > * New RAM Storage Manager. > * New psycopg2 support. > * New support for using the sqlite3 module built into Python 2.5. > * Support for typed and typeless SQLite. > * Support for SQLite :memory: databases. > > * Complete numeric precision and scale support. > * Native date function support. > * Complete M x N type-adaptation. > * Bulletproof encoding support. > * New 'range' function which returns the closed interval [min(attr), > ..., max(attr)]. > * New 'sum' function which returns the sum of all non-None values for > the given cls.attr. > * Multiple and custom Associations. > * Improved performance (especially ADO). > * New JSON encoder/decoder. > * Short config names for Storage Managers. > * ADO: New support for the CURRENCY datatype. > * ADO: Improved string comparisons using Convert and StrComp. > > Upgrading to 1.5: > Seehttp://projects.amor.org/dejavu/wiki/UpgradeTo1.5 > > Documentation for 1.5:http://projects.amor.org/docs/dejavu/1.5.0RC1/ > > Robert Brewer > System Architect > Amor Ministries > fuman... at amor.org From gagsl-py at yahoo.com.ar Mon Jan 15 13:44:19 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 15:44:19 -0300 Subject: check if there is data in stdin without blocking In-Reply-To: <9uNqh.48239$X97.14123@newsfe18.lga> References: <4PMqh.47441$X97.9536@newsfe18.lga> <9uNqh.48239$X97.14123@newsfe18.lga> Message-ID: <7.0.1.0.0.20070115154356.03288828@yahoo.com.ar> At Monday 15/1/2007 05:55, hg wrote: >Well I'm testing under Linux but need support under Windows ... is there any >way to poll stdin somehow under both plateform ? I think you may want this portable getch function: -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From creechm at gmail.com Fri Jan 12 11:19:17 2007 From: creechm at gmail.com (Mark) Date: 12 Jan 2007 08:19:17 -0800 Subject: Need better run/edit method. I have to restart the shell after every script change. In-Reply-To: References: <1168544475.849070.92160@77g2000hsv.googlegroups.com> Message-ID: <1168618757.457350.184350@a75g2000cwd.googlegroups.com> Thanks guys. I'll give it a try. Brian Blais wrote: > Mark wrote: > > I'm currently running the IDLE shell under Python 2.5, on Windows XP. > > > > Every time I edit my .txt or .py file, I have to restart the IDLE shell > > for the changes to take effect. It's pretty annoying. Assuming IDLE is > > already open, here are the steps that I typically take: > > > > 1. Open .txt version of module or script using notepad > > 2. make changes > > 3. save .txt file as .txt file > > 4. save .txt file as .py file > > 5. reset IDLE > > 6. import module again > > > > why do you involve notepad, and .txt files? Instead, try this: > > 1. Run Idle > 2. Choose File/New Window > 3. Edit your .py file, and save it as a .py file > 4. Choose Run/Run Module > 5. Make changes, and save again > 6. Choose Run/Run Module > 7. etc... > > you don't need to close IDLE ever. IDLE refers to the editor, and the shell that > runs connected to it. If you have just the shell, you can open the editor with > File/New Window. If you have just the editor, you can choose Run/Python Shell or > Run/Run Module depending on what you want to do, to get the shell. > > You can also take a .py file in the Windows explorer, right-click, and choose "Open > with IDLE" to start editing it directly. > > You shouldn't save things as .txt, because then IDLE will not recognize it is python > you are writing, and the right-click trick probably won't work either. You should > never use Notepad, because it is just icky, and doesn't know about any programming > languages. :) > > Hope this helps, > > Brian Blais > > > -- > ----------------- > > bblais at bryant.edu > http://web.bryant.edu/~bblais From removethis.kartic.krishnamurthy at gmail.com Mon Jan 29 16:16:03 2007 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 29 Jan 2007 21:16:03 GMT Subject: Sourcing Python Developers In-Reply-To: <7xirepimw0.fsf@ruckus.brouhaha.com> References: <45BE4348.9020500@gmail.com> <7xirepimw0.fsf@ruckus.brouhaha.com> Message-ID: <45BE6411.1020508@gmail.com> Paul Rubin sayeth, on 01/29/2007 03:44 PM: > Kartic writes: >> In any case, we have immediate requirements for a Pythonista with C++, >> MySQL, XML, Debian expertise. Please email resume to: > > Generally it's ok to post here to the newsgroup with Python jobs. But > you should describe the specific openings you're trying to fill, and > their locations. Paul - Thanks for the clarification; will use the list _sparingly_ post jobs. The skills I listed are the once I have (Py, MySQL, C++, XML, Debian). Location: Torrance CA. Compensation: Commensurate with Experience. From nagle at animats.com Mon Jan 29 14:45:47 2007 From: nagle at animats.com (John Nagle) Date: Mon, 29 Jan 2007 19:45:47 GMT Subject: SQL connecting In-Reply-To: References: Message-ID: Scripter47 wrote: > Hey > > It got a problem with python to connect to my SQL DBs, that's installed > on my apache server. how do i connect to sql? Gettting data? Insert into > it? You need a third-party open source package called "MySQLdb". John Nagle From ptmcg at austin.rr.com Thu Jan 25 23:10:11 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Jan 2007 20:10:11 -0800 Subject: Pyparsing - Dealing with a Blank Value In-Reply-To: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> References: <1169774005.890880.259830@j27g2000cwj.googlegroups.com> Message-ID: <1169784611.477582.270450@v33g2000cwv.googlegroups.com> On Jan 25, 7:13 pm, "Steve" wrote: > Hi All, > > I've picked up thePyParsingmodule and am trying to figure out how to > do a simple parsing of some HTML source code. My specific problem is > dealing with an element that is blank. > I'd also suggest use the makeHTMLTags helper module for the TR and TD tags: trStart,trEnd = makeHTMLTags("TR") tdStart,tdEnd = makeHTMLTags("TD") makeHTMLTags includes a much more robust definition than just Literal(""), including recognition of attributes and tolerance of upper/lower case. -- Paul From nospam at riddergarn.dk Sun Jan 28 06:19:05 2007 From: nospam at riddergarn.dk (Scripter47) Date: Sun, 28 Jan 2007 12:19:05 +0100 Subject: Mulig SPAM: Re: IP address In-Reply-To: References: Message-ID: <45BC86A9.2010509@riddergarn.dk> Klaus Alexander Seistrup skrev: > Scripter47 wrote: > >> How do i get my ip address? >> >> in cmd.exe i just type "ipconfig" then it prints: >> ... >> IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 >> ... >> how can i do that in python?? > > #v+ > > python -c 'import re, urllib; print re.findall("Your IP: (.+?)", urllib.urlopen("http://myip.dk/").read())[0]' > > #v- > > Cheers, > Hmm then you need Internet connecting. can i do it without that? ? and it doesn't work either :( From jura.grozni at gmail.com Sun Jan 28 18:01:37 2007 From: jura.grozni at gmail.com (azrael) Date: 28 Jan 2007 15:01:37 -0800 Subject: Data structure and algorithms In-Reply-To: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> References: <1170024965.321036.206010@m58g2000cwm.googlegroups.com> Message-ID: <1170025297.838143.191740@j27g2000cwj.googlegroups.com> I'm not a kid who heard that Python is simple, so he wants to use it and throw it away. I discovered it about 2 months ago, and I learnt it better then c in 2 years. I want to use python for this test because i love it. I am amazed about what i can do i such little time. My god, I even printed the python logo on my laptop. Please guys help me. I don't want to go back to C to pass the test From grante at visi.com Tue Jan 2 17:16:24 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 02 Jan 2007 22:16:24 -0000 Subject: list/dictionary as case statement ? References: Message-ID: <12plmdoem9bg575@corp.supernews.com> On 2007-01-02, Stef Mientki wrote: > If I'm not mistaken, I read somewhere that you can use > function-names/references in lists and/or dictionaries, but > now I can't find it anymore. > > The idea is to build a simulator for some kind of micro > controller (just as a general practise, I expect it too be > very slow ;-). > > opcodes ={ > 1: ('MOV', function1, ...), > 2: ('ADD', function2, ), > 3: ('MUL', class3.function3, ) > } > > def function1 > # do something complex > > > Is this possible ? Yes. What you're implementing is commonly referred to as a "dispatcher", and they're often done with a dictionary exactly as you show. -- Grant Edwards grante Yow! I guess you guys got at BIG MUSCLES from doing too visi.com much STUDYING! From dilbert01 at gmail.com Mon Jan 22 12:49:02 2007 From: dilbert01 at gmail.com (alessandro) Date: 22 Jan 2007 09:49:02 -0800 Subject: closing a "forever" Server Socket In-Reply-To: References: <1169123381.930403.24170@38g2000cwa.googlegroups.com> <1169143715.222186.30530@51g2000cwl.googlegroups.com> <1169482385.253887.249030@51g2000cwl.googlegroups.com> Message-ID: <1169488142.312711.322320@51g2000cwl.googlegroups.com> Oh my God! it's really so complicated? 3 modules (threading, SocketServer, select) only for design a way to shutdown a TCP server???? ...but they told me that python was easy... :) I'm working on a simulator and I have a monitor server that collects information. I can shutdown it using Ctrl-C from the keyboard but for my purpose could be very nice if I introduce a timer. So I could launch my monitor like this: ./monitor 100 and my monitor will run for 100 seconds. For this I'm using the Timer class provided by threading module, I have implemented a function like this: def shutdown(): sys.exit() but it doesen't work because the server remain alive...maybe SocketServer create immortal server... I need only to close my application, there is a way to force the server thread to close? thanks! Alessandro Laszlo Nagy ha scritto: > alessandro ?rta: > > thanks > > > > infact the server_forever() method is only a serve() method inside an > > infinite loop. > > > > many thanks again, > > > Here is a snipped that show a "software terminateable threading TCP > socker server". The "server" object is a SocketServer instance, > server_stopped is a threading.Event instance. You should also import the > "select" module. > > srvfd = server.fileno() > while not server_stopped.isSet(): > ready = select.select([srvfd], [], [], 1) # Give one second > for incoming connection so we can stop the server in seconds > if srvfd in ready[0]: > server.handle_request() > else: > pass # log('No incoming connection, retrying') From mheslep at gmail.com Fri Jan 12 15:37:25 2007 From: mheslep at gmail.com (mheslep at gmail.com) Date: 12 Jan 2007 12:37:25 -0800 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: <1168634245.604635.26860@38g2000cwa.googlegroups.com> Konrad Hinsen wrote: .... Perhaps we should start a > special interest group? Not so much in order to work on a single > project; I believe that at the current state of parallel computing we > still need many different approaches to be tried. But an exchange of > experience could well be useful for all of us. > + 1 -Mark From gagsl-py at yahoo.com.ar Wed Jan 24 21:26:26 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 24 Jan 2007 23:26:26 -0300 Subject: difflib qualm In-Reply-To: <2adc542f0701241805i79b79580y2522ec854e49621d@mail.gmail.co m> References: <2adc542f0701241805i79b79580y2522ec854e49621d@mail.gmail.com> Message-ID: <7.0.1.0.0.20070124231815.044b9058@yahoo.com.ar> At Wednesday 24/1/2007 23:05, Sick Monkey wrote: >I am trying to write a python script that will compare 2 files which >contains names (millions of them). > >More specifically, I have 2 files (Files1.txt and >Files2.txt). Files1.txt contains 180 thousand names and Files2.txt >contains 34 million names. > >I have a script which will analyze these two files and store them >into 2 different lists (fileList1 and fileList2 respectivly). I >have imported the diflib library and after the lists are created, >matching on the following criteria " " for diflib -> (just the names >that are similar between the two files). > >This works perfectly for hundreds of names but is taking forever for >millions of them; thus not really efficient. > >Does anyone have any idea on how to get this more >efficient? (speaking of Time and RAM) > >Any advice would be greatly appreciated. (NOTE: I have been >trying to study multithreading, but have not really grasp the >concept. So I may need some examples.) When you say "names" you mean people's names? So you want to match, say, Levenshtein Vladimir to Lebenstain V.? And you only have the names to match? Not a good candidate for difflib. See this paper: Record Linkage: A Machine Learning Approach, A Toolbox, and A Digital Government Web Service (2003) Mohamed G. Elfeky, Vassilios S. Verykios, Ahmed K. Elmagarmid, Thanaa M. Ghanem, Ahmed R. Huwait. http://citeseer.ist.psu.edu/elfeky03record.html and you can get other pointers from the Levenshtein distance article in Wikipedia and http://en.wikipedia.org/wiki/Fuzzy_string_searching -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Thu Jan 4 21:21:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 04 Jan 2007 23:21:53 -0300 Subject: Draw rectangle on a Window DC In-Reply-To: <459cd1e4.0232d77c.0893.ffff821d@mx.google.com> References: <459cd1e4.0232d77c.0893.ffff821d@mx.google.com> Message-ID: <7.0.1.0.0.20070104230719.05afb190@yahoo.com.ar> At Thursday 4/1/2007 07:07, Raymond wrote: >I want to Draw rectangle on Dc when gived a position. Can you teach >me? Let me view your code? This is more a Windows question. See http://msdn.microsoft.com/library/en-us/gdi/rectangl_4b03.asp py>from win32gui import GetDC py>hdc=GetDC(0) py>from win32gui import Rectangle py>Rectangle(hdc, 100,100, 300,300) py>ReleaseDC(hdc,0) 0 py> You should see a white square on your screen. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From Barry.Carroll at psc.com Tue Jan 23 18:32:34 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 23 Jan 2007 15:32:34 -0800 Subject: Overloading assignment operator Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595AA4@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: Achim Domma [mailto:domma at procoders.net] > Sent: Tuesday, January 23, 2007 10:25 AM > To: python-list at python.org > Subject: Overloading assignment operator > > Hi, > > I want to use Python to script some formulas in my application. The user > should be able to write something like > > A = B * C > > where A,B,C are instances of some wrapper classes. Overloading * is no > problem but I cannot overload the assignment of A. I understand that > this is due to the nature of Python, but is there a trick to work around > this? > All I'm interested in is a clean syntax to script my app. Any ideas are > very welcome. > > regards, > Achim Hello, Achim, I asked this question (in a different context) some months ago on the Python tutor mailing list (tutor at python.org). The answer I got is summarized below. ** There is no assignment operator in Python, assignment is a ** binding of an object to a name. (Alan Gauld) * ... the assignment operator is used to assign an * object to a name in the current namespace... IOW, you cannot "overload * the assignment operator." (wesley chun) Mr. Chun went on to describe a way to accomplish something similar, using properties. I reprint it here, slightly rewritten to match your use case. * ...here is where * properties become useful. you can create a getter, setter, and even a * deleter and doc string if you want. here's how you use it... add the * following to your class: * def get_result(self): * return self.__result * * def set_result (self, expression): * self.__result = expression * * result = property(get_result, set_ result, doc='result of operations') * * ----- * * in actuality, the value is stored in self.__result, but access is via * self.result. this should give you what you need provided you are happy * with using "A.result = B * C" vs. "A = B * C", the latter of which * will never work the way you want. ... I have tested this using the admittedly simple-minded code snipped below. >>>>>>>>>> @BCARROLL[Python]|3> class Aclass: |.> def __init__(self): |.> __result = None |.> def get_result(self): |.> return self.__result |.> def set_result (self, result): |.> self.__result = result |.> result = property(get_result, set_result, doc='result of expression') |.> @BCARROLL[Python]|5> A = Aclass() @BCARROLL[Python]|7> a.result = 2*3 @BCARROLL[Python]|8> a.result <8> 6 @BCARROLL[Python]|9> a.result = 25.0 * 5.25 @BCARROLL[Python]|10> a.result <10> 131.25 @BCARROLL[Python]|11> >>>>>>>>>> HTH Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From anthra.norell at vtxmail.ch Thu Jan 11 07:20:45 2007 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Thu, 11 Jan 2007 13:20:45 +0100 Subject: Type casting a base class to a derived one? Message-ID: <45A62B9D.7080805@vtxmail.ch> Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? class Derived (Base): def __init__ (self, base_object): # ( copy all attributes ) ... This looks expensive. Moreover __init__ () may not be available if it needs to to something else. Thanks for suggestions Frederic From bdesth.quelquechose at free.quelquepart.fr Mon Jan 8 16:08:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Jan 2007 22:08:40 +0100 Subject: Why less emphasis on private data? In-Reply-To: <1168283295.899914.125400@38g2000cwa.googlegroups.com> References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168283295.899914.125400@38g2000cwa.googlegroups.com> Message-ID: <45a2ac91$0$316$426a74cc@news.free.fr> time.swift at gmail.com a ?crit : > Wow, I got a lot more feedback than I expected! > > I can see both sides of the argument, both on technical merits, and > more philosophical merits. When I first learned C++ I felt > setters/getters were a waste of my time and extra code. When I moved > to C# I still felt that, and with their 'Property" syntax I perhaps > felt it more. What changed my mind is when I started placing logic in > them to check for values and throw expections or (hopefully) correct > the data. That's probably reason one why I find it weird in Python Python does have properties too. The point is that you can as well start with a plain attribute, then turn it into a computed one when (and if) needed. > Reason two is, as the user of a class or API I *don't care* what is > going on inside. Very true... until you have a legitimate reason to mess with implementation because of a use case the author did not expect. > All I want visible is the data that I can change. The > '_' convention is nice.. I do see that. I guess my old OOP classes are > hard to forget about. Access restriction is not a mandatory part of OO. Of course, objects are supposed to be treated as "black boxes", but that's also true of a binary executable, and nothing (technically) prevents you to open it with an hex editor and hack it as you see fit... But then, you would not complain about strange bugs, would you ?-) > I feel that the state of an object should be > "stable" and "valid" at all times, That's fine. Just remember that, in Python, methods are attributes too, and can be dynamically modified too. So when thinking about "object state", don't assume it only implies "data" attributes. Heck, you can even dynamically change the *class* of a Python object... > and if its going into an unstable > state - error then, not later. That's why I like being able to protect > parts of an instances state. If, as a provider of a calculation engine, > I let the user change the internal state of the engine, I have no > assurances that my product (the engine) is doing its job... If you follow the convention, you are not responsible for what happens to peoples messing with implementation. period. Just like you're not responsible for what happens if someone hack your binary executable with an hex editor. Welcome to Python, anyway. From jpellerin at gmail.com Wed Jan 31 23:31:27 2007 From: jpellerin at gmail.com (JP) Date: 31 Jan 2007 20:31:27 -0800 Subject: ANN: nose 0.9.2 released Message-ID: <1170304286.960583.210830@h3g2000cwc.googlegroups.com> nose is a discovery-based unittest extension that provides an alternate test discovery and running process for unittest, one that is intended to mimic the behavior of py.test as much as is reasonably possible without resorting to too much magic. nose 0.9.2 includes quite a few bug fixes and new features. The most significant are the new nosetests setuptools command, contributed by James Casbon, better support for python 2.2 thanks to a patch from Chad Whitacre, and some useful utilities for testing Twisted programs and writing decorators contributed by Antoine Pitrou. Thanks to them all, and the many other folks who contributed patches and filed bug reports and feature requests. For more information, see: http://somethingaboutorange.com/mrl/ projects/nose/ nose's project home has moved from python hosting to Google code. Please update your svn checkouts and bookmarks. To check out the current trunk: svn co http://python-nose.googlecode.com/svn/trunk To file issues, go to the new issues page: http://code.google.com/p/python-nose/issues/list To read up on features, writing plugins, and other topics, visit the new wiki: http://code.google.com/p/python-nose/w/list From thomas.mohme at gmx.net Wed Jan 31 03:11:46 2007 From: thomas.mohme at gmx.net (Thomas) Date: 31 Jan 2007 00:11:46 -0800 Subject: Can't install Turbogears (with pysqlite) on Windows Message-ID: <1170231106.741090.249460@j27g2000cwj.googlegroups.com> Hi there! Installing TurboGears out-of-the-box (egg-based) on Windows doesn't work because I can't compile the extensions needed for the required pysqlite (also egg- based): Installed c:\programme\python24\lib\site-packages\turbogears-1.0.1- py2.4.egg Processing dependencies for TurboGears[standard,testtools]>=1.0 Searching for pysqlite Reading http://www.python.org/pypi/pysqlite/ Reading http://pysqlite.org/ Reading http://www.python.org/pypi/pysqlite/2.3.3 Best match: pysqlite 2.3.3 Downloading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ pysqlite-2.3.3.tar.gz Processing pysqlite-2.3.3.tar.gz Running pysqlite-2.3.3\setup.py -q bdist_egg --dist-dir c:\temp \easy_install-ovrxv0\pysqlite-2.3.3\egg-dist-tmp-0ynhfx warning: no files found matching 'doc\*.html' error: Setup script exited with 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. To get away without the need to compile the pysqltite extensions I tried to install the Windows-binary package of pysqlite manually before installing TG this also doesn't work, because easy_install doesn't know anything of my fresh installed pysqlite and tries to install the egg from cheeseshop (with the above error . . .). Any suggestions to get beyond this? Is it possible to "tweak" the TG egg-installation so that it won't try to "easy_install pysqlite"? For the application I'm intending to build with TurboGears I don't even need pysqlite :( Thomas From citronelu at yahoo.com Wed Jan 24 16:35:51 2007 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 24 Jan 2007 13:35:51 -0800 Subject: wxPython: panel not fully painted Message-ID: <1169674550.837006.304370@q2g2000cwa.googlegroups.com> Hi, I'm new to wxpython, and the following code is my first serious attempt: #~ start code import wx class MyPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.parent = parent button = wx.Button(self, -1, "Refresh") button.SetPosition((100, 100)) button.SetFocus() self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button) def OnCloseMe(self, event): self.parent.f_redraw(self) pass class MyFrame(wx.Frame): def __init__( self, parent, ID, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE ): wx.Frame.__init__(self, parent, ID, title, pos, size, style) def f_redraw(self, kill_window): kill_window.Destroy() MyPanel(self, -1) #~ self.SendSizeEvent() wxApp = wx.App() f = MyFrame(None, -1, "App Title") MyPanel(f, -1) f.Show() wxApp.MainLoop() #~ end code My problem is: when I press the "refresh" button, the new panel is painted only as a 20x20 pixels square on the top right side of the frame. If I resize the frame, the panel is repainted correctly (that's why I inserted the self.SendSizeEvent() line - commented above). Is there something I'm missing, or this is normal ? I'm using python 2.4.3 and wxpython 2.8.1.1 unicode, on WinXP SP2. Windows extensions are also installed. From simon at brunningonline.net Fri Jan 12 15:00:03 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 12 Jan 2007 20:00:03 +0000 Subject: Rational Numbers In-Reply-To: References: Message-ID: <8c7f10c60701121200g5acb42acna447d716652a75af@mail.gmail.com> On 12 Jan 2007 19:41:52 GMT, Nick Maclaren wrote: > Sigh. I was hoping not to have that myth perpetrated again. > > Financial calculations need decimal FIXED-point, with a precisely > specified precision. It is claimed that decimal FLOATING-point > helps with providing that, but that claim is extremely dubious. > I can explain the problem in as much detail as you want, but would > very much rather not. Sorry, Nick, you might have to. ;-) I'm not educated in these matters, so I'd genuinely like to know why you say that. Not educated, but I do have some experience; I've used both fixed and floating point Decimal types extensively, and I've found floating types superior. More fiddly, certainly, 'cos you have to explicitly round back down to the precision that you want when you want. But explicit is better than implicit - the number of subtle rounding bugs that I've had to fix 'cos someone didn't realise where rounding was occurring is, uh, well, it happens from time to time. ;-) What am I missing? -- Cheers, Simon B simon at brunningonline.net From arkanes at gmail.com Wed Jan 24 12:16:57 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 11:16:57 -0600 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <4866bea60701240916l604b969u33cd1db70494b516@mail.gmail.com> On 1/23/07, John Nagle wrote: > The major complaint I have about Python is that the packages > which connect it to other software components all seem to have > serious problems. As long as you don't need to talk to anything > outside the Python world, you're fine. But once you do, things > go downhill. MySQLdb has version and platform compatibility > problems. So does M2Crypto. The built-in SSL support is weak. > Even basic sockets don't quite work right; the socket module > encapsulates the timeout mechanism but doesn't get it right. > > In the Perl, Java, PHP, and C/C++ worlds, the equivalent > functions just work. That's because, in those worlds, either the > development team for the language or the development team > for the subsystem takes responsibility for making them work. > Only Python doesn't do that. > > Python has been around long enough that this should have > been fixed by now. > > John Nagle This just isn't correct. You think that socket libraries don't have incompatibilities in C and that C++ libraries don't have versioning problems? You think that SSL works right from Java in all cases, or that changing your mysql client libraries underneath PHP won't affect it? From wolf_tracks at invalid.com Sun Jan 21 19:40:05 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 22 Jan 2007 00:40:05 GMT Subject: Beginners Tutorial in PDF Format? In-Reply-To: <1169415358.277431.130640@s34g2000cwa.googlegroups.com> References: <_6Qsh.51414$wc5.5373@newssvr25.news.prodigy.net> <1169415358.277431.130640@s34g2000cwa.googlegroups.com> Message-ID: Robert Hicks wrote: > W. Watson wrote: >> I'd like to print a tutorial in one fell swoop, but it seems most on the >> various sites are page by page embedded descriptions in the page. Any >> available as a pdf? >> >> Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) >> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >> >> Two laws Newton and Einstein didn't discover: >> 1. Time is money. >> 2. Matter will be damaged in direct proportion >> to its value. >> -- >> Web Page: > > http://docs.python.org/download.html > > http://www.diveintopython.org/ > > HTH > > Robert > Thanks, but the first url takes me to a web page that contains the complete tutorial. Does choosing pdf (USA) in the table download a file that contains all the documents on the list below and to the left? Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Two laws Newton and Einstein didn't discover: 1. Time is money. 2. Matter will be damaged in direct proportion to its value. -- Web Page: From kw at codebykevin.com Wed Jan 24 10:32:28 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 24 Jan 2007 10:32:28 -0500 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: <45B76FE8.5080701@codebykevin.com> Message-ID: <45B77C0C.1010202@codebykevin.com> hg wrote: > Kevin Walzer wrote: > >> Kevin Walzer wrote: >> >>> Tablelist: http://www.nemethi.de/ >>> Tabelist for Tkinter (with Tile support): >>> http://tkinter.unpythonic.net/wiki/TableListTileWrapper >>> >> Additionally, here is a link to some screenshots for Tablelist: >> >> http://www.nemethi.privat.t-online.de/tablelist/screenshots.html >> >> >> -- >> Kevin Walzer >> Code by Kevin >> http://www.codebykevin.com > > Just for info - one of the reasons I stopped using Tkinter a few years ago > was for the lack of print support (preview ...) - is there such an > extension today ? > > hg > Printing is the one glaring omission from Tk/Tkinter--at least a unified printing framework. There are platform-specific extensions for Mac and Windows. On *Nix, I think most Tk/Tkinter programs just call lpr. None of these libraries work in quite the same way, so there isn't a simple way to simply call a standard Tk/Tkinter function to print your data. This recent thread on comp.lang.tcl discusses the issue: http://groups.google.com/group/comp.lang.tcl/browse_thread/thread/735c4612541f8669/707463acf6d02c46? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From tpochep at mail.ru Mon Jan 22 06:50:30 2007 From: tpochep at mail.ru (tpochep) Date: 22 Jan 2007 03:50:30 -0800 Subject: python grammar Message-ID: <1169466630.014322.232500@l53g2000cwa.googlegroups.com> Hello. In 'augop' non-terminal : http://docs.python.org/ref/augassign.html the delimiter '//=' was skipped. Why? In 'Boolean operations': http://docs.python.org/ref/Booleans.html In 'expression' rule - what does 'if', 'else' mean? I guess 'if' and 'else' must be keywords, not non-terminals. From steve at holdenweb.com Wed Jan 10 13:26:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 10 Jan 2007 18:26:24 +0000 Subject: Is there a way to protect a piece of critical code? In-Reply-To: <000b01c734a0$2f635840$03000080@hendrik> References: <000b01c734a0$2f635840$03000080@hendrik> Message-ID: <45A52FD0.60802@holdenweb.com> Hendrik van Rooyen wrote: > Hi, > > I would like to do the following as one atomic operation: > > 1) Append an item to a list > 2) Set a Boolean indicator > > It would be almost like getting and holding the GIL, > to prevent a thread swap out between the two operations. > - sort of the inverted function than for which the GIL > seems to be used, which looks like "let go", get control > back via return from blocking I/O, and then "re - acquire" > > Is this "reversed" usage possible? > Is there some way to prevent thread swapping? > This seems to me to be a typical example of putting the cart before the horse. Therefore, please don't think that what follows is directed specifically at you: it's directed at everybody who thinks that their problem is something other than it really is (of course, my extensive experience on c.l.py plus my well-known psychic powers uniquely qualify me to explain to you that you don't understand your own problem). > The question arises in the context of a multi threaded > environment where the list is used as a single producer, > single consumer queue - I can solve my problem in various > ways, of which this is one, and I am curious as to if it is > possible to prevent a thread swap from inside the thread. > Of course you will know what they say about curiosity [1]. You don't say what the Boolean indicator is for. My natural inclination is to assume it's to say whether there's anything in the list. The Twisted crew can tell you this is a terrible mistake,. What you should really do is define a function that waits until there is something to put on the list and then returns a deferred that will eventually indicate whether the insertion was successful [2]. But your *actual* problem appears to be the introduction of critical sections into your program, a question about which computer scientists have written for over forty years now, albeit in the guise of discussions about how to get a good meal [3]. I could go on, but I am realising as I write that less and less of this is really relevant to you. In short, please don't try to reinvent the wheel when there are wheelwrights all around and a shop selling spare wheels just around the corner. Python is already replete with ways to implement critical sections and thread-safe queuing mechanisms [5]. I could, of course, say http://www.justfuckinggoogleit.com/search.pl?query=python+atomic+operation but that would seem rude, which is against the tradition of c.l.py. Besides which the answers aren't necessarily as helpful as what's been posted on this thread, so I'll content myself with saying that one's can often be better spent R'ing TFM than posting on this newsgroup, but that while Google /may/ be your friend it's not as good a friend as this newsgroup. If it isn't obvious that this post was meant more to amuse regular readers than inform and/or chastise someone who isn't (yet) one then please accept my apologies. Fortunately I don't normally go on like this more than once a year, so now it's hey ho for 2008 [6]. If you have been, thank you for reading. If you haven't then I guess you won't be reading this either. Have a nice day. And a Happy New Year to all my readers. regards Steve [1]: It killed the cat, thereby letting MSDOS's "type" command get a toehold and leaving people to fight about whether "less" really was "more" or not. [2]: Of course I'm joking. But it seems that Twisted's detractors don't have much of a sense of humour, so it's much more interesting to poke fun at Twisted, which at least has the merit of having been designed by real human beings with brains and everything. Though I have never seen any of them take a beer. [4]. [3] The UNIX fork() system call is actually named in honour of Edsger Dijkstra's discussions of the philosophers' problem, a classic text in the development of critical sections. Not a lot of people know that. Mostly because I just made it up. [4] That's this week's dig at both the Twisted community. I cheerfully admit that although this assertion is true it's a simple attempt to give currency to a scurrilous fabrication. I'm hoping I can persuade the Twisted crew to descend on PyCon /en masse/, thereby multiplying the fun quotient by 1.43. [5] Including thread.Lock and Queue.Queue - I bet you're getting sorry you asked now, aren't you? [6] Which will be the year after 2007, which will be the year of Python 3000. Or not, depending on whether Py3k is a dead parrot or not. I'm personally betting on "not". But not necessarily on 2007. -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From libintr at gmail.com Sun Jan 28 02:25:01 2007 From: libintr at gmail.com (lee) Date: 27 Jan 2007 23:25:01 -0800 Subject: import from future Message-ID: <1169969100.946843.111770@p10g2000cwp.googlegroups.com> what are the things that we can do with import from future usage.....i heard its very interesting......thanks From donn at u.washington.edu Thu Jan 18 17:26:35 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 18 Jan 2007 14:26:35 -0800 Subject: How to find out if another process is using a file References: Message-ID: In article , nmm1 at cus.cam.ac.uk (Nick Maclaren) wrote: > In article , > Donn Cave writes: > |> In article , > |> "Gabriel Genellina" wrote: > |> > "Tom Wright" escribi? en el mensaje > |> > news:eoo6vd$33u$1 at gemini.csx.cam.ac.uk... > |> > Use os.open with the O_EXCL flag; will fail if the other process has the > |> > file still open (and will fail if another process is reading the file, > |> > too, > |> > not just if someone is writing). > |> > |> O_EXCL fails if the file exists at all - whether closed or open. > > Yes. In theory. In practice, it usually works on normal files, provided > that all opens are local. Under some circumstances, it will even work > for NFS mounted files, as far as I recall. Mm, by "fail", I meant An attempt to open with O_EXCL set will "fail" if the file exists at all, i.e., the file will not be opened, a negative value will be returned, and errno will be set to EEXIST. What I neglected to mention is that this effect obtains when O_EXCL is used in combination with O_CREAT. Without O_CREAT, O_EXCL doesn't mean anything and is ignored. If there is any significant difference between theory and practice in this matter, it's news to me. Donn From tsuraan at gmail.com Mon Jan 8 12:19:40 2007 From: tsuraan at gmail.com (tsuraan) Date: Mon, 8 Jan 2007 11:19:40 -0600 Subject: Suitability for long-running text processing? In-Reply-To: <4866bea60701080849h16d1dacew7a0abe950726c006@mail.gmail.com> References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> <4866bea60701080849h16d1dacew7a0abe950726c006@mail.gmail.com> Message-ID: <84fb38e30701080919r41d52fb6nc5ee31f12e901ef3@mail.gmail.com> > My first thought was that interned strings were causing the growth, > but that doesn't seem to be the case. Interned strings, as of 2.3, are no longer immortal, right? The intern doc says you have to keep a reference around to the string now, anyhow. I really wish I could find that thing I read a year and a half ago about python never collecting small strings, but I just can't find it anymore. Maybe it's time for me to go source diving... -------------- next part -------------- An HTML attachment was scrubbed... URL: From tew24 at spam.ac.uk Mon Jan 15 10:37:26 2007 From: tew24 at spam.ac.uk (Tom Wright) Date: Mon, 15 Jan 2007 15:37:26 +0000 Subject: Default event handlers in wxPython Message-ID: Hi all I'm writing my first wxPython app and am having a problem with event handlers. I've set up a multi-part status bar and would like all the tooltips, menu help strings etc. to go into the second part of it. Is there some easy way of doing this? I've not found one, so have set up the following for the menu: self.Bind(wx.EVT_MENU_HIGHLIGHT, self.OnMenuHighlight) def OnMenuHighlight(self, event): self.SetStatusText(event.GetEventObject().GetHelpString(event.GetMenuId()), 1) ...this works fine. I've tried to set up the same for the toolbar: self.Bind(wx.EVT_TOOL_ENTER, self.OnToolbarHighlight) def OnToolbarHighlight(self, event): self.SetStatusText(event.GetEventObject().GetToolLongHelp(event.GetSelection()), 1) ...and this doesn't work. Well, it puts the text in the second part of the toolbar as requested, but the default handler is still being called and this messes up the first part of the toolbar which I want it to leave alone. How do I completely override the default handler for the toolbar? This method worked fine for menus and I'm a bit stuck. (ignore the indentation on the above examples - I know it's wrong, but long lines and usenet don't mix) -- I'm at CAMbridge, not SPAMbridge From citronelu at yahoo.com Sun Jan 28 18:37:26 2007 From: citronelu at yahoo.com (citronelu at yahoo.com) Date: 28 Jan 2007 15:37:26 -0800 Subject: wxPython: panel not fully painted In-Reply-To: References: <1169674550.837006.304370@q2g2000cwa.googlegroups.com> Message-ID: <1170027446.670921.140410@q2g2000cwa.googlegroups.com> Thank you. From melih.onvural at gmail.com Wed Jan 31 00:43:13 2007 From: melih.onvural at gmail.com (Melih Onvural) Date: 30 Jan 2007 21:43:13 -0800 Subject: Executing Javascript, then reading value In-Reply-To: References: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> <1170105229.984079.219180@l53g2000cwa.googlegroups.com> Message-ID: <1170222193.579676.282040@m58g2000cwm.googlegroups.com> In fact what you're describing is exactly what I needed. I ended up finding a way to execute the javascript using Rhino and then capturing the result. Not exactly what I wanted to do, but once I found it out, it works. Melih Onvural On Jan 30, 2:57 pm, John Nagle wrote: > Melih Onvural wrote: > > Thanks, let me check out this route, and then I'll post the results. > > > Melih Onvural > > > On Jan 29, 4:04 pm, Jean-Paul Calderone wrote: > > >> On 29 Jan 2007 12:44:07 -0800, Melih Onvural > >> wrote: > > >>> I need to execute some javascript and then read the value as part of a > >>> program that I am writing. I am currently doing something like > >>> this:Python doesn't include a JavaScript runtime. You might look into > >>> the > > >> stand-alone Spidermonkey runtime. However, it lacks the DOM APIs, so it > >> may not be able to run the JavaScript you are interested in running. There > >> are a couple other JavaScript runtimes available, at least. If > >> Spidermonkey is not suitable, you might look into one of them. > > This is getting to be a common problem. One used to be able to > look at web pages from a program by reading the HTML. Now you need to > load the page into a browser-like environment, run at least the > OnLoad JavaScript, and then start looking at the document object module. > This requires a browser emulator, a browser without a renderer. > Useful for spam filters and such. > > It's not clear if the original poster needs that much capability, > though. > > John Nagle From gert.cuykens at gmail.com Mon Jan 15 17:41:03 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Mon, 15 Jan 2007 23:41:03 +0100 Subject: whats wrong with my reg expression ? Message-ID: rex2=re.compile('^"(?P[^]*)"$',re.M) File "/usr/lib/python2.5/re.py", line 180, in compile return _compile(pattern, flags) File "/usr/lib/python2.5/re.py", line 233, in _compile raise error, v # invalid expression sre_constants.error: unexpected end of regular expression ? From msj at infoserv.dk Fri Jan 5 12:44:03 2007 From: msj at infoserv.dk (msj at infoserv.dk) Date: 5 Jan 2007 09:44:03 -0800 Subject: MySQLdb windows binaries for Python 2.5?? Yes, but from a World of Warcraft guild. In-Reply-To: References: <1162408100.985370.148650@m7g2000cwm.googlegroups.com> <1163238145.257490.144410@b28g2000cwb.googlegroups.com> <1166144355.616642.127080@n67g2000cwd.googlegroups.com> Message-ID: <1168019043.523288.50770@38g2000cwa.googlegroups.com> Anyone have a binary they want to share? /Martin From sndive at gmail.com Tue Jan 23 21:22:58 2007 From: sndive at gmail.com (sndive at gmail.com) Date: 23 Jan 2007 18:22:58 -0800 Subject: What's the reverse of Py_BuildValue("u#" ? Message-ID: <1169605378.718701.229310@d71g2000cwa.googlegroups.com> How could I get the pointer to and the length of ucs2 array out of a PyObject representing a string? Something that works whether PyObject string is in unicode or not. Also could I replace a sequence if(PyBool_Check(obj)) { ... } if(PyString_Check(obj)) { // would this be true for any string type? ... } if(PyFloat_Check(obj)) { ... with a switch? Thank you! From arkanes at gmail.com Wed Jan 24 10:36:40 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 09:36:40 -0600 Subject: Rendering text question (context is MSWin UI Automation) In-Reply-To: References: <45b6231b$1_2@news.bluewin.ch> <4866bea60701230724y3a51bc31p9970075f99b70d05@mail.gmail.com> Message-ID: <4866bea60701240736v837d246w187ecb1ccb90eefd@mail.gmail.com> On 1/24/07, Boris Borcic wrote: > Chris Mellon wrote: > > > > Using either win32 or wxPython you will be able to produce bitmaps > > directly, without needing to create a visible window. > > > > > > Some quick & dirty wxPython code > > > > def getTextBitmap(text, font, fgcolor, bgcolor): > > dc = wx.MemoryDC() > > dc.SetFont(font) > > width, height= dc.GetTextExtent(text) > > bmp = wx.EmptyBitmap(width, height) > > dc.SelectObject(bmp) > > dc.SetBackground(wx.Brush(bgcolor)) > > dc.Clear() > > dc.SetTextBackground(bgcolor) > > dc.SetTextForeground(fgcolor) > > dc.DrawText(text, 0, 0) > > dc.SelectObject(wx.NullBitmap) > > return bmp > > > > > > Raw win32 code will look similar but will be much more verbose. > > Thx again for this base. > > Quickly testing this, it appears that the result is rendered half a pixel off in > the x-direction. Does this make sense ? Is it possible to position text with > subpixel accuracy ? > The GDI text api, which is what wx is wrapping here, only provides pixel accuracy. You are probably seeing a kerning effect from your chosen font and perhaps the effects of ClearType. From http Wed Jan 10 08:30:47 2007 From: http (Paul Rubin) Date: 10 Jan 2007 05:30:47 -0800 Subject: Is there a way to protect a piece of critical code? References: Message-ID: <7xac0rovp4.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > I would like to do the following as one atomic operation: > > 1) Append an item to a list > 2) Set a Boolean indicator You could do it with locks as others have suggested, but maybe you really want the Queue module. From mail at microcorp.co.za Thu Jan 18 00:27:43 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 18 Jan 2007 07:27:43 +0200 Subject: Class data members in C References: Message-ID: <000001c73ac8$a25fb540$03000080@hendrik> "Nick Maclaren" wrote: > > In article , > "Hendrik van Rooyen" writes: > |> > > |> > Hmm. The extensions documentation describes how to add instance > |> > members to a class (PyMemberDef), but I want to add a class member. > |> > Yes, this is constant for all instances of the class. > |> > |> When? - at time of defining base class, between class definition and > |> first instance, at time of creating instance, or after instance creation? > |> > |> After instance creation is not easy, I think you would have to add > |> to each instance... > > Oh, one of the first two - I am not bonkers! Changing a class after > instance creation is guaranteed to cause confusion, if nothing else. > *grin* - its also just about impossible to do, if you try to imagine what you would have to do to all instances when you effectively change the __init__ method. And some people expect it to happen automagically... Sorry I can't be of more help. All of the docs I have read essentially talk about changing instances. From a practical point of view I would say: "Just redefine it". But that is not very helpful. Specially if you are mucking about in C, as your title suggests... It has never struck me before that the root word for "madness" and the slang for "copulation" is the same. I wonder if there is some sort of a message here? - Hendrik From exarkun at divmod.com Wed Jan 17 11:44:04 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 17 Jan 2007 11:44:04 -0500 Subject: Globbing files by their creation date In-Reply-To: <1169051467.179899.178570@s34g2000cwa.googlegroups.com> Message-ID: <20070117164404.11447.422170313.divmod.quotient.19758@ohm> On 17 Jan 2007 08:31:07 -0800, tkpmep at hotmail.com wrote: > >Thanks a mill - os.path.getctime(f) is what I needed. Unfortunately, my >attempts to turn the integer it returns into a date have failed. > >>>> os.path.getctime(fn) #fn was created today, 1/17/2007 >1168955503 > >I tried to convert this to a date object by typing >>>>datetime.date.fromordinal(1168955503) > >Traceback (most recent call last): > File "", line 1, in -toplevel- > datetime.date.fromordinal(1168955503) >ValueError: year is out of range > >How can I do the conversion? I'm trying to identify all files that were >created after YYYY/MM/DD. > >For a quick sanity check, I ran >>>> datetime.date.today().toordinal() >732693 > >which is orders of magnitude smaller than the number returned by >os.path.getctime(fn). > >Thanks in advance for your help Ordinals are unrelated to the values given back by getctime. Try something like this instead: exarkun at charm:~$ python Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> import datetime >>> datetime.date.fromtimestamp(os.path.getctime('.')) datetime.date(2007, 1, 17) >>> exarkun at charm:~$ ls -ld . drwxr-xr-x 93 exarkun exarkun 8192 2007-01-17 10:34 . exarkun at charm:~$ Jean-Paul From ptmcg at austin.rr.com Tue Jan 23 14:54:16 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jan 2007 11:54:16 -0800 Subject: Simple Matrix class Message-ID: <1169582056.315098.267950@k78g2000cwa.googlegroups.com> I've posted a simple Matrix class on my website as a small-footprint package for doing basic calculations on matrices up to about 10x10 in size (no theoretical limit, but performance on inverse is exponential). Includes: - trace - transpose - conjugate - determinant - inverse - eigenvectors/values (for symmetric matrices) - addition and multiplication (with constant or other matrix) Matrices are easily built from formatted strings, as in: m = Matrix( """1 2 3 4 5 11 20 3 2 7 11 1 0 5 3 1""") Pretty much a no-strings-attached license, just don't hassle me about little things like warranty, support, merchantability, accuracy, etc. See it at http://www.geocities.com/ptmcg/python/index.html#matrix_py -- Paul From bdesth.quelquechose at free.quelquepart.fr Tue Jan 9 18:14:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 Jan 2007 00:14:48 +0100 Subject: Python - C# interoperability In-Reply-To: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> References: <1168378200.620839.189750@i39g2000hsf.googlegroups.com> Message-ID: <45a41b98$0$321$426a74cc@news.free.fr> mc a ?crit : > Is there an easy way to compile a Python class (or set of classes) into > a .DLL that a C# program can call? Or otherwise to use an existing > library of Python classes from a C# program as seamlessly as possible? > I can't tell if that'll do, but have you looked at IronPython ? From jweida at gmail.com Sat Jan 27 17:43:57 2007 From: jweida at gmail.com (Jerry) Date: 27 Jan 2007 14:43:57 -0800 Subject: Hi, I'm new to python In-Reply-To: <1169905027.776723.194140@a75g2000cwd.googlegroups.com> References: <1169905027.776723.194140@a75g2000cwd.googlegroups.com> Message-ID: <1169937837.925954.109310@a75g2000cwd.googlegroups.com> I would definitely suggest checking out the documentation at http:// www.python.org/doc/. Also, you can check out the free book Dive into Python at http://www.diveintopython.org. It provides a great overview starting at the very beginning. I found it great and hope to buy it soon to support the author. Python is considered a general-purpose language (so is Perl by the way.) It can handle anything from processing text, to running as an application server (check out http://www.zope.com.) You can also use pieces of it for web programming. In fact, if you've heard of Ruby on Rails, then you can see a similar Python project called TurboGears at http://www.turbogears.com. If you only need a web framework, then you can also check out Django (http://www.djangoproject.com) and many other projects designed for getting a web-based application up and running quickly. Not to leave you with the impression that it's really only suited for web stuff, there is also Pygame (http://www.pygame.com), a library and bindings to SDL so you can write your own games. I am currently learning Pygame with OpenGL and writing a simple clone of SpaceWars. I've also written a Jabber bot in Python for use where I used to work. You can use Python for systems automation as well. I wrote a small applet that opened SSH connections to every server in a list and then sent all the text you typed into a single box to all servers at the same time. I'm currently learning how to use Python with osascript to control applications in Mac OS X and have dabbled a little with the win32com stuff to have Python control some aspects of Windows. As you can see, it's an extremely versatile language and is really only limited by your imagination. There are some things that it doesn't do so well, but for the most part, those things have solutions. For example, Python is typically slower than other languages when you must iterate over something many times. For example, in game programming, to iterate over the entire list of objects in the world to update their positions or draw them. Many times things like this can be moved into C libraries to make then run faster. I myself haven't had many problems with this at all. In fact, none of my iteration code is in C for my game. Well, that's enough rambling for me. I've turned this post into a commercial for Python. I hope that I've left you with enough ideas to get started in the language. -- Jerry H From davidh at ilm.com Tue Jan 16 18:05:19 2007 From: davidh at ilm.com (David Hirschfield) Date: Tue, 16 Jan 2007 15:05:19 -0800 Subject: Help: asyncore/asynchat and terminator string Message-ID: <45AD5A2F.7060701@ilm.com> I'm implementing a relatively simple inter-application communication system that uses asyncore/asynchat to send messages back and forth. The messages are prefixed by a length value and terminator string, to signal that a message is incoming, and an integer value specifying the size of the message, followed by the message data. My question is: how can I produce a short terminator string that won't show up (or has an extremely small chance of showing up) in the binary data that I send as messages? Frankly, I'm not so sure this is even an important question, but is nagging me. If my communication is a kind of state machine: sender: sends message length value, followed by terminator string, followed by message data receiver: waiting for terminator string via set_terminator() continually save what comes in via collect_incoming_data() receiver: when sender's message arrives, found_terminator() is called pull message length from previously received data set terminator to be the length of the message via set_terminator() receiver: collect_incoming_data() collects the message data receiver: found_terminator() called when full message length is read, receiver goes back to waiting for message terminator string I hope I explained that clearly enough. The only time I can conceive that the system will get confused by finding a terminator string in the binary data of the message is if something goes haywire and I end up looking for a terminator string when the other side is sending the message data. What gotchas do I need to look out for here? I'm not a networking person, so I'm relying on the underlying libraries to be stable and just let me handle the high-level stuff here. This isn't going to be used in a malicious environment, the only thing I have to contend with is network hiccups...nobody is actively going to try and break this system. Any advice/help would be appreciated, -Dave -- Presenting: mediocre nebula. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jan 12 12:01:31 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 12 Jan 2007 18:01:31 +0100 Subject: What about this? References: <1168525050.536736.74590@i39g2000hsf.googlegroups.com> <50n9kcF1g30l4U2@mid.individual.net> <1168612073.635206.84620@s34g2000cwa.googlegroups.com> Message-ID: <50pt7bF1h5hj5U3@mid.individual.net> Dr. Who wrote: > What's more amazing is that anyone would click on the link at all > given the increasing number of website that provide hidden content > that tries to deliver spyware or viruses just by getting visitors. How could active input reach *me* if I just fed the W3C validator with the URL? Regards, Bj?rn -- BOFH excuse #184: loop found in loop in redundant loopback From pwatson at redlinepy.com Thu Jan 4 13:25:03 2007 From: pwatson at redlinepy.com (Paul Watson) Date: Thu, 04 Jan 2007 12:25:03 -0600 Subject: what is this? In-Reply-To: References: Message-ID: <504v40F1ebv3sU1@mid.individual.net> Eric Price wrote: > Hello; > I'm studying some code examples from the python cookbook site. I came > across this: > > def colsplit(l, cols): > rows = len(l) / cols > if len(l) % cols: > rows += 1 > m = [] > for i in range(rows): > m.append(l[i::rows]) > return m > > What I'd like to know is what is the double colon? What does it do? > m.append(l[i::rows]) > > Thanks, > Eric http://docs.python.org/tut/tut.html http://docs.python.org/tut/node5.html#SECTION005140000000000000000 http://docs.python.org/ref/slicings.html Probably most helpful to you is: http://developer.mozilla.org/es4/proposals/slice_syntax.html From Bob.Sidebotham at gmail.com Fri Jan 12 09:17:01 2007 From: Bob.Sidebotham at gmail.com (Bob.Sidebotham at gmail.com) Date: 12 Jan 2007 06:17:01 -0800 Subject: context managers and co-routines Message-ID: <1168611420.448058.163860@11g2000cwr.googlegroups.com> I'm happily using context managers and co-routines, and would like to use both at the same time, e.g. with foo(): ... x = yield y ... In this code multiple copies of this code can be executing at the "same" time, interleaved by the yield statement. This doesn't work well, since the context manager is dealing with global state (specifically, re-routing stdout). The problem is that all of my state (local variables, etc.) is nicely saved over the yield, but the context is not. So I end up having to write the code like this: with foo(): ... x = yield y with foo(): ... which is not so pretty. What I'd like is some way to transparently save and restore context over a yield, but I don't see an easy way to do this. Any suggestions? Thanks, Bob Sidebotham From simon at brunningonline.net Fri Jan 12 14:30:17 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 12 Jan 2007 19:30:17 +0000 Subject: I need to consume a .NET web service in a Python client In-Reply-To: <1168629081.271619.316370@s34g2000cwa.googlegroups.com> References: <1168626439.257622.134700@38g2000cwa.googlegroups.com> <1168629081.271619.316370@s34g2000cwa.googlegroups.com> Message-ID: <8c7f10c60701121130r270c0948sc5e9c3780cc45626@mail.gmail.com> On 12 Jan 2007 11:11:21 -0800, Ravi Teja wrote: > Start Here > http://www.diveintopython.org/soap_web_services/index.html > Example Client > http://www.diveintopython.org/soap_web_services/first_steps.html Sadly, SOAPpy doesn't seem to be maintained any more. I'd take a look at ZSI, instead. -- Cheers, Simon B simon at brunningonline.net From steve at REMOVE.THIS.cybersource.com.au Mon Jan 1 00:37:53 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 01 Jan 2007 16:37:53 +1100 Subject: OO question References: <1167623232.105052.203550@42g2000cwt.googlegroups.com> Message-ID: On Sun, 31 Dec 2006 19:47:12 -0800, fejkadress wrote: > I want to make an addressbook and I'm new to OO programming, so I > wonder if this sounds reasonable. > > I think of making a class Address which contains all data about one > person, that class can have UserDict as baseclass so I can access data > like object['name'], etc.. If you are using Python 2.2 or greater, you can inherit from dict: >>> class Address(dict): ... pass ... >>> fred = Address({"address": "123 smith street"}) >>> fred['address'] '123 smith street' But ask yourself, what benefit do you gain by subclassing dict? Why not just use a dict? If this is a learning exercise, then sure, go for it, subclass away! But if this is meant to be real code, then consider what benefits and costs using OO will give you, compared to a function-based approach. (Please don't assume that this is a thinly veiled hint that OO is the wrong approach. It isn't.) > Then maybe I can have a class AddressBook which has a list that > contains all those Address objects. > Does that sound reasonable? Again, why create an AddressBook class? Why not just have a list of Addresses? > And then the real reason that I posted here is: > If I want to save all addresses to disk, I can have a method, say, > save() of AddressBook. But then what? What is a good object oriented > approach? Should each Address object take care of saving itself to the > file, with a method like writetofile(filename), or should the class > AddressBook take care of the saving and ask each object for its data? Here's one approach, assuming that AddressBook is merely a list of Addresses and that the Address class knows how to write to an open file object: def save(list_of_addresses, filename): f = file(filename, "w") for address in list_of_addresses: address.save(f) f.close() Here's a more pure OO approach to do the same thing: class AddressBook(object): def __init__(self, list_of_addresses): self.addresses = list_of_addresses def save(self, filename): f = file(filename, "w") for address in self.addresses: address.save(f) f.close() Here's a third approach: class AddressBook(object): def __init__(self, list_of_addresses): self.addresses = list_of_addresses self.currentfile = None def save_one_address(self, data): data = do_something_with(data) self.currentfile.write(data) def save(self, filename): self.currentfile = file(filename, "w") for address in self.addresses: self.save_one_address(address.export()) self.currentfile.close() self.currentfile = None -- Steven. From oliphant.travis at ieee.org Fri Jan 12 00:59:43 2007 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Thu, 11 Jan 2007 22:59:43 -0700 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168458486.538863.316130@k58g2000hse.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> Message-ID: oyekomova wrote: > Thanks for your help. I compared the following code in NumPy with the > csvread in Matlab for a very large csv file. Matlab read the file in > 577 seconds. On the other hand, this code below kept running for over 2 > hours. Can this program be made more efficient? FYI - The csv file was > a simple 6 column file with a header row and more than a million > records. > > There is some facility to read simply-formatted files directly into NumPy. You might try something like this. numpy.fromfile('somename.csv', sep=',') and then reshape the array. -Travis From robert.kern at gmail.com Tue Jan 23 22:54:42 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Jan 2007 21:54:42 -0600 Subject: easy_install pylons failure - www.myghty.org unavailable In-Reply-To: <17846.54389.27457.383902@montanaro.dyndns.org> References: <17846.54389.27457.383902@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > Is it not able to get past this point because there is only one source for > Myghty or does it always need to go to a package's home page? I was able to > work around this by manually downloading the Myghty-1.1.tar.gz file and > installing it. Asking on Distutils-SIG list will be more likely to get Phillip Eby's attention. It surprises me that setuptools didn't pick up the tarball on the CheeseShop. http://mail.python.org/mailman/listinfo/distutils-sig -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From researchbase at gmail.com Sat Jan 20 01:09:07 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sat, 20 Jan 2007 11:39:07 +0530 Subject: confused on python rpc with apache, is it possible? In-Reply-To: <51ce8uF1k0tl5U1@mid.uni-berlin.de> References: <51ce8uF1k0tl5U1@mid.uni-berlin.de> Message-ID: On 19/01/07, Diez B. Roggisch wrote: > > I'm unclear why you want the apache in there in the first place. Why don't > you just create an e.g. twisted-based XMLRPC-server, and simply let that > run? What is the apache intended for? twisted-based? what is that? what is that. I am very new to xml-rpc so my questions may sound very basic. any ways apache is doing nothing in there but I thought that if some thing needs to be done in php in the future then apache better be there but as I said that is no need if pythone can do it on a stand alone basis. From manstey at csu.edu.au Tue Jan 30 01:02:45 2007 From: manstey at csu.edu.au (manstey) Date: 29 Jan 2007 22:02:45 -0800 Subject: parent-child object design question Message-ID: <1170136965.015119.225920@q2g2000cwa.googlegroups.com> Hi, I am having trouble designing my classes. I have two classes. The first one wraps around an old-style class called oref Class CacheClass(object): def __init__(self, obj): self.__data = obj def __getattr__(self, attr): return getattr(self.__data, attr) The second class is much the same, also wrapping, but has some attributes. class CacheProperty(object): def __init__(self, obj, dicProperties={}): self.__data = obj lisProperties=[] for key, val in dicProperties.iteritems(): setattr(self, key, val) lisProperties.append(key) self.Properties = lisProperties def __getattr__(self, attr): return getattr(self.__data, attr) Here is my code: >>> MyClass = CacheClass(oref) >>> MyProperty = CacheProperty(oref2,{'Name':'Surname', 'Value':'Peter'}) >>> setattr(MyClass,MyProperty.Name,MyProperty) Now, the problem is that I want a method MyClass.MyProperty.Save() to save the value of MyClass.MyProperty to the database backend on disk, but the code for this is part of the wrapped oref code, and thus is invoked only by MyClass.set(MyProperty.Name,MyProperty.Value). How can I access this method inside the MyProperty class? I hope this is clear! regard,s matthew From ljz at asfast.com Sat Jan 6 15:44:26 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Sat, 06 Jan 2007 15:44:26 -0500 Subject: Recommended way to force a thread context switch? References: <1168103258.602286.146100@42g2000cwt.googlegroups.com> <1168104008.910681.46800@38g2000cwa.googlegroups.com> Message-ID: <874pr3navp.fsf@asfast.com> I have a python (2.5) program with number of worker threads, and I want to make sure that each of these does a context switch at appropriate times, to avoid starvation. I know that I can do a time.sleep(0.001) to force such a switch, but I'm wondering if this is the recommended method. Thanks in advance. -- Lloyd Zusman ljz at asfast.com God bless you. From wuwei23 at gmail.com Wed Jan 24 19:49:02 2007 From: wuwei23 at gmail.com (alex23) Date: 24 Jan 2007 16:49:02 -0800 Subject: Question about docutils In-Reply-To: <45b7fca1$0$49206$14726298@news.sunsite.dk> References: <45b7fca1$0$49206$14726298@news.sunsite.dk> Message-ID: <1169686142.135007.127760@m58g2000cwm.googlegroups.com> On Jan 25, 10:40 am, Damjan wrote: > I'm using docutils 0.4. > Is it possible to define special custom 'tags' (or something) that will > invoke my own function? The function would then return the real content in > the ReST document. I -think- this is what you're looking for: http://docutils.sourceforge.net/docs/howto/rst-roles.html Hope it helps. -alex23 From ziga.seilnacht at gmail.com Sun Jan 14 19:49:00 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 14 Jan 2007 16:49:00 -0800 Subject: Conflicting needs for __init__ method References: <1168817555.850650.261660@s34g2000cwa.googlegroups.com> Message-ID: <1168822140.799071.153390@s34g2000cwa.googlegroups.com> Mark wrote: [a lot of valid, but long concerns about types that return an object of their own type from some of their methods] I think that the best solution is to use an alternative constructor in your arithmetic methods. That way users don't have to learn about two different factories for the same type of objects. It also helps with subclassing, because users have to override only a single method if they want the results of arithmetic operations to be of their own type. For example, if your current implementation looks something like this: class Rational(object): # a long __init__ or __new__ method def __add__(self, other): # compute new numerator and denominator return Rational(numerator, denominator) # other simmilar arithmetic methods then you could use something like this instead: class Rational(object): # a long __init__ or __new__ method def __add__(self, other): # compute new numerator and denominator return self.result(numerator, denominator) # other simmilar arithmetic methods @staticmethod def result(numerator, denominator): """ we don't use a classmethod, because users should explicitly override this method if they want to change the return type of arithmetic operations. """ result = object.__new__(Rational) result.numerator = numerator result.denominator = denominator return result Hope this helps, Ziga From tsuraan at gmail.com Mon Jan 8 14:16:07 2007 From: tsuraan at gmail.com (tsuraan) Date: Mon, 8 Jan 2007 13:16:07 -0600 Subject: Suitability for long-running text processing? In-Reply-To: <4866bea60701080927r4dedd392o38d45660864a8717@mail.gmail.com> References: <84fb38e30701080741n1579e5f5h18f4f068c343a11f@mail.gmail.com> <84fb38e30701080813k1be616fch6d01922fb7a92fc5@mail.gmail.com> <4866bea60701080849h16d1dacew7a0abe950726c006@mail.gmail.com> <84fb38e30701080919r41d52fb6nc5ee31f12e901ef3@mail.gmail.com> <4866bea60701080927r4dedd392o38d45660864a8717@mail.gmail.com> Message-ID: <84fb38e30701081116n1dd8c6e3g2df74d1601902a9d@mail.gmail.com> > I remember something about it coming up in some of the discussions of > free lists and better behavior in this regard in 2.5, but I don't > remember the details. Under Python 2.5, my original code posting no longer exhibits the bug - upon calling del(a), python's size shrinks back to ~4 MB, which is its starting size. I guess I'll see how painful it is to migrate a gentoo system to 2.5... Thanks for the hint :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr._bogus_.com Fri Jan 5 08:47:33 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 5 Jan 2007 07:47:33 -0600 Subject: Draw rectangle on a Window DC References: <459cd1e4.0232d77c.0893.ffff821d@mx.google.com> Message-ID: <459e56f5$0$27069$4c368faf@roadrunner.com> "Gabriel Genellina" wrote in message news:mailman.2300.1167963723.32031.python-list at python.org... > At Thursday 4/1/2007 07:07, Raymond wrote: > >>I want to Draw rectangle on Dc when gived a position. Can you teach me? >>Let me view your code? > > This is more a Windows question. See > http://msdn.microsoft.com/library/en-us/gdi/rectangl_4b03.asp > > py>from win32gui import GetDC > py>hdc=GetDC(0) > py>from win32gui import Rectangle > py>Rectangle(hdc, 100,100, 300,300) > py>ReleaseDC(hdc,0) > 0 > py> > > You should see a white square on your screen. > Nice example. First line should be: from win32gui import GetDC, ReleaseDC -- Paul From michele.simionato at gmail.com Mon Jan 29 03:53:00 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 29 Jan 2007 00:53:00 -0800 Subject: Web File System In-Reply-To: <1170059509.601069.153290@q2g2000cwa.googlegroups.com> References: <1170059509.601069.153290@q2g2000cwa.googlegroups.com> Message-ID: <1170060780.314106.316160@v45g2000cwv.googlegroups.com> On Jan 29, 9:31 am, anthony.cutr... at gmail.com wrote: > Hi group, > > I have a development with a file system in Python, accessible from a > graphic web application. > > I mustn't use an NTFS or EXT3 system, because those are not adapted > for my use. Indeed, I would like my system to be able to recover > files, and get precedent versions. I also want it to index words > contained in files, to search with these. > > Files and folders have to be in an SQL database, mounted in ext3-like > system. File would be identified by a single ID, and links with names > should be connected on these IDs. > > Somebody have already worked (in Python) about this kind of things ? > is there a publicly available framework or toolkit ? > > thanks I do not understand extractly what you are asking, but do you know about WebDAV? I would give a look to Content Management Systems such as Zope for this kind of things. Michele Simionato From macsareback at mac.com Tue Jan 30 10:27:59 2007 From: macsareback at mac.com (Daniel kavic) Date: Tue, 30 Jan 2007 07:27:59 -0800 Subject: Please take me off the list Message-ID: Sorry to waste email space , but I wish to be off this list because I have tried python and it is too difficult for me. -Dan From sturlamolden at yahoo.no Mon Jan 8 18:25:39 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 8 Jan 2007 15:25:39 -0800 Subject: Why less emphasis on private data? In-Reply-To: References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <1168188427.144219.206490@s80g2000cwa.googlegroups.com> <%Isoh.22447$X97.12337@newsfe18.lga> Message-ID: <1168298739.053287.197780@51g2000cwl.googlegroups.com> Jussi Salmela wrote: > To surlamolden: I don't know how you define private, but if one defines > in C an external static variable i.e. a variable outside any functions, > on the file level, the scope of the variable is that file only. Sure, in C you can hide instances inside an object image by declaring them static. But the real virtue of static declarations is to assist the compiler. My definition of 'private' for this thread is the private attribute provided by C++, Java and C#. When I program C I use another idiom, /* THIS IS MINE, KEEP YOUR PAWS OFF */ and it works just as well. The same idiom works for Python as well. > To hg: One does not need in C the static keyword to make a variable > defined inside a function i.e. a so called 'automatic variable' private > to that test. Automatic variables are private to their function by > definition. The static keyword makes the variable permanent i.e. it > keeps its value between calls but it is of course private also. > > To Neil Cerutti: If a programmer in C has got a pointer to some piece of > memory, that piece is at the mercy of the programmer. There's no data > hiding at all in this case. > > To whom it may concern: please stop comparing C and Python with regard > to privacy and safety. They are two different worlds altogether. Believe > me: I've been in this world for 2.5 years now after spending 19 years in > the C world. > > Cheers, > Jussi From jtravs at gmail.com Tue Jan 9 13:46:15 2007 From: jtravs at gmail.com (jtravs at gmail.com) Date: 9 Jan 2007 10:46:15 -0800 Subject: distutils and ctypes Message-ID: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> Hi all, I suspect that I'm doing something stupid, I would like some other opinions though. I'm getting started with ctypes and am trying to use distutils to help build my module. At the moment I simply want distutils to build a shared c library (not a python extension!). Under linux, the following works, under windows xp id doesn't (which I guess is obvious, but the linux success lead me on). I have two files at the moment... /* begin test.c */ int test(int i) { return i*i; } /* end test.c */ #begin setup.py from distutils.core import setup, Extension setup(name="test", version="0.0", ext_modules = [Extension("test", ["test.c"])]) # end setup.py If I run: python setup.py build under linux, I get a nice shared c library under my build dir, which can be imported by ctypes. If I run it under windows I get the following: running build running build_ext building 'test' extension C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\Python25\libs /LIBPATH:C:\Python25\PCBuild /EXPORT:inittest build\temp.win32-2.5\Release\test.obj /OUT:build\lib.win32-2.5\test.pyd /IMPLIB:build\temp.win32-2.5\Release\test.lib LINK : error LNK2001: unresolved external symbol inittest build\temp.win32-2.5\Release\test.lib : fatal error LNK1120: 1 unresolved externals LINK : fatal error LNK1141: failure during build of exports file I can see the problem: python is trying to build an extension module and is telling the linker to export "inittest", which doesn't exist. This didn't happen under linux as you don't need to export interfaces in shared c libraries on linux. So finally, my question is, is there a way to get distutils to simply build a shared library on windows so that I can use ctypes with them??? Thanks for your patience with this post, and thanks for any replies. Best regards, John Travers From skip at pobox.com Wed Jan 24 12:33:15 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 Jan 2007 11:33:15 -0600 Subject: The reliability of python threads In-Reply-To: <45B7904B.90303@mvista.com> References: <45B7904B.90303@mvista.com> Message-ID: <17847.39003.410596.481072@montanaro.dyndns.org> Carl> Does anyone have any conclusive evidence that python threads/locks Carl> are safe or unsafe? In my experience Python threads are generally safer than the programmers that use them. ;-) Skip From cjw at sympatico.ca Sun Jan 14 09:39:30 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 14 Jan 2007 09:39:30 -0500 Subject: Comparing a matrix (list[][]) ? In-Reply-To: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> References: <1168730648.038901.187460@v45g2000cwv.googlegroups.com> Message-ID: jairodsl wrote: > Hi, > > How can I find the minus element greater than zero in a matrix, my > matrix is > > matrix= > [9,8,12,15], > [0,11,15,18], > [0,0,10,13], > [0,0,0,5] > > I dont want to use "min" function because each element in the matrix is > associated to (X,Y) position. > > Thanks a lot. > > jDSL > You might consider numarray or numpy for this sort of thing. Colin W. From steve at REMOVE.THIS.cybersource.com.au Sat Jan 27 18:51:48 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 28 Jan 2007 10:51:48 +1100 Subject: assertions to validate function parameters References: <1169909883.944892.74390@k78g2000cwa.googlegroups.com> Message-ID: On Sat, 27 Jan 2007 06:58:04 -0800, Carl Banks wrote: >> I find that when I detect invalid parameters overtly, I spend less time >> debugging. > > If it helps go ahead an use them. The world won't end if you use an > assertion in a less than ideal situation. And, after all, if someone > doesn't like it they can shut them off. Is there any way to have finer control of assertions than just passing -O to the Python interpreter? Suppose I want to switch them off for certain modules but not others, am I out of luck? -- Steven. From rschroev_nospam_ml at fastmail.fm Thu Jan 18 12:07:19 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 18 Jan 2007 17:07:19 GMT Subject: Would a Dutch speaker please check this wiki page please? In-Reply-To: <7x8xg0s5h1.fsf@ruckus.brouhaha.com> References: <45af8edf$0$336$e4fe514c@news.xs4all.nl> <7x8xg0s5h1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schreef: > "Martin P. Hellwig" writes: >> Indeed it's not Afrikaans but just incorrect use of Dutch and not >> related to python. > > It was apparently posted by someone with a .be address, so I'll guess > it was written a Belgian French speaker who knows some Dutch. The > "me" vs "mijn" error sounds like something a French speaker might have > done. To me (as a Belgian Dutch speaker) it sounds more like someone writing phonetically (probably because of a low education or low interest in writing correctly) and being from the Netherlands (since the pronunciation of 'mijn' sounds more like 'me' there then in Flanders). It's not unlike the use of "I should of" instead of "I should've" or "I should have" in English, though much less common. At least I think and hope it's much less common, but actually I don't read all that much forums, newsgroups etc. in Dutch. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From ggg at zzz.it Wed Jan 31 13:44:39 2007 From: ggg at zzz.it (deelan) Date: Wed, 31 Jan 2007 19:44:39 +0100 Subject: subway In-Reply-To: References: <5f56302b0701310802y7e45c98fmaaebe090e34d410@mail.gmail.com> <17856.50898.477998.112022@montanaro.dyndns.org> Message-ID: Daniel Nogradi wrote: (...) > > the egg file can not be downloaded completely, the connection is > closed at byte 138903 all the time and the file is bigger than that. > If anyone managed to grab the file please let me know so far I tried > wget and firefox. I've checked on my hd and found a recent (Jun 2006) checkout on the original SVN repos. There's everything in it: Subway code, web site and examples: HTH -- d. From emin.shopper at gmail.com Wed Jan 17 14:02:51 2007 From: emin.shopper at gmail.com (Emin) Date: 17 Jan 2007 11:02:51 -0800 Subject: question about module resolution In-Reply-To: References: <1169050133.438101.90030@a75g2000cwd.googlegroups.com> Message-ID: <1169060571.641437.297170@51g2000cwl.googlegroups.com> I put the lines you suggested in baz.py, but got an error: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import baz Traceback (most recent call last): File "", line 1, in File "baz.py", line 3, in from .. import config ValueError: Attempted relative import in non-package On Jan 17, 11:20 am, Peter Otten <__pete... at web.de> wrote: > Emin wrote: > > I often find myself wanting to have a child module get some parameters > > defined in a parent module. For example, imagine I have the following > > directory structure and want something in baz.py to look at a value in > > config.py. I end up putting in things like import sys; > > sys.path.append('../..'). Is there a better way? > > > foo/ > > __init__.py > > config.py > > bar/ > > __init__.py > > baz.pyfrom __future__ import absolute_import > from .. import config > > Peter From carsten at uniqsys.com Tue Jan 2 11:32:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 02 Jan 2007 11:32:10 -0500 Subject: How do I add users using Python scripts on a Linux machine In-Reply-To: References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: <1167755530.3387.16.camel@dot.uniqsys.com> On Tue, 2007-01-02 at 17:17 +0100, Sebastian 'lunar' Wiesner wrote: > Ravi Teja typed > > > > > Ivan Voras wrote: > >> Ramdas wrote: > >> > Well, > >> > > >> > I need to add users from a web interface for a web server, which > >> > runs only Python. I need to add users, set quotas and in future > >> > even look at managing ip tables to limit bandwidth. > >> > > >> > I know os.system(), but this has to be done through a form entry > >> > through a web interface. > >> > > >> > Anyways thanks, do advise if there more pythonic solutions > >> > >> What you're looking for is actually a pretty complex thing. You > >> *could* in theory manage /etc/passwd (and its "shadow" file) - you > >> can find crypto primitives like MD5 and DES on the 'net, but note > >> that you must run your script under the 'root' account in order to > >> write (and even read!) the passwd database. The same goes for using > >> os.system and the built-in OS utility. Be aware of security > >> implications if you're running your web server under the root > >> account. > > > > How about invoking scripts with SUID root set? > > Linux seems to ignore SUID bit on scripts: I don't think that that has anything to do with Linux or not. The script is not the actual executable, hence its suid bit is irrelevant. You'd have to set the suid bit on the python executable, but that would affect all python scripts, which is probably bad. -Carsten From inq1ltd at verizon.net Mon Jan 15 18:05:19 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Mon, 15 Jan 2007 18:05:19 -0500 Subject: download win32file In-Reply-To: <_mTqh.49191$kn7.39312@newsfe23.lga> References: <_mTqh.49191$kn7.39312@newsfe23.lga> Message-ID: <200701151805.19483.inq1ltd@verizon.net> On Monday 15 January 2007 10:37, hg wrote: > jim-on-linux wrote: > > Where can I download win32file / win32ui? > > > > The links below are broken. Mark Hammond > > should be made aware of this. > > > > > > URL below has two links that send you no > > place > > http://mail.python.org/pipermail/python-list/ > >2002-October/167638.html > > > > > > Links: > > http://starship.python.net/crew/mhammond/win3 > >2/Downloads.html > > > > http://starship.python.net/crew/mhammond/down > >loads/win32all-148.exe > > > > > > Produce; > > > > The requested URL was not found on this > > server. The link on the referring page seems > > to be wrong or outdated. Please inform the > > author of that page about the error. > > > > jim-on-linux > > Do you mean PyWin32 ? ?? Do I have to download pywin32 to get win32ui, or win32file, or win32api > > http://sourceforge.net/projects/pywin32/ From rubbishemail at web.de Thu Jan 18 06:16:56 2007 From: rubbishemail at web.de (rubbishemail at web.de) Date: 18 Jan 2007 03:16:56 -0800 Subject: arguments of a function/metaclass In-Reply-To: References: <1168960230.524841.280900@m58g2000cwm.googlegroups.com> Message-ID: <1169119016.289813.92050@38g2000cwa.googlegroups.com> thank you! From pavlovevidence at gmail.com Sat Jan 27 22:29:06 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 27 Jan 2007 19:29:06 -0800 Subject: assertions to validate function parameters In-Reply-To: References: <1169909883.944892.74390@k78g2000cwa.googlegroups.com> Message-ID: <1169954946.479629.312100@k78g2000cwa.googlegroups.com> On Jan 27, 6:51 pm, Steven D'Aprano wrote: > On Sat, 27 Jan 2007 06:58:04 -0800, Carl Banks wrote: > >> I find that when I detect invalid parameters overtly, I spend less time > >> debugging. > > > If it helps go ahead an use them. The world won't end if you use an > > assertion in a less than ideal situation. And, after all, if someone > > doesn't like it they can shut them off. > > Is there any way to have finer control of assertions than just passing -O > to the Python interpreter? Suppose I want to switch them off for certain > modules but not others, am I out of luck? Please relax. The suggestion that one could shut them off was tongue in cheek. Carl Banks From aliptah at gmail.com Sat Jan 6 17:26:57 2007 From: aliptah at gmail.com (aliptah at gmail.com) Date: 6 Jan 2007 14:26:57 -0800 Subject: WoC - A web of code Message-ID: <1168122417.024182.5350@i15g2000cwa.googlegroups.com> Web Of Code http://idiki.dyne.org/wiki/WoC WoC stands for Web Of Code. The basic idea is to add hyperlink capacities to source code documents, creating, in this way, a new Web, of code. The Idiki article describes the idea and shows how it can be implemented using existing tools, f.e. ViewVC, cscope and Vim. Another idea explored by the article is: #!/usr/bin/python from :openssl.org/ssl: import RSA* The article is here: http://idiki.dyne.org/wiki/WoC Best regards. From grahn+nntp at snipabacken.dyndns.org Thu Jan 11 06:53:42 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 11 Jan 2007 11:53:42 GMT Subject: Execute binary code References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> <1168355051.339026.211830@v33g2000cwv.googlegroups.com> <1168445561.239053.140340@77g2000hsv.googlegroups.com> Message-ID: On Wed, 10 Jan 2007 10:31:50 -0600, Chris Mellon wrote: > On 10 Jan 2007 08:12:41 -0800, sturlamolden wrote: >> >> Chris Mellon wrote: >> >> > This works fine if the binary data is "pure" asm, but the impresssion >> > the OP gave is that it's a compiled binary, which you can't just "jump >> > into" this way. >> >> You may have to offset the function pointer so the entry point becomes >> correct. >> > > That won't be enough. You basically would have to re-implement the OS > loading process, handling relocations and loading any linked > libraries. Possible, in theory, but very non-trivial. Yeah, that was implicitly my thinking a bit up in the thread. If all you have is an executable file (COFF/ELF/...) as a string, and you have no os.exec(string) or similar, then you're in trouble. At least if it has to work. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From __peter__ at web.de Wed Jan 3 07:14:49 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Jan 2007 13:14:49 +0100 Subject: Using codecs.EncodedFile() with Python 2.5 References: <1167824708.700486.249020@h40g2000cwb.googlegroups.com> Message-ID: David Hughes wrote: > I used this function successfully with Python 2.4 to alter the encoding > of a set of database records from latin-1 to utf-8, but the same > program raises an exception using Python 2.5. This small example shows > the problem: > > import codecs > fo = open('test.dat', 'w') > fo.write('G\xe2teaux') > fo.close() > > fi = open("test.dat",'r') > fx = codecs.EncodedFile(fi, 'utf-8', 'latin-1') > astring = fx.readline() > print astring > ustring = unicode(astring, 'utf-8' ) > print repr(ustring) > print ustring.encode('latin-1') > print ustring.encode('utf-8') > > Python 2.4 gives: > > G??teaux > u'G\xe2teaux' > G?teaux > G??teaux > > which I believe is correct, while 2.5 produces > > Traceback (most recent call last): > File "test_codec.py", line 8, in > astring = fx.readline() > File "C:\Python25\lib\codecs.py", line 709, in readline > data = self.reader.readline() > File "C:\Python25\lib\codecs.py", line 471, in readline > data = self.read(readsize, firstline=True) > File "C:\Python25\lib\codecs.py", line 418, in read > newchars, decodedbytes = self.decode(data, self.errors) > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-3: > invalid data > > Is there a genuine problem here, or have I been misusing this function? This is indeed a bug in Python 2.5. Fixed in subversion. http://svn.python.org/view/python/trunk/Lib/codecs.py?rev=52517&view=log Peter From gagsl-py at yahoo.com.ar Mon Jan 22 16:12:13 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Jan 2007 18:12:13 -0300 Subject: Best way to document Python code... In-Reply-To: References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070122180625.0598d188@yahoo.com.ar> At Monday 22/1/2007 17:48, Boris Ozegovic wrote: >Does Python has API just like in Java, for example >http://java.sun.com/j2se/1.5.0/docs/api/allclasses-noframe.html ctrl-f and >than click on class you are searching for, and finally you get clean list >of all fields and methods. Where can I find similar in Python, for >example, if I would like to see which methods list/dictionary has. Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> help(dict) Help on class dict in module __builtin__: class dict(object) | dict() -> new empty dictionary. | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs. | dict(seq) -> new dictionary initialized as if via: | d = {} | for k, v in seq: | d[k] = v | dict(**kwargs) -> new dictionary initialized with the name=value pairs | in the keyword argument list. For example: dict(one=1, two=2) | | Methods defined here: | | __cmp__(...) | x.__cmp__(y) <==> cmp(x,y) | | __contains__(...) You should skip at first magic __methods__. You can use help() with any object, or language keyword: help("if") py> import math py> help(math) Help on built-in module math: NAME math FILE (built-in) DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. [...] -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From noone at nowhere.com Tue Jan 30 00:11:32 2007 From: noone at nowhere.com (avidfan) Date: Mon, 29 Jan 2007 23:11:32 -0600 Subject: log parser design question References: <1170048047.660118.164850@l53g2000cwa.googlegroups.com> Message-ID: On 28 Jan 2007 21:20:47 -0800, "Paul McGuire" wrote: >On Jan 27, 10:43 pm, avidfan wrote: >> I need to parse a log file using python and I need some advice/wisdom >> on the best way to go about it: >> >> The log file entries will consist of something like this: >> >> ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled >> locked working.lock >> status running >> status complete >> >> ID=9009 IID=87234785 execute wait - 01.21.2007 status wait >> waiting to lock >> status wait >> waiting on ID=8688 >> >> and so on... >> >For the parsing of this data, here is a pyparsing approach. Once >parse, the pyparsing ParseResults data structures can be massaged into >a queryable list. See the examples at the end for accessing the >individual parsed fields. > >-- Paul > >data = """ >ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled > locked working.lock > status running > status complete > > >ID=9009 IID=87234785 execute wait - 01.21.2007 status wait > waiting to lock > status wait > waiting on ID=8688 > >""" >from pyparsing import * > >integer=Word(nums) >idref = "ID=" + integer.setResultsName("id") >iidref = "IID=" + integer.setResultsName("iid") >date = Regex(r"\d\d\.\d\d\.\d{4}") > >logLabel = Group("execute" + oneOf("begin wait")) >logStatus = Group("status" + oneOf("enabled wait")) >lockQual = Group("locked" + Word(alphanums+".")) >waitingOnQual = Group("waiting on" + idref) >statusQual = Group("status" + oneOf("running complete wait")) >waitingToLockQual = Group(Literal("waiting to lock")) >statusQualifier = statusQual | waitingOnQual | waitingToLockQual | >lockQual >logEntry = idref + iidref + logLabel.setResultsName("logtype") + "-" \ > + date + logStatus.setResultsName("status") \ > + ZeroOrMore(statusQualifier).setResultsName("quals") > >for tokens in logEntry.searchString(data): > print tokens > print tokens.dump() > print tokens.id > print tokens.iid > print tokens.status > print tokens.quals > print > >prints: > >['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', >'01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], >['status', 'running'], ['status', 'complete']] >['ID=', '8688', 'IID=', '98889998', ['execute', 'begin'], '-', >'01.21.2007', ['status', 'enabled'], ['locked', 'working.lock'], >['status', 'running'], ['status', 'complete']] >- id: 8688 >- iid: 98889998 >- logtype: ['execute', 'begin'] >- quals: [['locked', 'working.lock'], ['status', 'running'], >['status', 'complete']] >- status: ['status', 'enabled'] >8688 >98889998 >['status', 'enabled'] >[['locked', 'working.lock'], ['status', 'running'], ['status', >'complete']] > >['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', >'01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', >'wait'], ['waiting on', 'ID=', '8688']] >['ID=', '9009', 'IID=', '87234785', ['execute', 'wait'], '-', >'01.21.2007', ['status', 'wait'], ['waiting to lock'], ['status', >'wait'], ['waiting on', 'ID=', '8688']] >- id: 9009 >- iid: 87234785 >- logtype: ['execute', 'wait'] >- quals: [['waiting to lock'], ['status', 'wait'], ['waiting on', >'ID=', '8688']] >- status: ['status', 'wait'] >9009 >87234785 >['status', 'wait'] >[['waiting to lock'], ['status', 'wait'], ['waiting on', 'ID=', >'8688']] Paul, Thanks! That's a great module. I've been going through the docs and it seems to do exactly what I need... I appreciate your help! From nmm1 at cus.cam.ac.uk Mon Jan 15 16:23:15 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 15 Jan 2007 21:23:15 GMT Subject: Maths error References: <1168894093.278546.209850@m58g2000cwm.googlegroups.com> Message-ID: In article <1168894093.278546.209850 at m58g2000cwm.googlegroups.com>, "Rhamphoryncus" writes: |> |> I've been experimenting with a fixed-point interval type in python. I |> expect many algorithms would require you to explicitly |> round/collapse/whatever-term the interval as they go along, essentially |> making it behave like a float. Yes, quite. |> Do you think it'd suitable for |> general-use, assuming you didn't mind the explicit rounding? I doubt it. Sorry. |> Unfortunately I lack a math background, so it's unlikely to progress |> past an experiment. As the same is true for what plenty of people have done, despite them having good backgrounds in mathematics, don't feel inferior! Regards, Nick Maclaren. From paddy3118 at netscape.net Tue Jan 9 01:12:25 2007 From: paddy3118 at netscape.net (Paddy) Date: 8 Jan 2007 22:12:25 -0800 Subject: Colons, indentation and reformatting. Message-ID: <1168323145.393149.299540@v33g2000cwv.googlegroups.com> i was just perusing a Wikipedia entry on the "off side rule" at http://en.wikipedia.org/wiki/Off-side_rule . It says that the colon in Python is purely for readability, and cites our FAQ entry http://www.python.org/doc/faq/general.html#why-are-colons-required-for-the-if-while-def-class-statements . However, near the top of the Alternatives section, it states that for C type, curly braces using languages: "An advantage of this is that program code can be automatically reformatted and neatly indented without fear of the block structure changing". Thinking about it a little, it seems that a colon followed by non-indented code that has just been pasted in could also be used by a Python-aware editor as a flag to re-indent the pasted code. Tell me it is not so, or I will be editing the Wikipedia page I think. And if it is true then do we need to update the FAQ? - Paddy. From hardcoded.software at gmail.com Thu Jan 11 19:22:03 2007 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 11 Jan 2007 16:22:03 -0800 Subject: Matching Directory Names and Grouping Them References: <1168554244.459131.190440@k58g2000hse.googlegroups.com> <1168558702.851290.230100@i56g2000hsf.googlegroups.com> Message-ID: <1168561323.817430.34950@11g2000cwr.googlegroups.com> >From your example, if you want to group every path that has the same last 9 characters, a simple solution could be something like: groups = {} for path in paths: group = groups.setdefault(path[-9:],[]) group.append(path) I didn't actually test it, there ight be syntax errors. J wrote: > Steve- > > Thanks for the reply. I think what I'm trying to say by similar is > pattern matching. Essentially, walking through a directory tree > starting at a specified root folder, and returning a list of all > folders that matches a pattern, in this case, a folder name containing > a four digit number representing year and a subdirectory name > containing a two digit number representing a month. The matches are > grouped together and written into a text file. I hope this helps. > > Kind Regards, > J > > Steve Holden wrote: > > J wrote: > > > Hello Group- > > > > > > I have limited programming experience, but I'm looking for a generic > > > way to search through a root directory for subdirectories with similar > > > names, organize and group them by matching their subdirectory path, and > > > then output their full paths into a text file. For example, the > > > contents of the output text file may look like this: > > > > > > \Input1\2001\01\ > > > \Input2\2001\01\ > > > \Input3\2001\01\ > > > > > > \Input1\2002\03\ > > > \Input2\2002\03\ > > > \Input3\2002\03\ > > > > > > \Input2\2005\05\ > > > \Input3\2005\05\ > > > > > > \Input1\2005\12\ > > > \Input3\2005\12\ > > > > > > I tried working with python regular expressions, but so far haven't > > > found code that can do the trick. Any help would be greatly > > > appreciated. Thanks! > > > > > Define "similar". > > > > regards > > Steve > > -- > > Steve Holden +44 150 684 7255 +1 800 494 3119 > > Holden Web LLC/Ltd http://www.holdenweb.com > > Skype: holdenweb http://del.icio.us/steve.holden > > Blog of Note: http://holdenweb.blogspot.com From steveo at syslang.net Fri Jan 12 18:39:16 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 12 Jan 2007 18:39:16 -0500 (EST) Subject: Is it possible to get whole commandline include redirection.., etc In-Reply-To: <1168643505.949920.154470@a75g2000cwd.googlegroups.com> References: <1168643505.949920.154470@a75g2000cwd.googlegroups.com> Message-ID: On Friday, Jan 12th 2007 at 15:11 -0800, quoth postindex at gmail.com: =>Can I get whole commandline not only argument list. => =>1. When I command like this => $ a.py > filename =>2. sys.argv is returns only argument list => ['a.py'] => =>Is there a way to find out 'redirection' information. As a new person to python, I'm going to go out on a limb and declare this to not be a python question and to be a Unix question. If you're running under Windoze then my answer may not be valid since, as you can see, I only recently learned how to spell it. When any Unix commandline is handed to a shell, all pipes and redirections are processed by that shell so that the various IO channels for the command are defined to point to the desired files before the command is even started. Only after that setup has occured is the desired command even started. There are books on the subject and this is not the correct forum to explain it all, but the docs to read that will leave you with no hint of idiomatic usage are all in section 2: fork, exec, open, close, dup and pipe (plus a few others not germain here also). -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From steve at REMOVE.THIS.cybersource.com.au Sat Jan 27 00:39:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 27 Jan 2007 16:39:17 +1100 Subject: instancemethod References: <1169872049.261689.263820@j27g2000cwj.googlegroups.com> Message-ID: On Fri, 26 Jan 2007 20:27:29 -0800, Michele Simionato wrote: > On Jan 22, 2:58 am, "Gert Cuykens" wrote: > >> http://www.faqts.com/knowledge_base/view.phtml/aid/16824 > > There is a factual mistake on that reference. The last sentence > >> One final note: the single most common use for classmethod is probably >> in overriding __new__(). It is always needed when overriding __new__() >> because __new__() is a classmethod. > > is wrong, since __new__ is a staticmethod, NOT a classmethod. There's a contradiction in the Python docs. >From http://docs.python.org/lib/built-in-funcs.html we see: "A class method receives the class as implicit first argument, just like an instance method receives the instance." and "A static method does not receive an implicit first argument." But from http://docs.python.org/ref/customization.html we read: "__new__(cls[, ...]) Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class)." It seems that the description of __new__ is wrong. Since __new__ takes an implicit first argument, the class, it is a class method, not a static method. -- Steven. From fumanchu at amor.org Wed Jan 24 17:57:06 2007 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 24 Jan 2007 14:57:06 -0800 Subject: ANN: Dejavu 1.5.0RC1 Message-ID: <435DF58A933BA74397B42CDEB8145A8608C50C4F@ex9.hostedexchange.local> The Dejavu Object-Relational Mapper (version 1.5.0RC1) is now available and in the public domain. Get it at http://projects.amor.org/dejavu, or from PyPI: http://www.python.org/pypi/Dejavu/1.5.0RC1. Dejavu is an Object-Relational Mapper for Python applications. It is designed to provide the "Model" third of an MVC application. Dejavu avoids making decisions in the framework which are better left to developers, and avoids forcing developers to make decisions which are better left to deployers. In particular, deployers are allowed to mix and match storage mechanisms, including how and when to cache objects in memory, making it easier for deployers to tune applications to their particular environment. Dejavu provides: Modeling Layer 1. A base Unit class for persisting objects to storage. 2. A base UnitProperty class for persistent object attributes. 3. ID Sequencers. 4. Associations between Unit classes. 5. Unit Engines, Rules, and Collections. 6. Aggregation and analysis tools. Application Layer 1. Expressions: pure Python lambda querying. This is perhaps the most appealing feature of Dejavu. 2. Sandboxes, which serve as Identity Maps, transaction boundaries, and per-connection caches. 3. An Arena class for application-level data. Storage Layer 1. A base StorageManager class and specification. Unlike many ORMs, Dejavu does not require you to have complete control of the back end. 2. Specific StorageManagers for: a. Microsoft SQL Server/MSDE b. Microsoft Access (Jet) c. PostgreSQL d. MySQL e. SQLite f. Shelve g. Firebird h. RAM i. Filesystem What's New in 1.5: http://projects.amor.org/dejavu/wiki/WhatsNewIn15 * Native ID sequencing. * Distributed transactions and tested isolation levels. * Complete database introspection and auto discovery. * New Firebird support. * New RAM Storage Manager. * New psycopg2 support. * New support for using the sqlite3 module built into Python 2.5. * Support for typed and typeless SQLite. * Support for SQLite :memory: databases. * Complete numeric precision and scale support. * Native date function support. * Complete M x N type-adaptation. * Bulletproof encoding support. * New 'range' function which returns the closed interval [min(attr), ..., max(attr)]. * New 'sum' function which returns the sum of all non-None values for the given cls.attr. * Multiple and custom Associations. * Improved performance (especially ADO). * New JSON encoder/decoder. * Short config names for Storage Managers. * ADO: New support for the CURRENCY datatype. * ADO: Improved string comparisons using Convert and StrComp. Upgrading to 1.5: See http://projects.amor.org/dejavu/wiki/UpgradeTo1.5 Documentation for 1.5: http://projects.amor.org/docs/dejavu/1.5.0RC1/ Robert Brewer System Architect Amor Ministries fumanchu at amor.org From duncan.booth at invalid.invalid Wed Jan 17 04:33:17 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jan 2007 09:33:17 GMT Subject: How to determine what exceptions a method might raise? References: <12qq98ijkn5mld8@corp.supernews.com> <1169022894.357383.45950@a75g2000cwd.googlegroups.com> Message-ID: "George Sakkis" wrote: > As for the OP's question, since file is a fixed builtin, I think it > should be possible to know all the possible exceptions that can be > raised; I'm not sure if it's clearly documented though. Just calling 'file' the most obvious exceptions it can raise are: IOError MemoryError ValueError I'm not sure if it can return UnicodeDecodeError, it looks as though it may be possible on windows, but I couldn't trigger it. Assigning the result to a variable can of course raise absolutely any exception. That's the main problem: just because a C function raises only a few different exceptions doesn't mean that the line of code calling it cannot generate a host more. From ajdeshpande at gmail.com Wed Jan 31 12:04:15 2007 From: ajdeshpande at gmail.com (Analog Kid) Date: Wed, 31 Jan 2007 22:34:15 +0530 Subject: What is the dummy statement that do nothing in Python? In-Reply-To: References: Message-ID: <4ccf86300701310904s3d6c7aecscc31644cc84dade7@mail.gmail.com> hey dongsheng: not too sure what you are looking for ... but i guess a simple "pass" statement should do it ... if a > b: pass hth, -ajay On 1/31/07, Dongsheng Ruan wrote: > > I remember that in python there is some kind of dummy statement that just > holds space and does nothing. > > I want it to hold the place after a something like if a>b: do nothing > > I can't just leave the space blank after if statement because there will > be > error message. > > Does anybody know what to insert there? > > Thanks! > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- BBQ - "Spare (My) Ribs" being contemplated -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Thu Jan 25 23:26:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 26 Jan 2007 15:26:09 +1100 Subject: assertions to validate function parameters References: Message-ID: On Thu, 25 Jan 2007 16:54:05 +0000, Matthew Wilson wrote: > Lately, I've been writing functions like this: > > def f(a, b): > > assert a in [1, 2, 3] > assert b in [4, 5, 6] > > The point is that I'm checking the type and the values of the > parameters. If somebody passes in a == MyNumericClass(2), which would have worked perfectly fine except for the assert, your code needlessly raises an exception. Actually that's a bad example, because surely MyNumericClass(2) would test equal to int(2) in order to be meaningful. So, arguably, testing that values fall within an appropriate range is not necessarily a bad idea, but type-testing is generally bad. Note also that for real code, a bare assert like that is uselessly uninformative: >>> x = 1 >>> assert x == 3 Traceback (most recent call last): File "", line 1, in ? AssertionError This is better: >>> assert x == 3, "x must be equal to three but is %s instead" % x Traceback (most recent call last): File "", line 1, in ? AssertionError: x must be equal to three but is 1 instead This is even better still: >>> if x != 3: ... raise ValueError("x must be equal to three but is %s instead" % x) ... Traceback (most recent call last): File "", line 1, in ? ValueError: x must be equal to three but is 1 instead And even better still is to move that test out of your code and put it into unit tests (if possible). > I'm curious how this does or doesn't fit into python's duck-typing > philosophy. Doesn't fit, although range testing is probably okay. > I find that when I detect invalid parameters overtly, I spend less time > debugging. Yes, probably. But you end up with less useful code: def double(x): """Return x doubled.""" assert x == 2.0 and type(x) == float return 2*x Now I only need to test one case, x == 2.0. See how much testing I don't have to do? *wink* There's a serious point behind the joke. The less your function does, the more constrained it is, the less testing you have to do -- but the less useful it is, and the more work you put onto the users of your function. Instead of saying something like a = MyNumericClass(1) b = MyNumericClass(6) # more code in here... # ... result = f(a, b) you force them to do this: a = MyNumericClass(1) b = MyNumericClass(6) # more code in here... # ... # type-cast a and b to keep your function happy result = f(int(a), int(b)) # and type-cast the result to what I want result = MyNumericClass(result) And that's assuming that they can even do that sort of type-cast without losing too much information. > Are other people doing things like this? Any related commentary is > welcome. Generally speaking, type-checking is often just a way of saying "My function could work perfectly with any number of possible types, but I arbitrarily want it to only work with these few, just because." Depending on what you're trying to do, there are lots of strategies for avoiding type-tests: e.g. better to use isinstance() rather than type, because that will accept subclasses. But it doesn't accept classes that use delegation. Sometimes you might have a series of operations, and you want the lot to either succeed or fail up front, and not fail halfway through (say, you're modifying a list and don't want to make half the changes needed). The solution to that is to check that your input object has all the methods you need: def f(s): """Do something with a string-like object.""" try: upper = s.upper split = s.split except AttributeError: raise TypeError('input is not sufficiently string-like') return upper() Good unit tests will catch anything type and range tests will catch, plus a whole lot of other errors, while type-testing and range-testing will only catch a small percentage of bugs. So if you're relying on type- and range-testing, you're probably not doing enough testing. -- Steven. From garyjefferson123 at yahoo.com Thu Jan 25 16:22:18 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 25 Jan 2007 13:22:18 -0800 Subject: logging module and doctest In-Reply-To: References: <1169703145.393435.166020@m58g2000cwm.googlegroups.com> Message-ID: <1169760137.955864.178810@a75g2000cwd.googlegroups.com> Peter Otten wrote: > Peter Otten wrote: > > > Gary Jefferson wrote: > > > >> I've written a logging.filter and would like to use doctest on it > >> (using a StreamHandler for stdout), but this doesn't seem possible. > >> Output from the logger seems to disappear (running the doctest strings > >> through the interpreter as-is yields expected results). I assume this > >> is because doctest does something with logging. > > > > It redirects stdout to a StringIO subclass to capture the output. > > > >> Is there any way to make these work together? > > > > Using the StreamHandler with something like > > > > class WrapStdOut(object): > > def __getattr__(self, name): > > return getattr(sys.stdout, name) > > > > instead of sys.stdout directly should work. > > Or create the StreamHandler inside your doctest where sys.stdout is already > redirected. > > Peter I was creating the StreamHandler inside doctest. Turns out, however, that I hadn't imported 'sys', and so it didn't work. Its a little strange that this didn't result in an error, but there you have it. Thanks for the tip that led me to discover this. Gary From James.w.Howard at gmail.com Wed Jan 17 18:05:20 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: 17 Jan 2007 15:05:20 -0800 Subject: Asyncore select statement problem Message-ID: <1169075120.491855.103200@q2g2000cwa.googlegroups.com> I have a problem with python's asyncore module throwing a bad file descriptor error. The code might be difficult to copy here, but the problem is essentially: The server wants to sever the connection of an open Asyncore socket. Calling the socket.close() nor the socket.shutdown(2) calls seem to work. The only way I can close the connection without creating the error below is to have the client close the connection. I have the asyncore.loop() as the last line of a thread that is spawned within the applications "mainframe.py" or gui thread. It doesn't seem to me like this would make a difference, but I am unfamiliar with the specifics of how the asyncore module works. Any thoughts people have would be greatly appreciated. If needed I may be able to create a small version of the problem to post for people to see. Thanks, Jim Howard Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 460, in __bootstrap self.run() File "/Users/jwhoward2/Documents/Projects/LJServer/LJDeviceServer/DeviceServer.py", line 23, in run asyncore.loop() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/asyncore.py", line 191, in loop poll_fun(timeout, map) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/asyncore.py", line 121, in poll r, w, e = select.select(r, w, e, timeout) error: (9, 'Bad file descriptor') From robert.kern at gmail.com Tue Jan 23 23:00:52 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Jan 2007 22:00:52 -0600 Subject: easy_install pylons failure - www.myghty.org unavailable In-Reply-To: References: <17846.54389.27457.383902@montanaro.dyndns.org> Message-ID: Robert Kern wrote: > skip at pobox.com wrote: > >> Is it not able to get past this point because there is only one source for >> Myghty or does it always need to go to a package's home page? I was able to >> work around this by manually downloading the Myghty-1.1.tar.gz file and >> installing it. > > Asking on Distutils-SIG list will be more likely to get Phillip Eby's attention. > It surprises me that setuptools didn't pick up the tarball on the CheeseShop. Now that www.myghty.org is back up, I see that the CheeseShop tarball is picked up eventually. I believe that easy_install checks all of the various sources to try to find a best match (for some definition of "best"). Of course, I would consider it a bug that an exception raised while trying to fetch one possible source stops the entire process, particularly when a matching tarball has already been found. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From beej at beej.us Tue Jan 30 15:44:49 2007 From: beej at beej.us (Beej) Date: 30 Jan 2007 12:44:49 -0800 Subject: Help me understand this In-Reply-To: <528hvsF1lrmsgU1@mid.uni-berlin.de> References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> <1170146755.446429.90720@v45g2000cwv.googlegroups.com> <528hvsF1lrmsgU1@mid.uni-berlin.de> Message-ID: <1170189889.846237.157500@a75g2000cwd.googlegroups.com> On Jan 30, 1:38 am, "Diez B. Roggisch" wrote: > Because 2. is the start of a float-literal. That isn't distinguishable for > the parsere otherwise. Oh, excellent! I wonder why I didn't think of that--I was too busy in "get a field" mode it didn't even occur to me that the "." had a different context, no matter how much more obvious. >>> print 2. 2.0 >>> type(2.) -Beej From altis at semi-retired.com Tue Jan 30 11:46:09 2007 From: altis at semi-retired.com (Kevin Altis) Date: Tue, 30 Jan 2007 08:46:09 -0800 Subject: ANNOUNCE: OSCON 2007 Call for Participation Ends Soon Message-ID: <45bf7567$0$497$815e3792@news.qwest.net> Be Heard at OSCON 2007 -- Submit Your Proposal to Lead Sessions and Tutorials by February 5! The O'Reilly Open Source Convention July 23-27, 2007 Portland, Oregon http://conferences.oreillynet.com/os2007/ More than 2500 open source developers, gurus, experts and users will gather, eager to network, learn, and share the latest knowledge on open source software. We think of this group as "the best of the best," and we invite you to contribute to the more than 400 sessions and 40 tutorials designed to build inspiration and know-how. Submit your proposals at: http://conferences.oreillynet.com/cs/os2007/create/e_sess Share your favorite techniques, your proven successes, and newly developed technology in tracks for Linux, PHP, Perl, Python, Ruby, Java, Databases, Desktop Applications, Web Applications (client-side and server-side), Windows, Administration, Security, and Emerging Topics. No topic (other than closed source software) is off-limits, so send us your best ideas. Among the hot topics we want to hear about are: - Tools for the administration and deployment of large server farms - Parallelization, grid, and multicore technologies - Virtualization - Ajax, Javascript, standards-based design, and other client-side web issues - Seaside, Rails, Django, and other interesting server-side technology - Ubuntu as an emergent usable Linux distro and contender for Red Hat and Sun's client and server markets - Java as open source - AI, machine learning, and other ways of making software smarter than the people using it - User experience and usability engineering lessons for web and desktop software - The spread of open source into law, culture, data, and services, and the accompanying issues and lessons For full details and guidelines on submitting your proposal, go to http://conferences.oreillynet.com/os2007/. If you know someone who would be a good speaker, please pass this email on. Whether as a speaker or as an attendee, you'll want to participate in this meeting of the best minds in the business, which will also include the O'Reilly Radar Executive Briefing. Be sure to save the dates -- July 23-27. Registration will open in early April. We hope to see you in Portland in July! The OSCON Team P.S. Remember, proposals for sessions and tutorials must be submitted to http://conferences.oreillynet.com/os2007/ by (11:59PM Pacific Standard Time) Monday, February 5. ******************************************************* To change your newsletter subscription options, please visit http://www.oreillynet.com/cs/nl/home. To unsubscribe from O'Reilly conference announcements, email conferences-unsubscribe at oreilly.com. For assistance, email help at oreillynet.com. O'Reilly Media, Inc. 1005 Gravenstein Highway North, Sebastopol, CA 95472 ******************************************************* From bearophileHUGS at lycos.com Thu Jan 18 21:15:54 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Jan 2007 18:15:54 -0800 Subject: Match 2 words in a line of file In-Reply-To: <1169172293.938820.103400@51g2000cwl.googlegroups.com> References: <1169164007.110870.29650@m58g2000cwm.googlegroups.com> <1169166223.073714.109620@51g2000cwl.googlegroups.com> <1169172293.938820.103400@51g2000cwl.googlegroups.com> Message-ID: <1169172954.107365.133950@51g2000cwl.googlegroups.com> MrJean1 wrote: > def lines_with_words(file, word1, word2): > """Print all lines in file that have both words in it.""" > for line in file: > words = line.split() > if word1 in words and word2 in words: > print line This sounds better, it's probably faster than the RE version, Python 2.5 has a really fast str.__contains__ method, done by effbot: def lines_with_words(file, word1, word2): """Print all lines in file that have both words in it. (word1 may be the less frequent word of the two).""" for line in file: if word1 in line and word2 in line: print line Bye, bearophile From webraviteja at gmail.com Mon Jan 22 17:02:41 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 22 Jan 2007 14:02:41 -0800 Subject: How to convert a string into an integer In-Reply-To: <1169502340.434227.224820@11g2000cwr.googlegroups.com> References: <1169502340.434227.224820@11g2000cwr.googlegroups.com> Message-ID: <1169503361.730963.178670@v45g2000cwv.googlegroups.com> yinglcs at gmail.com wrote: > Can you please tell me why the following code does not work in python? > My guess is I need to convert 'count' from a string to an integer. How > can I do that? > And my understanding is python is a dynamic type language, should > python convert it for me automatically? > > count = sys.argv[2] > for i in range(count): > #do some stuff > > Thank you. You are confusing dynamic typing with weak typing. Weakly typed languages (such as BASIC perform) such implicit conversions. However, Python is dynamically and strongly typed. With dynamic typing, the type information resides with the actual object and not with the name referring to it. That simply means that the type cannot be determined till the object is actually created (i.e till runtime). But once created, the object does have a type. So you will need to explicitly convert yourself. In this case with int_value = int(string_value) Ravi Teja. From michael at mustun.ch Wed Jan 3 19:16:01 2007 From: michael at mustun.ch (Michael) Date: Thu, 04 Jan 2007 01:16:01 +0100 Subject: code optimization (calc PI) In-Reply-To: <459BFDCB.4000503@sschwarzer.net> References: <5020j6F1du59cU1@mid.uni-berlin.de> <459BFDCB.4000503@sschwarzer.net> Message-ID: Yes. But it still runns very slowly. If someone is really interested in speed optimization, I can publish my PI-calc code. Maybe for some Python compiler/interpreter hackers... ;-) (There are only 2 while-loops, one within another, and some simple basic calculations. Nothing special.) Stefan Schwarzer wrote: > On 2007-01-03 16:50, mm wrote: > >>More general, maybe there is a speed optimazation docu out there. > > > At least Alex Martellis "Python in a Nutshell" has a section on > optimization. > > I presented this at the last EuroPython conference: > http://sschwarzer.com/download/optimization_europython2006.pdf > > Stefan > From Florian.Lindner at xgm.de Wed Jan 24 15:48:38 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Wed, 24 Jan 2007 21:48:38 +0100 Subject: Static variables Message-ID: Hello, does python have static variables? I mean function-local variables that keep their state between invocations of the function. Thanks, Florian From tubby at bandaheart.com Thu Jan 25 16:05:11 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 25 Jan 2007 16:05:11 -0500 Subject: pdf to text Message-ID: I know this question comes up a lot, so here goes again. I want to read text from a PDF file, run re searches on the text, etc. I do not care about layout, fonts, borders, etc. I just want the text. I've been reading Adobe's PDF Reference Guide and I'm beginning to develop a better understanding of PDF in general, but I need a bit of help... this seems like it should be easier than it is. Here's some code: import zlib fp = open('test.pdf', 'rb') bytes = [] while 1: byte = fp.read(1) #print byte bytes.append(byte) if not byte: break for byte in bytes: op = open('pdf.txt', 'a') dco = zlib.decompressobj() try: s = dco.decompress(byte) #print >> op, s print s except Exception, e: print e op.close() fp.close() I know the text is compressed... that it would have stream and endstream makers and BT (Begin Text) and ET (End Text) and that the uncompressed text is enclosed in parenthesis (this is my text). Has anyone here done this in a simple fashion? I've played with the pyPdf library some, but it seems overly complex for my needs (merge PDFs, write PDFs, etc). I just want a simple PDF text extractor. Thanks From arkanes at gmail.com Wed Jan 24 12:23:33 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 11:23:33 -0600 Subject: The reliability of python threads In-Reply-To: References: Message-ID: <4866bea60701240923l1facdeccnb308cb4a0b67b4ff@mail.gmail.com> On 24 Jan 2007 17:12:19 GMT, Nick Maclaren wrote: > > In article , > "Carl J. Van Arsdall" writes: > |> Hey everyone, I have a question about python threads. Before anyone > |> goes further, this is not a debate about threads vs. processes, just a > |> question. > |> > |> With that, are python threads reliable? Or rather, are they safe? I've > |> had some strange errors in the past, I use threading.lock for my > |> critical sections, but I wonder if that is really good enough. > |> > |> Does anyone have any conclusive evidence that python threads/locks are > |> safe or unsafe? > > Unsafe. They are built on top of unsafe primitives (POSIX, Microsoft > etc.) Python will shield you from some problems, but not all. > > There is precious little that you can do, because the root cause is > that the standards and specifications are hopelessly flawed. > This is sufficiently inaccurate that I would call it FUD. Using threads from Python, as from any other language, requires knowledge of the tradeoffs and limitations of threading, but claiming that their usage is *inherently* unsafe isn't true. It is almost certain that your code and locking are flawed, not that the threads underneath you are buggy. From nogradi at gmail.com Thu Jan 18 13:56:05 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 18 Jan 2007 19:56:05 +0100 Subject: Traversing the properties of a Class In-Reply-To: <1169141253.332211.12790@38g2000cwa.googlegroups.com> References: <1169141253.332211.12790@38g2000cwa.googlegroups.com> Message-ID: <5f56302b0701181056p67bcf4c5g371fa80a6f3d76da@mail.gmail.com> > I'm using Python version 2.4 and I created a class with some properties > like: > > def GetCallAmount(self): > return somedata > > def GetCallCurrency(self): > return somemoredata > > more....defs..etc. > > CallAmount = property(GetCallAmount,None,None,None) > CallCurrency = property(GetCallCurrency, None, None, None) > > more....properies..etc. > > For debugging purposes, I would like to traverse the class listing out > all the properties. for attr in dir( yourclass ): if repr( yourclass.__dict__[ attr ] ).startswith( ' References: Message-ID: <45BE3966.70704@kentsjohnson.com> skip at pobox.com wrote: > Matt> In some instances I want to access just the function f, though, > Matt> and catch the values before they've been decorated. > > def f(x): > return x * x > > @as_string > def fs(x): > return f(x) or just fs = as_string(f) Kent > > Call the one you want. > > Skip From john.pye at gmail.com Thu Jan 25 00:24:29 2007 From: john.pye at gmail.com (John Pye) Date: 24 Jan 2007 21:24:29 -0800 Subject: Catching floating point errors from linked C code In-Reply-To: References: <1169696243.262973.188540@s48g2000cws.googlegroups.com> Message-ID: <1169702669.027065.65990@v33g2000cwv.googlegroups.com> Hi John, On Jan 25, 3:43 pm, John Nagle wrote: > Python is probably running with floating point exceptions disabled, > but you can enable them in your C code, and restoring the floating > point mode when you leave, if you want. This is probably > only worth doing under a debugger, because otherwise you just end > up with an aborted instance of Python. So as far as you know, Python doesn't switch stuff like feenableexcept(FE_EXCEPT_ALL)? Does Python use the internally, or are all its FPEs detected by explicit checks beforehand? If writing a python module with SWIG, and the module uses Python callbacks, do I need to restore the signal handlers before running the callback, or python do that itself? (These might be questions better asked on the SWIG list I guess) Cheers JP From deets at nospam.web.de Fri Jan 26 08:03:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 26 Jan 2007 14:03:41 +0100 Subject: Mounting shares with python References: <1169815227.574577.176610@m58g2000cwm.googlegroups.com> Message-ID: <51uchdF1lnrdqU1@mid.uni-berlin.de> Marcpp wrote: > Hi, when i mount a share with python... > > os.system ("mount -t smbfs -o username=nobody ...") > > the problem is that I'll to be root. > Have a comand to send a root password...? > I've tried > > os.system ("su") > os.system ("the password") > > but it doesn't works. You can try to use sudo os.system ("sudo mount -t smbfs -o username=nobody ...") It must be configured properly of course. Diez From uymqlp502 at sneakemail.com Mon Jan 22 02:41:32 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 21 Jan 2007 23:41:32 -0800 Subject: Is any python like linux shell? In-Reply-To: <1169398326.510530.180860@51g2000cwl.googlegroups.com> References: <1169398326.510530.180860@51g2000cwl.googlegroups.com> Message-ID: <1169451692.443462.99220@q2g2000cwa.googlegroups.com> Frank Potter wrote: > I learned some python in windows. > And now I've turned to linux. > I read a book and it teaches how to write shell script with bash, > but I don't feel like the grammar of bash. > Since I know about python, > I want to get a linux shell which use python grammar. > I searched by google and I found pysh, which is not maintained any > more. > There's another script named pyshell, which is not likely what I'm > searching for. > So, will somebody please tell me if there are any python like shells > for linux? You could in principle use Python as a general-purpose interactive shell, but it wouldn't make much sense. Bash is more convenient for basic operations such as changing directories, listing directories, copying files, etc. For more advanced scripting, I use both bash and Python. I use bash typically as an executive for scripting Python programs. For example, I use bash for stepping through a list of directories and running a set of python programs in each directory. Sure, I could use Python for the whole thing, but simply starting programs and moving files around is more straightforward in bash than in Python. From deets at nospam.web.de Fri Jan 19 05:12:37 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 Jan 2007 11:12:37 +0100 Subject: Why this script can work? References: Message-ID: <51bjskF1jbnhrU1@mid.uni-berlin.de> Jm lists wrote: > Please help with this script: > > class ShortInputException(Exception): > '''A user-defined exception class.''' > def __init__(self,length,atleast): > Exception.__init__(self) > self.length=length > self.atleast=atleast > > try: > s=raw_input('Enter something --> ') > if len(s)<3: > raise ShortInputException(len(s),3) > # Other work can continue as usual here > except EOFError: > print '\nWhy did you do an EOF on me?' > except ShortInputException,x: > print 'ShortInputException: The input was of length %d, was > expecting at least %d' %(x.length,x.atleast) > else: > print 'No exception was raised.' > > > My questions are: > > 1) ShortInputException,x: what's the 'x'? where is it coming? except , : will catch an exception of the kind specified in (it might actually be more than one), and store the exception object in the variable named > 2) The 'if' and 'else' are not in the same indent scope,why this can work? Because additionally to if, also for and try have else-clauses. The latter two are only being called if the body of the control structure hasn't been left due to "unnatural" circumstances. See this: for i in xrange(10): pass else: print "test 1" for i in xrange(10): break else: print "test 2" try: pass except: pass else: print "test 3" try: raise "I know I shouldn't rais strings..." except: pass else: print "test 4" It will only print test 1 test 3 Diez From hotfigs at gmail.com Thu Jan 11 16:52:47 2007 From: hotfigs at gmail.com (Geoff) Date: 11 Jan 2007 13:52:47 -0800 Subject: Best FCGI handler Message-ID: <1168552367.745450.84800@p59g2000hsd.googlegroups.com> Hi! Does anyone have any recommendations for FGCI interfaces for python? For example jonpy? Thanks, Geoff From kay.schluehr at gmx.net Wed Jan 24 17:39:59 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 24 Jan 2007 14:39:59 -0800 Subject: Python does not play well with others In-Reply-To: <1169660807.369400.120220@h3g2000cwc.googlegroups.com> References: <1169660807.369400.120220@h3g2000cwc.googlegroups.com> Message-ID: <1169678399.502252.123450@j27g2000cwj.googlegroups.com> On 25 Jan., 04:46, "Paul Boddie" wrote: > > That's because, in those worlds, either the > > development team for the language or the development team > > for the subsystem takes responsibility for making them work. > > Only Python doesn't do that.And this is where I'd almost reach agreement with you. It's not enough > for the language to keep growing new features if the libraries are > broken or appear archaic, and this task seems to be outside the "core > developers" area of interest. But it shouldn't be - although this is not a request for the core developers to maintain any 3rd party package in the world, of course. A while ago someone on python-dev suggested to use builtbot to monitor were 3rd party packages get broken by new Python releases and offered this as a service to library developers. I do think this and similar ideas are relevant to improve overall quality, not only that of the CPython interpreter. I would also suggest stricter policies for PyPI were unmaintained packages might be removed after a period ( or at least tagged in a certain way ). But maybe admitting quality problems of free software that is affecting the whole community ( and not just isolated projects ) is just too much negative PR on a "competitive language market"? We all know Ruby makes us happy and Haskell is driven by real academics, who are doing software engineering right, by default. Maybe Python could survive only leaving the impression that it binds to everything and has an ever growing code base of high quality? From gagsl-py at yahoo.com.ar Sun Jan 7 15:03:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 12:03:32 -0800 Subject: strange for loop construct In-Reply-To: References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> <12ptf5bl21f2teb@corp.supernews.com> <1168193206.598957.257700@38g2000cwa.googlegroups.com> Message-ID: <1168200211.928423.319260@38g2000cwa.googlegroups.com> On 7 ene, 16:34, s... at pobox.com wrote: > Gabriel> Where do you find the "What's new" for previous releases? I > Gabriel> have to read them online. > > Google for > > what's new site:python.org That's what I do. But this post: > If you have a Python installation you should be able to find the > "Whats New" section of the docs. List comprehensions are described > pretty well in the "What's new in Python 2.0?" section. suggested that one could find that info inside the Python installation, and I was asking *where*, because I can't find it, and I suspect it actually isn't there. -- Gabriel Genellina From mail at microcorp.co.za Tue Jan 9 03:22:32 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 9 Jan 2007 10:22:32 +0200 Subject: code formatter? References: Message-ID: <021b01c733c8$415c6b00$03000080@hendrik> "siggi" wrote: > Is there a simple code formatter that first removes all indentations and > then refomats correctly? tabnanny ? - Hendrik From sturlamolden at yahoo.no Wed Jan 10 11:12:41 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 Jan 2007 08:12:41 -0800 Subject: Execute binary code In-Reply-To: References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168288176.054142.232780@s80g2000cwa.googlegroups.com> <1168355051.339026.211830@v33g2000cwv.googlegroups.com> Message-ID: <1168445561.239053.140340@77g2000hsv.googlegroups.com> Chris Mellon wrote: > This works fine if the binary data is "pure" asm, but the impresssion > the OP gave is that it's a compiled binary, which you can't just "jump > into" this way. You may have to offset the function pointer so the entry point becomes correct. From jstroud at mbi.ucla.edu Fri Jan 12 16:49:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 12 Jan 2007 13:49:00 -0800 Subject: Regex Question In-Reply-To: References: Message-ID: Bill Mill wrote: > Hello all, > > I've got a test script: > > ==== start python code ===== > > tests2 = ["item1: alpha; item2: beta. item3 - gamma--", > "item1: alpha; item3 - gamma--"] > > def test_re(regex): > r = re.compile(regex, re.MULTILINE) > for test in tests2: > res = r.search(test) > if res: > print res.groups() > else: > print "Failed" > > ==== end python code ==== > > And a simple question: > > Why does the first regex that follows successfully grab "beta", while > the second one doesn't? > > In [131]: test_re(r"(?:item2: (.*?)\.)") > ('beta',) > Failed > > In [132]: test_re(r"(?:item2: (.*?)\.)?") > (None,) > (None,) > > Shouldn't the '?' greedily grab the group match? > > Thanks > Bill Mill > bill.mill at gmail.com The question-mark matches at zero or one. The first match will be a group with nothing in it, which satisfies the zero condition. Perhaps you mean "+"? e.g. py> import re py> rgx = re.compile('1?') py> rgx.search('a1').groups() (None,) py> rgx = re.compile('(1)+') py> rgx.search('a1').groups() James From gandalf at designaproduct.biz Fri Jan 12 10:24:38 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 12 Jan 2007 16:24:38 +0100 Subject: context managers and generators In-Reply-To: <1168614604.273032.173650@51g2000cwl.googlegroups.com> References: <1168611420.448058.163860@11g2000cwr.googlegroups.com> <1168614604.273032.173650@51g2000cwl.googlegroups.com> Message-ID: <45A7A836.2020907@designaproduct.biz> > I'm still thinking there is a better way to do it, and would appreciate > any ideas. > Everything can be implemented with goto and arrays. http://entrian.com/goto/ :-P From steve at REMOVE.THIS.cybersource.com.au Sat Jan 20 05:45:32 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 20 Jan 2007 21:45:32 +1100 Subject: Does eval has the same features as Perl's? References: Message-ID: On Sat, 20 Jan 2007 17:30:24 +0800, Jm lists wrote: > Hello members, > > I want to know does the "eval" in python have the same features as in > Perl (capture errors)? > > For example,in perl I can wrote: > > $re = eval { 1 / 0 }; > > Though 1/0 is a fatal error but since it's in "eval" block so the perl > interpreter doesn't get exit. How hard would it be to actually try it? >>> eval("1/0") Traceback (most recent call last): File "", line 1, in File "", line 1, in ZeroDivisionError: integer division or modulo by zero It took about three seconds to actually test it. eval has many security risks -- as a rule, you should never pass strings you've got from the user to eval, unless you want the user to p0wn your computer. It is harder than you might think to make eval safe -- you should seriously consider it an advanced tool, not a basic tool. As a newbie, you should work under the following rule: "If I think I need to use eval, I'm probably wrong." I've been using Python for seven or eight years, and I don't think I've ever used eval in serious code. Now, suppose you find yourself wanting to use eval. You've considered the above rule carefully, and decided that it doesn't apply in this case. You've been careful to use it only on safe strings, not arbitrary strings from users. How do you use eval so it captures errors? try: eval("1/0") except ZeroDivisionError: # capture only one error pass or something like this: try: eval("something or other goes here") except Exception: # capture any error pass -- Steven. From wojciech_mula at poczta.null.onet.pl.invalid Sun Jan 28 16:13:28 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?ISO-8859-2?Q?Mu=B3a?=) Date: Sun, 28 Jan 2007 21:13:28 +0000 (UTC) Subject: Trouble with max() and __cmp__() References: <1170017167.165222.325800@a34g2000cwb.googlegroups.com> Message-ID: Thomas Nelson wrote: > My code: > > class Policy(list): > def __cmp__(self,other): > return cmp(self.fitness,other.fitness) Define method __gt__. From fsck_spam at telenet.be Wed Jan 17 14:05:18 2007 From: fsck_spam at telenet.be (Rikishi 42) Date: Wed, 17 Jan 2007 20:05:18 +0100 Subject: Making a simple script standalone References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: On Wednesday 17 January 2007 03:33, Gabriel Genellina wrote: > At Tuesday 16/1/2007 19:49, Rikishi 42 wrote: > >>What I want to do is to compile/bundle/prepare/whatever_term a simple >>Python script for deployment on a Windows machine. Installing Python >>itself on that machine, is not an option. Ideally I would like to obtain >>a single executable file, but a script+runtime is acceptable. > > distutils + py2exe Tried that, just after asking here. A bit messy (poor docs) and a very bloated result. Thanks for the answer, anyway. -- Research is what I'm doing, when I don't know what I'm doing. (von Braun) From zaz600 at gmail.com Wed Jan 24 23:25:43 2007 From: zaz600 at gmail.com (NoName) Date: 24 Jan 2007 20:25:43 -0800 Subject: How can i do this in Python? Message-ID: <1169699143.237710.277160@l53g2000cwa.googlegroups.com> perl -ane "print join(qq(\t), at F[0,1,20,21,2,10,12,14,11,4,5,6]).qq(\n)" file.txt -a autosplit mode with -n or -p (splits $_ into @F) -n assume "while (<>) { ... }" loop around program From gagsl-py at yahoo.com.ar Sun Jan 7 12:43:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: 7 Jan 2007 09:43:00 -0800 Subject: still struggling, howto use a list-element as a name ? Sory, hit send button to early In-Reply-To: References: <45a01981$0$296$426a74cc@news.free.fr> <441e$45a02246$d443bb3a$24795@news.speedlinq.nl> Message-ID: <1168191780.620228.67440@42g2000cwt.googlegroups.com> Stef Mientki ha escrito: > class LED (device): > pinlist ={ > # pin name type init-value other-parameters > 1: ('Cathode', _DIG_IN, [], _par2), > 2: ('Anode', _DIG_OUT, [], _par33) > } > > Status = {True:('On'), False:('Off')} > > def execute (self): > old = self.On > self.On = (~self.Cathode.Value & self.Anode.Value) > 0 > if self.On <> old : print self.Name, self.Status[self.On] I don't know of what type are those values (certainly the're not [] because ~[] won't work). But note that using ~ with apparently logical values doesn't work as expected. The operators &,|,^,~ are meant to be used on integers, and work bit by bit. The operators and, or, xor, not operate on logical, or boolean, values. py> value = True py> negvalue = ~value py> if negvalue: print "oops!" ... oops! py> bool(negvalue) True If you want to express the condition "The led is ON when the value of Anode is > 0 and the value of Cathode is < 0" that would be self.On = self.Anode.Value>0 and self.Cathode.Value<0 but since I don't know the types of values involved I'm not sure if this expression is right. -- Gabriel Genellina From duncan.booth at invalid.invalid Tue Jan 23 16:00:21 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jan 2007 21:00:21 GMT Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> <1169563580.634000.122540@v45g2000cwv.googlegroups.com> Message-ID: "gangesmaster" wrote: > ugliness :) > > so this is why [lambda: i for i in range(10)] will always return 9. > imho that's a bug, not a feature. Horses for courses. There are cases where you need to get the latest value of the bound variable, and there are cases where you want the value at the time it was bound. For the latter case you have always been able to use default arguments. From Thomas.Ploch at gmx.net Sun Jan 7 17:33:11 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Sun, 07 Jan 2007 23:33:11 +0100 Subject: how to find the longst element list of lists In-Reply-To: <%keoh.230$L06.209@nntpserver.swip.net> References: <45a169f0$0$309$426a34cc@news.free.fr> <%keoh.230$L06.209@nntpserver.swip.net> Message-ID: <45A17527.3070206@gmx.net> Michael M. schrieb: >> Err... this makes three distinct lists, not a list of lists. >> > > Sure. Logically spoken. Not in Python code. Or a number of lists. > Sure not [[ bla... ] [bla.]] etc. ??????? Thomas From gmenhennitt at optusnet.com.au Tue Jan 9 17:29:06 2007 From: gmenhennitt at optusnet.com.au (Graham Menhennitt) Date: Wed, 10 Jan 2007 09:29:06 +1100 Subject: injecting functions into a python sandbox within a python program Message-ID: <45a4172e$0$71751$c30e37c6@ken-reader.news.telstra.net> I have a large Python 2.5 program that I want my users to be able to "extend" using a Python script. However, I want their script to run in a sandbox within the overall program so that they only have access to the rest of the program via a single simple interface. Note that this is not meant to be a real anti-hacker type security sandbox - just "help them to avoid shooting themselves in the foot" type security. So I created a single object that has the interface that I want them to access. I call their script via "exec" passing the single interface object in the "globals" parameter to exec. It (conceptually) looks like this: i = Interface() glob = { 'i': i } exec script in glob Then they can call i.whatever() from within their script. This all works fine. Now, what I want to do is provide some "helper" functions for them to use in the script. These functions still only access the rest of the program via 'i'. They just wrap some of the interface functions to make life easier for the user. My current solution is to prepend these functions onto the start of the script. I.e. helperFuncs = """ def f1(): i.whatever() """ exec helperFuncs + "\n" + script.read() in glob This works but doesn't seem very elegant. I've tried defining the helper funcions in my caller and passing them through the globals i.e. def f1(): i.whatever() glob = { 'i': i, 'f1': f1 } exec script in glob The problem here is that the functions don't have access to the global variable 'i'. I need to use that object instance since it has other functionality that is required to interface to the rest of the program. I'm sure that this is simple to get around for a Python expert (which I am not!). Does anybody have any ideas? Any alternate approach? Thanks in advance for any assistance, Graham From tjreedy at udel.edu Tue Jan 23 12:28:55 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Jan 2007 12:28:55 -0500 Subject: best package for a physical simulation? References: <60915.195.220.102.78.1169558458.squirrel@mailgate.phys.ens.fr> Message-ID: wrote in message news:60915.195.220.102.78.1169558458.squirrel at mailgate.phys.ens.fr... | Hello everyone, | i would like to use python to perform some simulation involving collisions | of colloidal particles. | which is the best package/engine to do that in python? | thanks, I would start with numpy/scipy and perhaps look at Scientific Python. tjr From rds1226 at sh163.net Tue Jan 16 15:07:16 2007 From: rds1226 at sh163.net (Dongsheng Ruan) Date: Tue, 16 Jan 2007 15:07:16 -0500 Subject: How can I create a linked list in Python? References: Message-ID: Thanks for your kindly help. I am new CS student taking datat structure and algorithms with AHO's book with the same title. The book is done in Pascal, which might be an outdated language. However, my instructor probably wants us to understand the list ADT better by not using the built in list in Python. "Gary Herron" wrote in message news:mailman.2791.1168975031.32031.python-list at python.org... > Dongsheng Ruan wrote: >> with a cell class like this: >> >> #!/usr/bin/python >> >> import sys >> >> class Cell: >> >> def __init__( self, data, next=None ): >> self.data = data >> self.next = next >> >> def __str__( self ): >> return str( self.data ) >> >> def echo( self ): >> print self.__str__() > If you really want a list (as Python defines a list - with all the > methods) then you should use Python's lists. They are quite efficient and > convenient: > > l = [Cell(1), Cell(2), Cell(3)] > > However, if what you want is each cell to refer to a next cell (which > after all is what a linked list does), then you already have it with the > next attribute. (In other languages you might implement 'next' as a > pointer, while in Python we call it a reference -- but it amounts to the > same thing.) Create it this way: > > c = Cell(3) > b = Cell(2, c) a = Cell(1, b) > > or > > a = Cell(1, Cell(2, Cell(3))) > > However, I'll repeat this: The concept of a linked list if a figment of > languages with pointer data types. Python abstracts that by allowing > attributes to contain references to other objects. However, you're much > better off if you can use Python's list data structure rather than try to > emulate an outdated concept in a modern language. > > Gary Herron > > > From horpner at yahoo.com Wed Jan 24 09:23:06 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 24 Jan 2007 14:23:06 GMT Subject: Thoughts on using isinstance References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> Message-ID: On 2007-01-24, abcd wrote: > In my code I am debating whether or not to validate the types of data > being passed to my functions. For example > > def sayHello(self, name): > if not name: > rasie "name can't be null" > if not isinstance(name, str): > raise "name must be a string" > print "Hello " + name > > Is the use of isinstance a "bad" way of doing things? is it a > "heavy" operation? for example, if I use this in each function > validate input will it slow things down a lot? > > just curious how you might handle this type of situation (other > than not validating at all). Validation of parameters is an excellent idea, but *not* validation of datatypes. The problem is that sayHello can function properly with many more objects than just strings, if you write it differently. The following version accepts any iterable over strings. def sayHello(self, name): it = iter(name) print "Hello", ''.join(it) It still lacks validation. But to validate a name you will need to conceive a set of regular strings that contains every name you'd like to accept. Names probably aren't worth validating, although you might reasonably reject a few things, like the empty string. -- Neil Cerutti From gagsl-py at yahoo.com.ar Thu Jan 11 19:34:52 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 21:34:52 -0300 Subject: Fixed keys() mapping In-Reply-To: <1168535970.585977.317760@p59g2000hsd.googlegroups.com> References: <1168535970.585977.317760@p59g2000hsd.googlegroups.com> Message-ID: <7.0.1.0.0.20070111211744.0592cfd8@yahoo.com.ar> At Thursday 11/1/2007 14:19, George Sakkis wrote: >The implementation I came up with goes like this: each fkdict instance >stores only the values as a list in self._values. The keys and the >mapping of keys to indices are stored in a dynamically generated >subclass of fkdict, so that self._keys and self._key2index are also >accessible from the instance. The dynamically generated subclasses are >cached so that the second time an fkdict with the same keys is created, >the cached class is called. > >Since the keys are determined in fkdict.__init__(), this scheme >requires changing self.__class__ to the dynamically generated subclass. >As much as I appreciate Python's dynamic nature, I am not particularly >comfortable with objects that change their class and the implications >this may have in the future (e.g. how well does this play with >inheritance). Is this a valid use case for type-changing behavior or is >there a better, more "mainstream" OO design pattern for this ? I can >post the relevant code if necessary. I think a better place would be __new__ instead. This is where you can determine the right class to use and construct the new instance. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From tiedon_jano at hotmail.com Tue Jan 16 10:34:10 2007 From: tiedon_jano at hotmail.com (Jussi Salmela) Date: Tue, 16 Jan 2007 15:34:10 GMT Subject: Regular expressions question In-Reply-To: <1168947810.175793.228620@51g2000cwl.googlegroups.com> References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> Message-ID: Victor Polukcht kirjoitti: > I have 2 strings: > > "Global etsi3 *200 ok 30 100% 100% > Outgoing" > and > "Global etsi3 * 4 ok 30 100% 100% > Outgoing" > > The difference is "*200" instead of "* 4". Is there ability to write a > regular expression that will match both of that strings? > If the goal is not to study regular expressions, here's a solution without them. Not so short, but working. lst = [ "Global etsi3 *200 ok 30 100% 100% Outgoing", "Global etsi3 * 4 ok 30 100% 100% Outgoing"] for e in lst: es = e.split() if len(es) == 9: num_val = es[3] else: num_val = es[2][1:] print es[0], num_val, es[-3], es[-2] Cheers, Jussi From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jan 11 16:29:38 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 11 Jan 2007 22:29:38 +0100 Subject: Learning Python book, new edition? References: Message-ID: <50noi2F1gnearU1@mid.individual.net> Demel, Jeff wrote: > Bj?rn replied: >>IIRC, differences to 2.4 are in it, too. > Interesting. The description I read said 2.3. That's good to > know. Whoops, I think it was Python Cookbook that has also remarks about 2.4. Learning Python is only about 2.3 as it seems. Regards, Bj?rn -- BOFH excuse #342: HTTPD Error 4004 : very old Intel cpu - insufficient processing power From duncan.booth at invalid.invalid Tue Jan 16 06:59:35 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jan 2007 11:59:35 GMT Subject: Regular expressions question References: <1168947810.175793.228620@51g2000cwl.googlegroups.com> Message-ID: "Victor Polukcht" wrote: > I have 2 strings: > > "Global etsi3 *200 ok 30 100% 100% > Outgoing" > and > "Global etsi3 * 4 ok 30 100% 100% > Outgoing" > > The difference is "*200" instead of "* 4". Is there ability to write a > regular expression that will match both of that strings? > Yes, ".*" would match both of the strings, but not in a useful way. You'll have to consider which strings you *don't* want to match as well as which ones you do and whether you want to extract any information from the strings or find the ones which match. But first take a step back and look at the problem as a whole. You didn't say what you are trying to do, and often people will jump at regular expressions as the solution when there may be better ways of doing what they want without writing a regular expression. What do you really want to do? From jmike at alum.mit.edu Fri Jan 12 09:49:22 2007 From: jmike at alum.mit.edu (jmike at alum.mit.edu) Date: 12 Jan 2007 06:49:22 -0800 Subject: Command line arguments on Vista Message-ID: <1168613362.406648.304720@11g2000cwr.googlegroups.com> So I write this sript called printargs.py: ------ #!/usr/local/bin/python import sys print 'there are %d args' % len(sys.argv) for arg in sys.argv: print 'arg: %s' % arg ------ and make it executable. On pretty much every platform I can get my hands on, when I run printargs.py booga -a wooga I get this output: there are 4 args arg: printargs.py arg: booga arg: -a arg: wooga But on Windows Vista, when I run that command, I get there are 1 args arg: printargs.py What's up with that? --JMike From Thomas.Ploch at gmx.net Thu Jan 4 22:40:34 2007 From: Thomas.Ploch at gmx.net (Thomas Ploch) Date: Fri, 05 Jan 2007 04:40:34 +0100 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> Message-ID: <459DC8B2.60908@gmx.net> jeremito schrieb: > I am writing a class that is intended to be subclassed. What is the > proper way to indicate that a sub class must override a method? > > Thanks, > Jeremy > What do you mean by 'indicate'? Writing it to the docstring of the class/method? Writing a comment? class Foo: """ When inheriting from Foo, method foo must be overridden. Otherwise SPAM. """ def foo(self): print 'bar' class Bar(Foo): def __init__(self): Foo.__init__(self) # Has to be defined to override the base class's method # when inheriting from class Foo. Otherwise: SPAM def foo(self): print 'foo' I don't know any other way. Thomas From michele.simionato at gmail.com Tue Jan 9 07:31:43 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Jan 2007 04:31:43 -0800 Subject: General Question About Python In-Reply-To: <1168254451.098796.144790@42g2000cwt.googlegroups.com> References: <1168254451.098796.144790@42g2000cwt.googlegroups.com> Message-ID: <1168345903.305552.205330@42g2000cwt.googlegroups.com> Enteng wrote: > To those who program in python, what programs do you do? > Also what community projects are you involved in(OSS probably)? > Will mastering the language land me a job? Well, I few years ago I decided to learn Python to get a job and it worked. Of course, you should think of something to get yourself visibile (i.e. contribute to some OSS project, write articles, partecipate to conferences, etc.) Michele Simionato From gagsl-py at yahoo.com.ar Tue Jan 9 20:47:06 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Jan 2007 22:47:06 -0300 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A6E@eugsrv400.psc.psc net.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A6E@eugsrv400.psc.pscnet.com> Message-ID: <7.0.1.0.0.20070109222253.0395f220@yahoo.com.ar> At Tuesday 9/1/2007 22:03, Carroll, Barry wrote: >The first assumption was correct: the file object is destroyed. The >second assumption is apparently incorrect: the file handle is not >released when the associated object is destroyed. These 'orphaned' >file handles build up and when the OS handle limit is reached, "too >many open files" errors show up. I've tried with 2.3.4 something like this: flist = [] for i in range(5000): fn = 'test%04.4d.tmp' % i print fn f = open(fn,'w') flist.append(f) # f.close() Without the last close(), I get an error on iteration 509 like you; adding the close(), I can create the 5000 file instances without problems. So it seems that Python *does* release the file handle. > > On Python 2.5 you can use the new `with` statement. > > > >Not only that, the file errors don't appear when we run our >program/table combination under 2.5. I can't explain the >difference, unless the work done to implement the 'with' statement >has an impact outside the scope of that feature. In any event, it >does us no good. Other constraints on the test system require us to >stick with Python 2.3, at least for the present. My advise would be (as others have already suggested) to not *assume* anything and put a print statement when you think you close the file. Perhaps that code fragment is never executed! Or perhaps there is *another* place where you open a file and never close it (a logfile perhaps? it doesnt have to be a different file each time). Someone already suggested to use Filemon to trace the file operations; you can also use Process Explorer to inspect the open file handles (both tools available from SysInternals). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From horpner at yahoo.com Tue Jan 23 11:28:48 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Jan 2007 16:28:48 GMT Subject: Best way to document Python code... References: <1169492869.101706.253620@38g2000cwa.googlegroups.com> <1169500149.885333.170320@s34g2000cwa.googlegroups.com> Message-ID: On 2007-01-22, bearophileHUGS at lycos.com wrote: > Boris Ozegovic: >> Does Python has API just like in Java, for example >> http://java.sun.com/j2se/1.5.0/docs/api/allclasses-noframe.html ctrl-f and >> than click on class you are searching for, and finally you get clean list >> of all fields and methods. Where can I find similar in Python, for >> example, if I would like to see which methods list/dictionary has. > > You can do that from the shell, with help(name) or dir(name), > where name can be a class, object, most things. It is OK for a lark, but sadly dir is not suitable enough. You do need to refer to the documentation off-line or you'll miss vital entries. It won't hurt to read effbot.org, either, as I keep finding out. Also check out the interactive help system. If you've got the html versions of the docs installed, it functions somewhat like perldoc. Type help() at the interactive prompt to get started. -- Neil Cerutti Will the last person to leave please see that the perpetual light is extinguished --sign at New England church -- Posted via a free Usenet account from http://www.teranews.com From paul at boddie.org.uk Sun Jan 14 13:20:47 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 14 Jan 2007 10:20:47 -0800 Subject: Threaded for loop References: <1168719342.627408.98870@a75g2000cwd.googlegroups.com> <7xr6ty8ugv.fsf@ruckus.brouhaha.com> <1168750177.856791.85730@s34g2000cwa.googlegroups.com> Message-ID: <1168798847.405344.126410@51g2000cwl.googlegroups.com> skip at pobox.com wrote: > > There is a module in development (processing.py) that provides an API like > the threading module but that uses processes under the covers: > > http://mail.python.org/pipermail/python-dev/2006-October/069297.html > > You might find that an interesting alternative. See the promised parallel processing overview on the python.org Wiki for a selection of different solutions: http://wiki.python.org/moin/ParallelProcessing Paul From steve at holdenweb.com Thu Jan 11 18:13:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Jan 2007 23:13:02 +0000 Subject: globals accros modules In-Reply-To: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> References: <3ad32$45a64fc7$83aef404$32138@news1.tudelft.nl> Message-ID: stef wrote: >> Change a=1 to amodule.a=1 >> If you find yourself doing tricks with the module globals, think about >> redesigning your application. >> > Of course I completely agree with you. > > But ... > if you're moving from MatLab to Python, > and want to show your collegaes, > with how little effort they can reuse all their existing MatLab routines > in Python, > then the global issue is a real pain !! > > You can explain your collegaes, that > - the startindex of arrays changes from 1 to 0 > - slices are upto, instead of including the final border > - indention is th? key > And tell them about all beautiful things in Python, > but tell them that they are going to loose all their globals ??? > Yup. If they don't tell us how to write programs we won't tell them how to cure illness. Sounds like a deal to me ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From basti.wiesner at gmx.net Tue Jan 2 13:14:45 2007 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Tue, 02 Jan 2007 19:14:45 +0100 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: Carsten Haese typed > On Tue, 2007-01-02 at 17:17 +0100, Sebastian 'lunar' Wiesner wrote: >> Ravi Teja typed >> >> > >> > Ivan Voras wrote: >> >> Ramdas wrote: >> >> > Well, >> >> > >> >> > I need to add users from a web interface for a web server, which >> >> > runs only Python. I need to add users, set quotas and in future >> >> > even look at managing ip tables to limit bandwidth. >> >> > >> >> > I know os.system(), but this has to be done through a form entry >> >> > through a web interface. >> >> > >> >> > Anyways thanks, do advise if there more pythonic solutions >> >> >> >> What you're looking for is actually a pretty complex thing. You >> >> *could* in theory manage /etc/passwd (and its "shadow" file) - you >> >> can find crypto primitives like MD5 and DES on the 'net, but note >> >> that you must run your script under the 'root' account in order to >> >> write (and even read!) the passwd database. The same goes for >> >> using os.system and the built-in OS utility. Be aware of security >> >> implications if you're running your web server under the root >> >> account. >> > >> > How about invoking scripts with SUID root set? >> >> Linux seems to ignore SUID bit on scripts: > > I don't think that that has anything to do with Linux or not. The > script is not the actual executable, hence its suid bit is irrelevant. I don't think so. From what I know, the script is passed as executable to the kernel loader, which interprets the shebang and feeds the script through the correct interpreter. So the kernel loader sees the script itself as executable instead of the interpreter binary. I've heard of other Unix systems, which handle this differently (meaning that the SUID bit on scripts has an effect), but I may be wrong. > You'd have to set the suid bit on the python executable, but that > would affect all python scripts, which is probably bad. It _is_ bad! -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From joeyslistings at yahoo.com Sun Jan 7 11:54:57 2007 From: joeyslistings at yahoo.com (joeyslistings at yahoo.com) Date: 7 Jan 2007 08:54:57 -0800 Subject: I want to learn In-Reply-To: References: <1168174097.252001.71130@s80g2000cwa.googlegroups.com> Message-ID: <1168188897.811575.278490@51g2000cwl.googlegroups.com> Thanks for the links guys!! Dive into Python is great and I am subscribing to tutor as well. Thomas Ploch wrote: > joeyslistings at yahoo.com schrieb: > > Hi, > > > > I have been "programming" in the .net environment and ide for a few > > years and I am looking to make the switch over to python. I have > > absolutely no python experience whatsoever. I am looking for a python > > guru who has instant messenger or gtalk or whatever who can meet me > > online in the mornings, give me some direction for the day and then > > answer some questions here and there online throughout the day. > > > So you are looking for a person (no, a guru), that stays by your side > the whole day, gives you answers and helps you learning python. > > This is a ridiculous request. > > If you want to learn python, you should start with visiting > http://www.diveintopython.org/ and read it. If you have previous > programming experience, this is the place to start. > > > Sorry to interrupt the group but since all python gurus appear to be > > happily at work on the next level apps at google nobody responded to > > my craigslist ads. > > You can always ask your questions here on the list, there are enough > people that are willing to help. > > Thomas From nmm1 at cus.cam.ac.uk Tue Jan 16 17:01:02 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 16 Jan 2007 22:01:02 GMT Subject: Class data members in C Message-ID: Hmm. The extensions documentation describes how to add instance members to a class (PyMemberDef), but I want to add a class member. Yes, this is constant for all instances of the class. Any pointers? Regards, Nick Maclaren. From gert.cuykens at gmail.com Sun Jan 21 20:12:01 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Mon, 22 Jan 2007 02:12:01 +0100 Subject: instancemethod In-Reply-To: References: Message-ID: On 1/22/07, Gabriel Genellina wrote: > "Gert Cuykens" escribi? en el mensaje > news:ef60af090701211416n5b2eb7edt2ee6d4555bd49c1a at mail.gmail.com... > > > class Db: > > > > _db=-1 > > _cursor=-1 > > > > @classmethod > > def __init__(self,server,user,password,database): > > self._db=MySQLdb.connect(server , user , password , database) > > self._cursor=self._db.cursor() > > > > @classmethod > > def excecute(self,cmd): > > self._cursor.execute(cmd) > > self._db.commit() > > > > > > if __name__ == '__main__': > > gert=Db('localhost','root','******','gert') > > gert.excecute('select * from person') > > for x in range(0,gert.rowcount): > > print gert.fetchone() > > gert.close() > > Besides your specific question that was already answered, why are you using > classmethods at all? > You are constructing a Db instance and using it as if all were normal > instance methods... Just remove all those @classmethod declarations and use > it in a standard way. > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > i thought @classmethod was the normal method ? From gagsl-py at yahoo.com.ar Wed Jan 17 18:13:24 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 17 Jan 2007 20:13:24 -0300 Subject: Making a simple script standalone In-Reply-To: References: <5d1084-5j7.ln1@whisper.very.softly> Message-ID: <7.0.1.0.0.20070117194341.0337c128@yahoo.com.ar> At Wednesday 17/1/2007 16:05, Rikishi 42 wrote: > >>What I want to do is to compile/bundle/prepare/whatever_term a simple > >>Python script for deployment on a Windows machine. Installing Python > >>itself on that machine, is not an option. Ideally I would like to obtain > >>a single executable file, but a script+runtime is acceptable. > > > > distutils + py2exe > >Tried that, just after asking here. >A bit messy (poor docs) and a very bloated result. Consider that, at a bare minimum, you need to include python25.dll wich is rather large, and transitive module imports can lead to a large library.zip too. Different "bundlers" may be more or less convenient, have more or less documentation, easier or harder to use, but they all make comparable file sizes; no one is so dumb to include all the scripts reachable along the PYTHONPATH, and on the other hand, if it included too few files your script might fail when it can't import a needed module. See http://mail.python.org/pipermail/python-list/2005-August/336851.html for a related issue. If you're going to try different alternatives, posting your findings at the end would be a good thing. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From vinay_sajip at yahoo.co.uk Fri Jan 19 11:40:36 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 19 Jan 2007 08:40:36 -0800 Subject: My first try using logger didn't work. Why? In-Reply-To: <1169221734.071338.107190@11g2000cwr.googlegroups.com> References: <1169221734.071338.107190@11g2000cwr.googlegroups.com> Message-ID: <1169224835.820468.316040@v45g2000cwv.googlegroups.com> CedricCicada at gmail.com wrote: > Greetings! > > I want to write messages into the Windows event log. I found > sevicemanager, but the source is always "Python Service", and I'd like > to be a bit more descriptive. Poking around on the Internet revealed > the existence of the logging module. It seems to have easily > understood methods with the power I need. So I tried it. Here's my > attempt: > > logger = logging.getLogger("TahChung Part 1") > logger.setLevel(logging.INFO) > eventHandler = logging.NTEventLogHandler() > eventHandler.setlevel(logging.INFO) > formatter = logging.Formatter("%(message)s") > eventHandler.setFormatter(formatter) > > logger.addHandler(eventHandler) > logger.error("This comes from the logger object.") > > I get no error messages from this, but I also don't get anything in my > event log. What am I doing wrong? > > By the way, my source of instructions for how to do this was: > http://www.onlamp.com/pub/a/python/2005/06/02/logging.html > > Rob Richardson > RAD-CON, Inc. Well Rob, Your first try didn't work because (based on your posted snippet) it contained some errors. The OnLAMP article was nice, but it's always best to go the the actual documentation: http://docs.python.org/lib/module-logging.html Where you will see that NTEventLogHandler (described on page http://docs.python.org/lib/node418.html) requires an initialiser argument. Also, "setlevel" is misspelt - it should be "setLevel". The following slightly modified version of your script puts an entry in the NT Event Log on my machine: import logging, logging.handlers logger = logging.getLogger("TahChung Part 1") logger.setLevel(logging.INFO) eventHandler = logging.handlers.NTEventLogHandler("TahChung") eventHandler.setLevel(logging.INFO) formatter = logging.Formatter("%(message)s") eventHandler.setFormatter(formatter) logger.addHandler(eventHandler) logger.error("This comes from the logger object.") Best regards, Vinay Sajip From Barry.Carroll at psc.com Tue Jan 9 20:03:18 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 9 Jan 2007 17:03:18 -0800 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A6E@eugsrv400.psc.pscnet.com> Hi, Gabriel, > -----Original Message----- > From: Gabriel Genellina [mailto:gagsl-py at yahoo.com.ar] > Sent: Tuesday, January 09, 2007 4:06 PM > To: python-list at python.org > Subject: RE: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final > report) > > At Tuesday 9/1/2007 20:31, Carroll, Barry wrote: > > >I've spent about a day investigating our "too many open files" error. I > >found the following: > > > > 1. Windows XP allows a Python 2.5 script to open 509 concurrent > > files. > > And do you actually need so many open files simultaneously? No. In fact, that was the original point of my post. We expected that the maximum number of file objects (open and otherwise) would never be more than five or six. We believed (apparently incorrectly) that destroying the table parser object would destroy its associated file object and close the referenced file. Here is the code that does this: ########## def unloadtable(self, log=True): """Unload current table and pop prior processor from call stack. """ # SNIP # force clean up for unloaded table self.processor = None gc.collect() # pop prior processor from stack self.processor = self.pstack.pop() # SNIP ########## The first assumption was correct: the file object is destroyed. The second assumption is apparently incorrect: the file handle is not released when the associated object is destroyed. These 'orphaned' file handles build up and when the OS handle limit is reached, "too many open files" errors show up. > Try to close them explicitly when you finish working on them - do > not rely on GC for closing files. This has *always* been the > recomended practice (except maybe, inside a short script that > finishes quickly). This is what we have done. The unloadtable function now looks like this: ########## def unloadtable(self, log=True): """Unload current table and pop prior processor from call stack. """ # SNIP # force clean up for unloaded table self.processor.source.close() self.processor = None gc.collect() # pop prior processor from stack self.processor = self.pstack.pop() # SNIP ########## > On Python 2.5 you can use the new `with` statement. > Not only that, the file errors don't appear when we run our program/table combination under 2.5. I can't explain the difference, unless the work done to implement the 'with' statement has an impact outside the scope of that feature. In any event, it does us no good. Other constraints on the test system require us to stick with Python 2.3, at least for the present. > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas > Thanks for your interest. Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From exarkun at divmod.com Wed Jan 31 17:20:16 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 31 Jan 2007 17:20:16 -0500 Subject: Any python scripts to do parallel downloading? In-Reply-To: <45C10FA3.7030208@mvista.com> Message-ID: <20070131222016.25807.1107543360.divmod.quotient.5093@ohm> On Wed, 31 Jan 2007 13:52:35 -0800, "Carl J. Van Arsdall" wrote: >Jean-Paul Calderone wrote: >> On 31 Jan 2007 12:24:21 -0800, Carl Banks wrote: >> >>> Michele Simionato wrote: >>> >>>> On Jan 31, 5:23 pm, "Frank Potter" wrote: >>>> >>>>> I want to find a multithreaded downloading lib in python, >>>>> can someone recommend one for me, please? >>>>> Thanks~ >>>>> >>>> Why do you want to use threads for that? Twisted is the >>>> obvious solution for your problem, >>>> >>> Overkill? Just to download a few web pages? You've got to be >>> kidding. >>> >> >> Better "overkill" (whatever that is) than wasting time re-implementing >> the same boring thing over and over for no reason. >> > >How is that a waste of time? I wrote the script to do it in 10 lines. >What is a waste of time is learning a whole new technology/framework to >do a simple task that can be scripted in 4 minutes. > You're right. Learning new things is bad. My mistake. Jean-Paul From robert.kern at gmail.com Tue Jan 23 14:07:47 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Jan 2007 13:07:47 -0600 Subject: best package for a physical simulation? In-Reply-To: <60915.195.220.102.78.1169558458.squirrel@mailgate.phys.ens.fr> References: <60915.195.220.102.78.1169558458.squirrel@mailgate.phys.ens.fr> Message-ID: sittner at lkb.ens.fr wrote: > Hello everyone, > i would like to use python to perform some simulation involving collisions > of colloidal particles. > which is the best package/engine to do that in python? What kind of numerical methods does such simulation require? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From kleiner at hora-obscura.de Thu Jan 18 05:10:08 2007 From: kleiner at hora-obscura.de (Stefan Palme) Date: Thu, 18 Jan 2007 11:10:08 +0100 Subject: DOTALL not working as expected Message-ID: Hi all, using the "re" module of Python (2.3 and 2.4), I tried the following: import re print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL) I wanted to replace Xab cdY by a single "Z", but the "." in the pattern does not match the included "\n". When using the pattern "X(.|\n)*?Y" (explicity including "\n" in the set of "any character") I get the wanted result. My fault or a bug in the module? Thanks -stefan- From miki.tebeka at gmail.com Thu Jan 25 20:44:25 2007 From: miki.tebeka at gmail.com (Miki) Date: 25 Jan 2007 17:44:25 -0800 Subject: stop script w/o exiting interpreter In-Reply-To: References: Message-ID: <1169775865.519601.121290@h3g2000cwc.googlegroups.com> Hello Alan, > I'm fairly new to Python and I've lately been running a script at > the interpreter while working on it. Sometimes I only want to > run the first quarter or half etc. What is the "good" way to do this? If you want to exit from the program then "raise SystemExit" is what you want. If you want to enter the debugger, you can do: from pdb import set_trace ... set_trace() # Stop and execute debugger here. ... HTH, -- Miki http://pythonwise.blogspot.com From arkanes at gmail.com Wed Jan 24 15:05:31 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 14:05:31 -0600 Subject: Regex for URL extracting In-Reply-To: <1169665668.999341.183480@a75g2000cwd.googlegroups.com> References: <1169655624.981833.29730@j27g2000cwj.googlegroups.com> <1169665668.999341.183480@a75g2000cwd.googlegroups.com> Message-ID: <4866bea60701241205w4f03db4cka209f3d632150b98@mail.gmail.com> On 24 Jan 2007 11:07:49 -0800, Paul McGuire wrote: > On Jan 24, 10:20 am, "Johny" wrote: > > Does anyone know about a good regular expression for URL extracting? > > > > J. > Google turns this up: > > http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx > > But I've seen other re's for this problem that are hundreds of > characters long. > > -- Paul > > -- > http://mail.python.org/mailman/listinfo/python-list > These are the regexps that gnome-terminal uses for it's URL auto-recognition, and I have shamelessly stolen them for use in one of my own apps: urlfinders = [ re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*[^]'\\.}>\\),\\\"]"), re.compile("([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|(((news|telnet|nttp|file|http|ftp|https)://)|(www|ftp)[-A-Za-z0-9]*\\.)[-A-Za-z0-9\\.]+)(:[0-9]*)?"), re.compile("(~/|/|\\./)([-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]|\\\\ )+"), re.compile("'\\<((mailto:)|)[-A-Za-z0-9\\.]+@[-A-Za-z0-9\\.]+"), ] From bearophileHUGS at lycos.com Tue Jan 2 21:28:23 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Jan 2007 18:28:23 -0800 Subject: Writing more efficient code In-Reply-To: <459b03e5$0$8725$ed2619ec@ptn-nntp-reader02.plus.net> References: <459959ea$0$8719$ed2619ec@ptn-nntp-reader02.plus.net> <1167687229.430930.197720@v33g2000cwv.googlegroups.com> <459989ec$0$8759$ed2619ec@ptn-nntp-reader02.plus.net> <1167699678.310643.140480@n51g2000cwc.googlegroups.com> <459b03e5$0$8725$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1167791303.898576.47680@42g2000cwt.googlegroups.com> Jon Harrop: > I think this sort of functionality would be a welcome addition to Python. I don't know. > Perhaps it can be written in Python? Pyparsing and beautifulsoup show that practically useful parsing modules can be done using Python alone too. Set module of Python 2.3, translated to C in Python 2.4 and improved in Python 2.5 shows that sometimes Python is fit to create prototypes that can be debugged, and whose API can be improved, and they can later translated to a faster language. But the decimal module shows that sometimes such translation can become a bit difficult. The re module shows that external modules too can be good enough compared of Perl/Ruby built-in regex syntax. Beside Python, various much faster languages may be used, like D, Pyrex, C, or your loved OCaml. Or theoretically even ShedSkin. I think D may be fit, the "Pyd" Python <-> D bridge is quite good, and it's improving. And D is reaching version 1.0. OCaml maybe can be used to produce Python compiled modules, so it can be a possibility too, but then very few people are able to maintain it, so maybe it's better to use a more common language (even D is more common, because its syntax is easy to grasp by C++ programmers). > What is the easiest way to add such functionality to Python? I think implementation language isn't the main problem. I think the definition of the purpose and API are more difficult. Mathematica allows you to define rules that let the system chose the right function (among some with the same name) according to the input pattern or the kind of input. Guido has discussed some about something similar, the multimethods. There are some ways and tricks to add such capabilities to Python, but I don't think they are fast and reliable enough for real programs. Maybe Python 3.0 will change this some. If you want just to create something like a regular engine that works on lists, that contains matching rules, rewriting rules and calls to many user-defined functions, then I think you can do it with Python (with Psyco if you want) in few lines (a really basic RE on lists can be defined in about 20 lines, maybe a good system may can be built with 2000-10000 lines), but I don't know how much useful it can be, maybe it can find some purpose (and maybe someone has already written such module). > I think that is an excellent idea. Who will pay me? ;-) I don't know, probably no one. Most people don't even know how to use such pattern matching programming paradigm. For Python it may become just an experiment. Bye, bearophile From skip at pobox.com Sat Jan 13 19:58:45 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Jan 2007 18:58:45 -0600 Subject: Newbie - converting csv files to arrays in NumPy - Matlab vs. Numpy comparison In-Reply-To: <1168735174.140171.74930@v45g2000cwv.googlegroups.com> References: <1168373279.943232.228160@o58g2000hsb.googlegroups.com> <1168458486.538863.316130@k58g2000hse.googlegroups.com> <1168715634.695961.14710@l53g2000cwa.googlegroups.com> <1168728465.178605.218850@q2g2000cwa.googlegroups.com> <1168735174.140171.74930@v45g2000cwv.googlegroups.com> Message-ID: <17833.32837.216986.1686@montanaro.dyndns.org> oyekomova> def read_test(): oyekomova> start = time.clock() oyekomova> reader = csv.reader( file('data.txt') ) oyekomova> data = [ map(float, row) for row in reader ] oyekomova> data = array(data, dtype = float) oyekomova> print 'Data size', len(data) oyekomova> print 'Elapsed', time.clock() - start You have the entire file in memory as well as the entire array. Try operating line-by-line. #!/usr/bin/env python import array import time import random import csv def make_data(nrows=1000000, cols=6): counter = range(cols) writer = csv.writer(open('data.txt', 'wt')) for row in xrange(nrows): writer.writerow([random.random() for x in counter]) def read_test(): reader = csv.reader( file('data.txt') ) data = array.array('f') for row in reader: data.extend(map(float, row)) print 'Data size', len(data) start = time.clock() make_data() print "generate data:", (time.clock()-start) start = time.clock() read_test() print "read data:", (time.clock()-start) Skip From horpner at yahoo.com Mon Jan 8 09:53:40 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 8 Jan 2007 15:53:40 +0100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xhcv2195o.fsf@ruckus.brouhaha.com> Message-ID: On 2007-01-08, Paul Rubin wrote: > Dennis Lee Bieber writes: >> I'd be quite concerned about the design environment rather than the >> immediate code... Probably need something ugly like... >> >> from mod1 import B as B1 >> from mod2 import B as B2 >> class A(B1, B2): >> .... > > Interesting. I just tried that. mod1.py contains: > > class B: > def foo(self): self.__x = 'mod1' > > mod2.py contains: > > class B: > def bar(self): self.__x = 'mod2' > > And the test is: > > from mod1 import B as B1 > from mod2 import B as B2 > > class A(B1, B2): pass > > a = A() > a.foo() > print a._B__x > a.bar() > print a._B__x > > Sure enough, mod2 messes up mod1's private variable. When faced with this situation, is there any way to proceed besides using composition instead? -- Neil Cerutti We've got to pause and ask ourselves: How much clean air do we really need? --Lee Iacocca From steve at REMOVE.THIS.cybersource.com.au Tue Jan 9 10:26:50 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 10 Jan 2007 02:26:50 +1100 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7x7ivz88af.fsf@ruckus.brouhaha.com> <7xmz4v11jq.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 09 Jan 2007 10:27:56 +0200, Hendrik van Rooyen wrote: > "Steven D'Aprano" wrote: > > >> On Mon, 08 Jan 2007 13:11:14 +0200, Hendrik van Rooyen wrote: >> >> > When you hear a programmer use the word "probability" - >> > then its time to fire him, as in programming even the lowest >> > probability is a certainty when you are doing millions of >> > things a second. >> >> That is total and utter nonsense and displays the most appalling >> misunderstanding of probability, not to mention a shocking lack of common >> sense. > > Really? > > Strong words. > > If you don't understand you need merely ask, so let me elucidate: > > If there is some small chance of something occurring at run time that can > cause code to fail - a "low probability" in all the accepted senses of the > word - and a programmer declaims - "There is such a low probability of > that occurring and its so difficult to cater for that I won't bother" > - then am I supposed to congratulate him on his wisdom and outstanding > common sense? > > Hardly. - If anything can go wrong, it will. - to paraphrase Murphy's law. > > To illustrate: > If there is one place in any piece of code that is critical and not protected, > even if its in a relatively rarely called routine, then because of the high > speed of operations, and the fact that time is essentially infinite, Time is essentially infinite? Do you really expect your code will still be in use fifty years from now, let alone a billion years? I know flowcharts have fallen out of favour in IT, and rightly so -- they don't model modern programming techniques very well, simply because modern programming techniques would lead to a chart far too big to be practical. But for the sake of the exercise, imagine a simplified flowchart of some program, one with a mere five components, such that one could take any of the following paths through the program: START -> A -> B -> C -> D -> E START -> A -> C -> B -> D -> E START -> A -> C -> D -> B -> E ... START -> E -> D -> C -> B -> A There are 5! (five factorial) = 120 possible paths through the program. Now imagine one where there are just fifty components, still quite a small program, giving 50! = 3e64 possible paths. Now suppose that there is a bug that results from following just one of those paths. That would match your description of "lowest probability" -- any lower and it would be zero. If all of the paths are equally likely to be taken, and the program takes a billion different paths each millisecond, on average it would take about 1.5e55 milliseconds to hit the bug -- or about 5e44 YEARS of continual usage. If every person on Earth did nothing but run this program 24/7, it would still take on average almost sixty million billion billion billion years to discover the bug. But of course in reality some paths are more likely than others. If the bug happens to exist in a path that is executed often, or if it exists in many paths, then the bug will be found quickly. On the other hand, if the bug is in a path that is rarely executed, your buggy program may be more reliable than the hardware you run it on. (Cynics may say that isn't hard.) You're project manager for the development team. Your lead developer tells you that he knows this bug exists (never mind how, he's very clever) and that the probability of reaching that bug in use is about 3e-64. If it were easy to fix, the developer wouldn't even have mentioned it. This is a really hard bug to fix, it's going to require some major changes to the program, maybe even a complete re-think of the program. Removing this bug could even introduce dozens, hundreds of new bugs. So okay Mister Project Manager. What do you do? Do you sack the developer, like you said? How many dozens or hundreds of man-hours are you prepared to put into this? If the money is coming out of your pocket, how much are you willing to spend to fix this bug? [snip] > How is this a misunderstanding of probability? - probability applies to > any one trial, so in a series of trials, when the number of trials is > large enough - in the > order of the inverse of the probability, then ones expectation must be > that the rare occurrence should occur... "Even the lowest probability is a certainty" is mathematically nonsense: it just isn't true -- no matter how many iterations, the probability is always a little less than one. And you paper over a hole in your argument with "when the number of trials is large enough" -- if the probability is small enough, "large enough" could be unimaginably huge indeed. Or, to put it another way, while anything with a non-zero probability _might_ happen (you might drop a can of soft drink on your computer, shorting it out and _just by chance_ causing it to fire off a perfectly formatted email containing a poem about penguins) we are justified in writing off small enough probabilities as negligible. It's not that they can't happen, but the chances of doing so are so small that we can rightly expect to never see them happen. You might like to read up on Borel's "Law" (not really a law at all, really just a heuristic for judging when probabilities are negligible). Avoid the nonsense written about Borel and his guideline by Young Earth Creationists, they have given him an undeserved bad name. http://www.talkorigins.org/faqs/abioprob/borelfaq.html > There is a very low probability that any one gas molecule will collide > with any other one in a container Not so. There is a very low probability that one gas molecule will collide with a _specific_ other molecule -- but the probability of colliding with _any_ other molecule is very high. > - and "Surprise! Surprise! " there > is nevertheless something like the mean free path... Yes. And that mean free path increases without limit as the volume of the gas increases. Take your molecule into the space between stars, and the mean free path might be dozens of lightyears -- even though there is actually more gas in total than in the entire Earth. > Now how does all this show a shocking lack of common sense? You pay no attention to the economics of programming. Programming doesn't come for free. It is always a trade-off for the best result with the least effort. Any time people start making absolute claims about fixing every possible bug, no matter how obscure or unlikely or how much work it will take, I know that they aren't paying for the work to be done. -- Steven. From grahn+nntp at snipabacken.dyndns.org Sun Jan 7 10:00:21 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 7 Jan 2007 15:00:21 GMT Subject: program deployment References: <1167998448.978001.3720@38g2000cwa.googlegroups.com> <1168002070.704739.76470@q40g2000cwq.googlegroups.com> <1168004752.091662.178060@s80g2000cwa.googlegroups.com> <12psqtppgi5cme6@corp.supernews.com> Message-ID: On Fri, 05 Jan 2007 15:16:09 -0000, Grant Edwards wrote: > On 2007-01-05, king kikapu wrote: > >>> Python code is normally deployed as straight source code. >> >> But isn't this a problem of its own? I mean, many people do not feel >> good if the know that their source code is lying around on other >> machines... > > Are they embarassed by their code? For companies, that may be one reason. For many companies, rightly so ... /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From garyjefferson123 at yahoo.com Sun Jan 21 22:49:23 2007 From: garyjefferson123 at yahoo.com (Gary Jefferson) Date: 21 Jan 2007 19:49:23 -0800 Subject: selective logger disable/enable In-Reply-To: <1169395276.181654.160810@a75g2000cwd.googlegroups.com> References: <1169190498.593059.238150@q2g2000cwa.googlegroups.com> <1169204564.348768.186900@38g2000cwa.googlegroups.com> <1169349399.938121.238430@38g2000cwa.googlegroups.com> <1169395276.181654.160810@a75g2000cwd.googlegroups.com> Message-ID: <1169437763.213781.163660@38g2000cwa.googlegroups.com> Vinay Sajip wrote: > > I don't know enough about your target environment and application to > necessarily give you the best advice, but I'll make some general > comments which I hope are useful. You seem to be thinking that loggers > are binary - i.e. you turn them on or off. But they can be controlled > more finely than that; you should be able to get the effect that you > want by using the different logging levels available judiciously, as > well as using the fact that loggers inhabit a named hierarchy. Note > that loggers, by default, inherit the level of the first ancestor > logger which has an explicitly set level (by ancestor, I mean in the > name hierarchy). The root logger's default level is WARNING, so by > default all loggers will work at this level. [N.B. You can also set > levels for individual handlers, e.g. to ensure that only CRITICAL > conditions are emailed to a specified email address using SMTPHandler, > or that ERROR conditions and above are written to file but not to > console.] > > So, for your networking scenario, let's suppose you do the following: > Have all network loggers live in the hierarchy namespace below > "network" (e.g. "network", "network.tcp", "network.http" etc.). By > default, all of these will only log events of severity WARNING and > above. Also, suppose you log events in your application code, which are > sometimes but not always of interest, at level DEBUG or level INFO. > Then, these events will never show up in the logging output, since they > are below WARNING in severity. Subsequently, if you want to turn on > logging verbosity for the network code only, you can arrange, via a > command-line switch or environment variable or configuration file, to > do > > logging.getLogger("network").setLevel(logging.DEBUG) > > whereupon you will start seeing events from the networking code at > severity DEBUG and INFO. This will affect all loggers in the "network" > hierarchy whose levels you have not explicitly set (so that they will > get the effective level of the first ancestor which has a level > explicitly set - the logger named "network"). > > If all you are interested in is turning on verbosity based on different > event severities (levels), you should not need to use or set Filters. > Filters are for use only when levels don't meet your use case > requirements. > > Best regards, > > Vinay Sajip Vinay, okay, I think what you described will work out for me -- thank you very much for the explanation. I am still a bit confused about Filters, though. It seems they are a bit of an anomoly in the hierarchical view of loggers that the API supports elsewhere, i.e., filters don't seem to inherit... Or am I missing something again? Here's a quick example: import logging log1 = logging.getLogger("top") log2 = logging.getLogger("top.network") log3 = logging.getLogger("top.network.tcp") log4 = logging.getLogger("top.network.http") log5 = logging.getLogger("top.config") log6 = logging.getLogger("top.config.file") logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') filter = logging.Filter("top.network") log1.addFilter(filter) # only affects log1, do this for each of log2-7 too? log1.debug("I'm top") log2.debug("I'm top.network") log3.debug("I'm top.network.tcp") log4.debug("I'm top.network.http") log5.debug("I'm top.config") log6.debug("I'm top.config.file") This is only for the binary case (and I think if I ignore the binary case and filters altogether as you suggested), but it really would be nice to be able to squelch /all/ output from loggers that belong to certain parts of the namespace by using a filter as above (which I can't get to work). Perhaps if I set up a basicConfig with a loglevel of nothing, I can get this to approximate squelching of everything but that which I explicitly setLevel (which does inherit properly). In other words, the addFilter/removeFilter part of the API seems rather impotent if it can't be inherited in the logging namespaces. In fact, I can't really figure out a use case where I could possibly want to use it without it inheriting. Obviously I'm missing something. I'm sure I've consumed more attention that I deserve already in this thread, but, do you have any pointers which can enlighten me as to how to effectively use addFilter/removeFilter? many thanks, Gary From S.Mientki-nospam at mailbox.kun.nl Sat Jan 6 15:24:02 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 06 Jan 2007 21:24:02 +0100 Subject: still struggling, howto use a list-element as a name ? In-Reply-To: References: Message-ID: <182cf$45a00556$d443bb3a$17174@news.speedlinq.nl> >> class Power_Supply(device): >> pinlist = { >> 0: ('GND', _DIG_OUT, _par2), >> 1: ('VCC', _DIG_OUT, _par33) >> } > > I may be confused about what you're after, but wouldn't something > like this work? (I don't know what a _par2 object is; I've named > it something here.) _par2, is just (a reference to) a constant > > class Power_Supply(device): > def __init__(self): > self.pin = { > 0:dict(Name='GND',Value=_DIG_OUT,something=_par2), > 1:dict(Name='VCC',Value=_DIG_OUT,something=_par33), > } Why so complex, I need 10 or more parameters (or empty), and then this becomes completely unreadable. As this is part of the "user interface", (I want that completely unknown with Python people, write these lines), I think my "pinlist" is much easier. > for k in self.pin.keys(): > self.__dict__[self.pin[k]['Name']] = self.pin[k] thanks "rzed" ?, that is exactly what I was looking for: self.__dict__[self.pinlist[k][0]] = self.pin[k] cheers, Stef From tomerfiliba at gmail.com Tue Jan 23 06:45:31 2007 From: tomerfiliba at gmail.com (gangesmaster) Date: 23 Jan 2007 03:45:31 -0800 Subject: free variables /cell objects question Message-ID: <1169552731.189786.274930@s48g2000cws.googlegroups.com> why does CPython require to wrap the free variables if closure functions by a cell objects? why can't it just pass the object itself? >>> def f(x): ... def g(): ... return x+2 ... return g ... >>> g5 = f(5) >>> dis(g5) 3 0 LOAD_DEREF 0 (x) 3 LOAD_CONST 1 (2) 6 BINARY_ADD 7 RETURN_VALUE >>> dis(f) 2 0 LOAD_CLOSURE 0 (x) 3 BUILD_TUPLE 1 6 LOAD_CONST 1 (>> i don't see why dereferencing is needed. why not just pass the object itself to the MAKE_CLOSURE? i.e. LOAD_FAST 0 (x) LOAD_CONST 1 (the code object) MAKE_CLOSURE 0 what problem does the cell object solve? -tomer From tim.one at comcast.net Tue Jan 9 13:03:45 2007 From: tim.one at comcast.net (Tim Peters) Date: Tue, 09 Jan 2007 12:03:45 -0600 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: [Rory Campbell-Lange] >>> Is using the decimal module the best way around this? (I'm >>> expecting the first sum to match the second). It seem >>> anachronistic that decimal takes strings as input, though. [Nick Maclaren] >> As Dan Bishop says, probably not. The introduction to the decimal >> module makes exaggerated claims of accuracy, amounting to propaganda. >> It is numerically no better than binary, and has some advantages >> and some disadvantages. [Carsten Haese] > Please elaborate. Which exaggerated claims are made, Well, just about any technical statement can be misleading if not qualified to such an extent that the only people who can still understand it knew it to begin with <0.8 wink>. The most dubious statement here to my eyes is the intro's "exactness carries over into arithmetic". It takes a world of additional words to explain exactly what it is about the example given (0.1 + 0.1 + 0.1 - 0.3 = 0 exactly in decimal fp, but not in binary fp) that does, and does not, generalize. Roughly, it does generalize to one important real-life use-case: adding and subtracting any number of decimal quantities delivers the exact decimal result, /provided/ that precision is set high enough that no rounding occurs. > and how is decimal no better than binary? Basically, they both lose info when rounding does occur. For example, >>> import decimal >>> 1 / decimal.Decimal(3) Decimal("0.3333333333333333333333333333") >>> _ * 3 Decimal("0.9999999999999999999999999999") That is, (1/3)*3 != 1 in decimal. The reason why is obvious "by eyeball", but only because you have a lifetime of experience working in base 10. A bit ironically, the rounding in binary just happens to be such that (1/3)/3 does equal 1: >>> 1./3 0.33333333333333331 >>> _ * 3 1.0 It's not just * and /. The real thing at work in the 0.1 + 0.1 + 0.1 - 0.3 example is representation error, not sloppy +/-: 0.1 and 0.3 can't be /represented/ exactly as binary floats to begin with. Much the same can happen if you instead you use inputs exactly representable in base 2 but not in base 10 (and while there are none such if precision is infinite, precision isn't infinite): >>> x = decimal.Decimal(1) / 2**90 >>> print x 8.077935669463160887416100508E-28 >>> print x + x + x - 3*x # not exactly 0 1E-54 The same in binary f.p. is exact, because 1./2**90 is exactly representable in binary fp: >>> x = 1. / 2**90 >>> print x # this displays an inexact decimal approx. to 1./2**90 8.07793566946e-028 >>> print x + x + x - 3*x # but the binary arithmetic is exact 0.0 If you boost decimal's precision high enough, then this specific example is also exact using decimal; but with the default precision of 28, 1./2**90 can't be represented exactly in decimal to begin with; e.g., >>> decimal.Decimal(1) / 2**90 * 2**90 Decimal("0.9999999999999999999999999999") All forms of fp are subject to representation and rounding errors. The biggest practical difference here is that the `decimal` module is not subject to representation error for "natural" decimal quantities, provided precision is set high enough to retain all the input digits. That's worth something to many apps, and is the whole ball of wax for some apps -- but leaves a world of possible "surprises" nevertheless. From tubby at bandaheart.com Thu Jan 25 17:09:42 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 25 Jan 2007 17:09:42 -0500 Subject: pdf to text In-Reply-To: <86714$45b9254c$54d1d767$3741@news.chello.no> References: <86714$45b9254c$54d1d767$3741@news.chello.no> Message-ID: David Boddie wrote: > The pdftotext tool may do what you want: > > http://www.foolabs.com/xpdf/download.html > > Let us know how you get on with it. > > David Perhaps I'm just using pdftotext wrong? Here's how I was using it: f = filename try: sout = os.popen('pdftotext "%s" - ' %f) data = sout.read().strip() print data sout.close() except Exception, e: print e From __peter__ at web.de Sun Jan 28 04:15:39 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 28 Jan 2007 10:15:39 +0100 Subject: set update in 2.5 References: <45bc0c0c.0@entanet> Message-ID: Duncan Smith wrote: > In moving from 2.4 to 2.5 I find that some of my unit tests are now > failing. I've worked out that the problem relates to the set update > method. In 2.4 I could update a set with an iterable type derived from > dict as the argument. I now find that the set is updated with the hash > values of the items in my iterable, rather than the items themselves. > Converting to a list first gets round the problem. > > My iterable type has the same API as 'set' but requires items to have > hashable 'uid' attributes, so they can also be looked up by uid. I hope > this, and the fact that this worked fine in 2.4 will be enough to track > down the issue without me having to paste reams of code (other than the > following, pasted from IDLE). Any ideas? Cheers. > > Duncan > > >>>> from graphItems import Node >>>> from keyed_sets import KeyedSet >>>> n = Node(1) >>>> n.uid > 1 >>>> k = KeyedSet([n]) >>>> k > KeyedSet([1]) >>>> type(iter(k).next()) > >>>> type(k[1]) > >>>> s = set() >>>> s.update(list(k)) >>>> type(iter(s).next()) > >>>> s = set() >>>> s.update(k) >>>> type(iter(s).next()) > >>>> s = set() >>>> s.add(n) >>>> type(iter(s).next()) > >>>> hash(n) > 1 >>>> Is your KeyedSet derived from dict? $ python2.5 [snip] >>> class D(dict): ... def __iter__(self): return self.itervalues() ... >>> d = D(a=1, b=2) >>> set(d) set(['a', 'b']) >>> $ python2.4 [snip] >>> class D(dict): ... def __iter__(self): return self.itervalues() ... >>> d = D(a=1, b=2) >>> set(d) set([1, 2]) I think you should file a bug report. The fix is probably --- setobject.c 2006-09-08 08:02:26.000000000 +0200 +++ setobject_new.c 2007-01-28 10:02:24.071688248 +0100 @@ -854,7 +854,7 @@ if (PyAnySet_Check(other)) return set_merge(so, other); - if (PyDict_Check(other)) { + if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; while (PyDict_Next(other, &pos, &key, &value)) { Peter From __peter__ at web.de Tue Jan 23 07:02:49 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 Jan 2007 13:02:49 +0100 Subject: free variables /cell objects question References: <1169552731.189786.274930@s48g2000cws.googlegroups.com> Message-ID: gangesmaster wrote: > why does CPython require to wrap the free variables if > closure functions by a cell objects? > why can't it just pass the object itself? > >>>> def f(x): > ... def g(): > ... return x+2 > ... return g > ... >>>> g5 = f(5) >>>> dis(g5) > 3 0 LOAD_DEREF 0 (x) > 3 LOAD_CONST 1 (2) > 6 BINARY_ADD > 7 RETURN_VALUE >>>> dis(f) > 2 0 LOAD_CLOSURE 0 (x) > 3 BUILD_TUPLE 1 > 6 LOAD_CONST 1 ( 9 MAKE_CLOSURE 0 > 12 STORE_FAST 1 (g) > > 4 15 LOAD_FAST 1 (g) > 18 RETURN_VALUE >>>> > > i don't see why dereferencing is needed. why not just pass > the object itself to the MAKE_CLOSURE? i.e. > > LOAD_FAST 0 (x) > LOAD_CONST 1 (the code object) > MAKE_CLOSURE 0 > > what problem does the cell object solve? If I understand you correctly: def f(x): def g(): return x + 2 x = 42 return g assert f(0)() == 44 Peter From ptmcg at austin.rr._bogus_.com Fri Jan 5 17:27:49 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 5 Jan 2007 16:27:49 -0600 Subject: Dividing integers...Convert to float first? References: <1168017342.255981.134400@11g2000cwr.googlegroups.com><459E8B5C.6020804@gmx.net><12pt3f3kc1jmcf8@corp.supernews.com> Message-ID: <459ed0e7$0$16932$4c368faf@roadrunner.com> "Simon Brunning" wrote in message news:mailman.2339.1168019925.32031.python-list at python.org... > On 1/5/07, Grant Edwards wrote: >> >>> from __future__ import LotteryNumbers >> File "", line 1 >> SyntaxError: future feature LotteryNumbers is not defined >> >> Damn. >> >> I guess it's back to work then. > > Remember the PEP 8 module name standards. > >>>> from __future__ import lottery_numbers > [1, 16, 19, 20, 21, 39] > > -- > Cheers, > Simon B > simon at brunningonline.net The computer printed it out, it must be correct! We can all become millionaires! (Now if we only knew which drawing in the future, and from which lottery...) -- Paul From michael at mustun.ch Wed Jan 3 11:00:07 2007 From: michael at mustun.ch (Michael) Date: Wed, 03 Jan 2007 17:00:07 +0100 Subject: code optimization (calc PI) In-Reply-To: References: <5020j6F1du59cU1@mid.uni-berlin.de> Message-ID: <%pQmh.103$9v1.124@nntpserver.swip.net> Ah, no. It was a HASH (assoziative Array or somethings like that). mm wrote: > > I konw, that for example while-loops in Perl are very slow. Maybe this > is also known in Pyhton. Then, I can translate the while-loops in to > for-loops, for example. > More general, maybe there is a speed optimazation docu out there. > From toto at titi.de Fri Jan 5 16:23:34 2007 From: toto at titi.de (laurent rahuel) Date: Fri, 05 Jan 2007 22:23:34 +0100 Subject: importing / loading a module / class dynamically In-Reply-To: References: Message-ID: <459ec2cc$0$21147$7a628cd7@news.club-internet.fr> Hi, Using exec or eval ISN'T what should be done ever. When you have troubles importing you should : - Add some repository to your sys.path and/or - Use the buildin import method and/or - Use Mr Eby's Importing module (http://python.org/pypi/Importing) Regards, Laurent hg a ?crit : > Hi, > > I have the following problem. > > I find in a directory hierarchy some files following a certain sets of > rules: > > .../.../../plugin/name1/name1.py > .... > .../.../../plugin/namen/namen.py > > each file will in turn have a class with the same name as the filename > (minus .py) > > > I fetch those names in a list of string and want to import the files / > instantiate the classes. > > > I block at the beginning and tried this (test.py is a real file) >>>> s = 'test.py' >>>> eval ('import ' + s) > > and get > > Traceback (most recent call last): > File "", line 1, in -toplevel- > eval ('import ' + s) > File "", line 1 > import test.py > > Any clue ? > > Thanks > > hg > From risomt at gmail.com Wed Jan 31 02:32:27 2007 From: risomt at gmail.com (risomt at gmail.com) Date: 30 Jan 2007 23:32:27 -0800 Subject: PY Zip In-Reply-To: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> References: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> Message-ID: <1170228747.334418.136290@v45g2000cwv.googlegroups.com> On Jan 31, 12:18 am, "GISDude" wrote: > Hi all. > > I am trying to find a module that has a Zip utility that I can use in > Python. I would like to be able to call the module and ZIP up a > directory. I thought there was such a module, but I have not been able > to find it. > > I need this to be able to be used in Python Win. Is there a ZIP utilty > already stored with a basic PYTHON download? > > Thanks all. the module is named "zipfile" (http://docs.python.org/lib/module- zipfile.html) http://docs.python.org/lib/zipfile-objects.html#zipfile-objects has more indepth information on all functions I can't say i've ever used it, but it seems pretty straightforward and mostly reminiscent of the basic read/write file modules. From tew24 at spam.ac.uk Tue Jan 30 06:13:33 2007 From: tew24 at spam.ac.uk (Tom Wright) Date: Tue, 30 Jan 2007 11:13:33 +0000 Subject: select windows References: Message-ID: Dennis Lee Bieber wrote: > (And the Amiga could add even more complexity -- I still miss the > Amiga's ability to PUSH a window to the back while STILL KEEPING > FOCUS... Made it easy to type stuff into one window while reading data > from a covering window!) KDE's window manager can do this (and it is useful, you're right). I suspect most other window managers will offer it as an option, too. -- I'm at CAMbridge, not SPAMbridge From gagsl-py at yahoo.com.ar Tue Jan 16 20:10:00 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Jan 2007 22:10:00 -0300 Subject: Search Queue In-Reply-To: References: <1168960945.787822.286690@s34g2000cwa.googlegroups.com> <1168962673.664083.146220@38g2000cwa.googlegroups.com> <1168964356.125262.45110@v45g2000cwv.googlegroups.com> Message-ID: <7.0.1.0.0.20070116215719.042859f0@yahoo.com.ar> At Tuesday 16/1/2007 15:01, Dennis Lee Bieber wrote: > If "Queue like functionality" means inserting at the end, and >removing from the front... Just use a list Someone said that time complexity should be part of an object public interfase. Implementing a queue using Python lists is trivial in terms of lines of code needed, but has a big time penalty. Queue users expect that put() and get() were fast, O(1) operations, but list.pop(0) is O(n). Python>=2.4 has a deque class (in the collections module) that can be used as a simple queue, and is efficient both in time and memory used. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at holdenweb.com Wed Jan 24 08:35:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 Jan 2007 13:35:08 +0000 Subject: Thoughts on using isinstance In-Reply-To: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> Message-ID: <45B7608C.4000007@holdenweb.com> abcd wrote: > In my code I am debating whether or not to validate the types of data > being passed to my functions. For example > > def sayHello(self, name): > if not name: > rasie "name can't be null" > if not isinstance(name, str): > raise "name must be a string" > print "Hello " + name > > Is the use of isinstance a "bad" way of doing things? is it a "heavy" > operation? for example, if I use this in each function validate input > will it slow things down a lot? > > just curious how you might handle this type of situation (other than > not validating at all). > > thanks > The "Python way" is to validate by performing the operations you need to perform and catching any exceptions that result. In the case of your example, you seem to be saying that you'd rather raise your own exception (which, by the way, should really be a subclass of Exception, but we will overlook that) that relying on the interpreter to raise a ValueError or a TypeError. Is there really any advantage to this? You increase your code size and add *something* to execution time with little real purpose. People coming to Python after C++ or some similar language that allows or requires parameter type declarations often don't feel comfortable taking this direction to start with, but it works well for most of us. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From could.net at gmail.com Sun Jan 7 04:27:57 2007 From: could.net at gmail.com (Frank Potter) Date: 7 Jan 2007 01:27:57 -0800 Subject: where is python on linux? In-Reply-To: References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> Message-ID: <1168162077.707526.281650@38g2000cwa.googlegroups.com> Thank you! "which python" works for me. I got it. Peter Otten wrote: > Frank Potter wrote: > > > I installed fedora core 6 and it has python installed. > > But the question is, where is the executable python file? > > Find out yourself with > > $ which python > > Peter From parallelpython at gmail.com Mon Jan 8 22:12:42 2007 From: parallelpython at gmail.com (Parallel Python The team) Date: Tue, 9 Jan 2007 03:12:42 +0000 Subject: Parallel Python In-Reply-To: <45A2109D.5050501@designaproduct.biz> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <45A2109D.5050501@designaproduct.biz> Message-ID: <8c1dbbd40701081912s897fafen8bf7b4f976c8b9d1@mail.gmail.com> On 1/8/07, Laszlo Nagy wrote: > > I always thought that if you use multiple processes (e.g. os.fork) then > Python can take advantage of multiple processors. I think the GIL locks > one processor only. The problem is that one interpreted can be run on > one processor only. Am I not right? Is your ppm module runs the same > interpreter on multiple processors? That would be very interesting, and > something new. > > > Or does it start multiple interpreters? Another way to do this is to > start multiple processes and let them communicate through IPC or a local > network. > > > Laszlo > > You are right. ppsmp start multiple interpreters in separate processes and organize communication between them through IPC. So far ppsmp features load balancing (distributes workload evenly between worker processes.) and low overhead (example http://www.parallelpython.com/content/view/17/31/#REVERSE_MD5 submits a 100 jobs to the system with no noticeable overhead). Of coerce there is always room for growth and I am considering adding new features/functionality. Do you have any functionality in mind which you want to see in this system? Best regards, Vitalii -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Mon Jan 1 02:57:33 2007 From: sjmachin at lexicon.net (John Machin) Date: 31 Dec 2006 23:57:33 -0800 Subject: A question about unicode() function In-Reply-To: <1167635228.725060.39110@42g2000cwt.googlegroups.com> References: <1167571210.084436.311610@48g2000cwx.googlegroups.com> <1167635228.725060.39110@42g2000cwt.googlegroups.com> Message-ID: <1167638253.544596.130630@v33g2000cwv.googlegroups.com> JTree wrote: > Hi, > > I changed my codes to: > > #!/usr/bin/python > #Filename: test.py > #Modified: 2007-01-01 > > import cPickle as p > import urllib > import htmllib > import re > import sys > > funUrlFetch = lambda url:urllib.urlopen(url).read() > > objUrl = raw_input('Enter the Url:') > content = funUrlFetch(objUrl) > content = content.encode('gb2312','ignore') Why did you change what you had before? "content" is a str, encoded in gb2312 (according to the internal evidence). You are now pretending that it is unicode, and trying to encode it as gb2312. However because it is *not* unicode, Python tries to convert it to unicode first. What you have coded above is equivalent to: content = content.decode('ascii').encode('gb2312', 'ignore') and of course the *decode* fails, as the error message says: Unicode*Decode*Error: 'ascii' codec can't decode byte 0xbb in position 88: ordinal not in range(128) It never got any where near the encode() So: If you want a str encoded in gb2312, leave it alone. If you want it in unicode, do this: ucontent = unicode(content, 'gb2312') > print content Try print repr(content) It's much better for diagnostic purposes. > content.close() This will be your next problem; "content" refers to a str object or a unicode object -- they don't have a close() method !! > > I used "ignore" to deal with the data lose, but it still caused a > error: What data loss??? > > C:\WINDOWS\system32\cmd.exe /c python tianya.py > Enter the Url:http://www.tianya.cn > Traceback (most recent call last): > File "tianya.py", line 17, in ? > content = content.encode('gb2312','ignore') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xbb in position > 88: ordinal not in range(128) > shell returned 1 > Hit any key to close this window... > > My python version is 2.4, Does it have some problems with asian > encoding support? "asian" is irrelevant. You would have got the same problem with just about any non-ascii encoding, including cp1252 and similar encodings commonly used in English-speaking countries and in western Europe. The only encoding support problem with 2.4 is that it can't read your mind. By the way, you should upgrade to 2.5, it can't read your mind either, but it has more functionality etc :-) HTH, John From jeremy+complangpython at jeremysanders.net Tue Jan 23 06:54:26 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 23 Jan 2007 11:54:26 +0000 Subject: PyQt4 strangeness References: Message-ID: Tina I wrote: > > self.connect(self.ui.testButton, QtCore.SIGNAL("clicked()"), > self.doSomething) > > Anyone know why this is? Or am I missing something very basic here? (I'm > still very much a noob I guess) If you want to import both you can do something like: import PyQt4.Qt as Qt which imports QtCore and QtGui Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From bj_666 at gmx.net Mon Jan 22 03:34:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 22 Jan 2007 09:34:13 +0100 Subject: Code reformater? References: Message-ID: In , Vincent Delporte wrote: > On Sun, 21 Jan 2007 14:15:46 +1100, Steven D'Aprano > wrote: >>Still, it is better not to lose the indentation in the first place. > > Thanks for the tips. But it does happen when copy/pasting code from > either a web page or an e-mail that TABs are messed up, which is not a > problem with other languages, but is a problem with Python. Too bad. Well then don't use code from people using TABs. If it's indented by four spaces per level, like suggested by the style guide, there's no problem with TABs. Ciao, Marc 'BlackJack' Rintsch From steven.bethard at gmail.com Wed Jan 31 11:25:04 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 31 Jan 2007 09:25:04 -0700 Subject: Conditional expressions - PEP 308 In-Reply-To: References: Message-ID: Colin J. Williams wrote: > It would be helpful if the rules of the game were spelled out more clearly. > > The conditional expression is defined as X if C else Y. > We don't know the precedence of the "if" operator. From the little test > below, it seem to have a lower precedence than "or". > > Thus, it is desirable for the user to put the conditional expression in > parentheses. Could you submit a documentation patch? http://sourceforge.net/tracker/?group_id=5470&atid=105470 It doesn't need to be in LaTeX. Plain text is fine. Just indicate in what document you think text should be added. STeVe From http Mon Jan 29 00:52:37 2007 From: http (Paul Rubin) Date: 28 Jan 2007 21:52:37 -0800 Subject: Random passwords generation (Python vs Perl) =) References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: <7x3b5uwfa2.fsf@ruckus.brouhaha.com> "NoName" writes: > from random import choice > import string > print ''.join([choice(string.letters+string.digits) for i in > range(1,8)]) > > !!generate password once :( > > who can write this smaller or without 'import'? If you don't mind possibly getting a few nonalphanumeric characters: import os,binascii print binascii.b2a_base64(os.urandom(6)) From maxerickson at gmail.com Mon Jan 8 14:05:06 2007 From: maxerickson at gmail.com (Max Erickson) Date: Mon, 8 Jan 2007 19:05:06 +0000 (UTC) Subject: recursive function References: <1168265240.294223.298750@s80g2000cwa.googlegroups.com> Message-ID: "cesco" wrote: > Hi, > > I have a dictionary of lists of tuples like in the following > example: dict = {1: [(3, 4), (5, 8)], > 2: [(5, 4), (21, 3), (19, 2)], > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]] > > In this case I have three lists inside the dict but this number > is known only at runtime. I have to write a function that > considers all the possible combinations of tuples belonging to > the different lists and return a list of tuples of tuples for > which the sum of the first element of the most inner tuple is > equal to N. > > For example, assuming N = 24, in this case it should return: > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), > (19, 2), (0, 2))] > > A simple list comprehension would be enough if only I knew the > number of keys/lists beforehand but this is not the case. I guess > I need a recursive function. Can anyone help? > > Thanks in advance > Francesco > This thread is probably of interest: http://groups.google.com/group/comp.lang.python/browse_frm/thread/f0c0 406fce981a54/59a2a5dcd1507ab9#59a2a5dcd1507ab9 max From rdiaz02 at gmail.com Sat Jan 20 16:37:24 2007 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Sat, 20 Jan 2007 22:37:24 +0100 Subject: Py 2.5 on Language Shootout In-Reply-To: <1169321686.025356.120340@s34g2000cwa.googlegroups.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> <45B23400.2010906@gmx.de> <1169321686.025356.120340@s34g2000cwa.googlegroups.com> Message-ID: <624934630701201337w10f72ce4j9903419e10befe3@mail.gmail.com> On 20 Jan 2007 11:34:46 -0800, Isaac Gouy wrote: > > Ramon Diaz-Uriarte wrote: > > On 1/20/07, Carl Friedrich Bolz wrote: > > > pgarrone at acay.com.au wrote: > > > >>> Looking over the benchmarks, one gains the impression that Python is a > > > >>> slow language. > > > >> What does that even mean - a slow language? > > > >> > > > > > > > > The alioth benchmarks provide a set of numbers by which > > > > languages may be compared. > > > > > > Wrong. The benchmarks provide a set of numbers by which > > > _implementations_ of languages can be compared. After all, it is > > > possible that someone implements a magic-pixie-dust-interpreter that > > > executes Python programs several orders of magnitude fastes than > > > CPython. Or you could say that C is slow because if you use CINT, a C > > > interpreter ( http://root.cern.ch/root/Cint.html ) to execute it, it is > > > slow. > > > > > > Yeah, but this is hair-splitting. Except for Jython, IronPython, and > > Stackless, I think when we say "Python is slow/fast" we think CPython > > (otherwise, we qualify the implementation). For that matter it is > > often said "the GIL ..."; oh, but wait, Stackless ... > > When we say "Python is slow/fast" what does "slow/fast" mean? > Oh, well, I have no idea. I guess you'd have to define what "speed" and, if that is a single number, then we can just rank languages. We'd probably never agree on how to obtain a single number. But I think most of us, when looking at the shootout, can see that there are some languages that, for most of the programs, are consistently faster than the rest, and others that are consistently slower. But really, I think the shootout page has large, detailed and statements about the perils and pitfalls of measuring these things. (And I do not go to the shootout to hear the oracle tell me which language I should use in my next project). > > > > > With other languages (e.g., Common Lisp) the separation between the > > language and the implementation is key because, to begin with, there > > is something external from, and independent of, any particular > > implementation. That is not the case with Python. > > > > And the example of CINT is hair-splitting to the nth power.To begin > > with, I do not think CINT implements the full standard C. But even if > > it were, when people think of C they rarely think of CINT. > > And that's why the existence of CINT is such a stark reminder of the > separation between the language and the implementation. When people > think of C what do they think of - gcc? tiny-c? intel c? microsoft c? > some mythical C implementation? > > Really, this ain't my war. Sure, there are two things: the language and the implementation. But, for practical purposes, when most people today say Python they mean CPython, whereas if the say Scheme, they certainly need to say _which_ Scheme (I think only PLT is in the official shootout page; there are others in the beta tests). If people want to mean Jython or Stackless, they just say that. As for C, I think people will need to qualify what exactly they mean. I think all these issues do not really lead to confusion for most of us; certainly not if you go to the shootout page. But as I said, this ain't my war. I was simply pointing out that correcting one poster for talking about languages when referring to python was hair splitting. And I think we are all running in circles, because I guess we all agree. This is turning into what in Spain (a country of catholic tradition) we call a discussion about "the sex of the angels" (el sexo de los angeles), i.e., whether angels are male or female or something else. Since sexing angels is not my area of expertise, I'll just shut up (I actually don't really know why I even said anything about this issue; please, forgive my chatiness). Best, R. > > > > I think readers understood the previous poster. > > > > Best, > > > > R. > > > > > > Cheers, > > > > > > Carl Friedrich Bolz > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > -- > > Ramon Diaz-Uriarte > > Statistical Computing Team > > Structural Biology and Biocomputing Programme > > Spanish National Cancer Centre (CNIO) > > http://ligarto.org/rdiaz > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From http Tue Jan 23 04:42:45 2007 From: http (Paul Rubin) Date: 23 Jan 2007 01:42:45 -0800 Subject: AES and Credit card number encryption References: <45b5159e$0$24377$88260bb3@free.teranews.com> <7xy7nu4ubj.fsf@ruckus.brouhaha.com> <45b55d8b$0$24450$88260bb3@free.teranews.com> Message-ID: <7xac0aoz8q.fsf@ruckus.brouhaha.com> Tobiah writes: > Looking at the problem further, I am getting the idea that > PGP, or GPG (Asymetric encryption) would be better, because > then all of the software that has to *write* CC numbers, would > not have to access the 'secret' key. Yes. > PGP sounds great, but it seems like a huge subject to cover > in a day or two. Is there a nice module for python that would > let me do the most usual operations easily? I just want to make > a key, hide it, and the use the public key to encrypt all future > and past credit card numbers. I think I did hear of a GPG module. You can also call GPG as an external library. There are also modules around that do public-key operations directly, or some like M2Crypto that use OpenSSL for public key operations. I wrote something a while back for applications pretty similar to yours, but never released it. I should clean it up sometime. At the moment I wouldn't consider it well-tested enough for deployment in real applications, and also it currently doesn't support AES because it was written to avoid using C extensions, so it used a nonstandard pure-Python cipher. http://www.nightsong.com/phr/crypto/crypto.txt If you want to just encrypt stuff in pure Python and you don't mind using a nonstandard (but reasonably secure, at least compared with the old rotor module it was written to replace), it's here: http://www.nightsong.com/phr/crypto/p3.py Note that you get a ciphertext considerably longer than the plaintext. This is unavoidable for various security reasons and a proper AES setup (or a call to GPG) will be the same way. From steven.bethard at gmail.com Sat Jan 27 22:00:48 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 27 Jan 2007 20:00:48 -0700 Subject: distutils, sdist and tests In-Reply-To: References: Message-ID: Robert Kern wrote: > Steven Bethard wrote: >> How do I get distutils to include my testing module in just the "sdist" >> distribution? > > Use a MANIFEST. > > http://docs.python.org/dist/source-dist.html > >> I want test_argparse.py to be available in the source distribution, but >> I don't think it should be included in the binary distributions. Using a MANIFEST appears to do the same thing as putting "test_argparse" into py_modules -- that is, it puts "test_argparse.py" into both "sdist" and "bdist" distributions. In "bdist" distributions it gets installed to the site-packages directory like any other module. STeVe From http Wed Jan 24 20:18:20 2007 From: http (Paul Rubin) Date: 24 Jan 2007 17:18:20 -0800 Subject: The reliability of python threads References: <4866bea60701241036g374bb401m6abbc1978ff6701c@mail.gmail.com> <1169683654.672020.136820@q2g2000cwa.googlegroups.com> <7xveiwklt0.fsf@ruckus.brouhaha.com> <1169687269.885833.285410@a34g2000cwb.googlegroups.com> Message-ID: <7x8xfr6h0j.fsf@ruckus.brouhaha.com> "Klaas" writes: > CPython is more that "a particular implementation" of python, It's precisely a particular implementation of Python. Other implementations include Jython, PyPy, and IronPython. > and the GIL is more than an "artifact". It is a central tenet of > threaded python programming. If it's a central tenet of threaded python programming, why is it not mentioned at all in the language or library manual? The threading module documentation describes the right way to handle thread synchronization in Python, and that module implements traditional locking approaches without reference to the GIL. > I don't advocate relying on the GIL to manage shared data when > threading, but 1) it is useful for the reasons I mention 2) the OP's > question was almost certainly about an application written for and run > on CPython. Possibly true. From steve at REMOVE.THIS.cybersource.com.au Sat Jan 27 01:00:36 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 27 Jan 2007 17:00:36 +1100 Subject: strip question References: <1169876027.003477.161350@a75g2000cwd.googlegroups.com> Message-ID: On Fri, 26 Jan 2007 21:33:47 -0800, eight02645999 wrote: > hi > can someone explain strip() for these : > [code] >>>> x='www.example.com' >>>> x.strip('cmowz.') > 'example' > [/code] > > when i did this: > [code] >>>> x = 'abcd,words.words' >>>> x.strip(',.') > 'abcd,words.words' > [/code] > > it does not strip off "," and "." .Why is this so? > thanks Fascinating... It gets weirder: >>> x.strip('s') 'abcd,words.word' Why strip only the final s, not the earlier one? >>> x.strip('w') 'abcd,words.words' >>> x.strip('o') 'abcd,words.words' >>> x.strip('r') 'abcd,words.words' Strips nothing. >>> x.strip('ba') 'cd,words.words' Strips correctly. >>> x.strip('bwa') 'cd,words.words' Strips the a and b but not the w. >>> x.strip('bwas') 'cd,words.word' ...and only one of the S's. >>> y = "bwas" >>> y.strip('bwas') '' >>> y = "bwasxyz" >>> y.strip('bwas') 'xyz' And yet these work. You know, I'm starting to think there may be a bug in the strip method... either that or the documentation should say: strip(...) S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove none, some or all characters in chars instead. If chars is unicode, S will be converted to unicode before stripping *wink* -- Steven. From mahs at telcopartners.com Mon Jan 29 18:27:07 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 29 Jan 2007 15:27:07 -0800 Subject: Overloading assignment operator In-Reply-To: References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> <1169604475.177104.40330@s48g2000cws.googlegroups.com> Message-ID: J. Clifford Dyer wrote: > I think that's the first time I've actually seen someone use a Monty > Python theme for a python example, and I must say, I like it. However, > "We are all out of Wensleydale." > > Cheers, > Cliff Oh, then you clearly don't waste nearly enough time on this newsgroup ;-) http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=spam+eggs http://groups.google.com/group/comp.lang.python/search?q=shrubbery http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=knights+ni http://groups.google.com/group/comp.lang.python/search?group=comp.lang.python&q=larch Idly yours, Michael From NikitaTheSpider at gmail.com Sat Jan 20 15:38:41 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sat, 20 Jan 2007 15:38:41 -0500 Subject: urllib2 and transfer-encoding = chunked References: <1169108468.497013.228520@l53g2000cwa.googlegroups.com> <1169137502.990783.222150@51g2000cwl.googlegroups.com> Message-ID: In article <1169137502.990783.222150 at 51g2000cwl.googlegroups.com>, jdvolz at gmail.com wrote: > Haha! My mistake. > > The error is that when a web server is chunking a web page only the > first chunk appears to be acquired by the urllib2.urlopen call. If you > check the headers, there is no 'Content-length' (as expected) and > instead there is 'transfer-encoding' = 'chunked'. I am getting about > the first 30Kb, and then nothing else. > > I don't get a ValueError like described at the following post: Hi jdvolz, What error *do* you get? Or is it that no error is raised; you're just not getting all of the data? If it is the latter, then the sending server might be at fault for not properly following the chunked transfer protocol. One way to find out would be to fire up Ethereal and see what's coming down the wire. > I am having errors which appear to be linked to a previous bug in > urllib2 (and urllib) for v2.4 and v2.5 of Python. Has this been fixed? > Has anyone established a standard workaround? I keep finding old > posts about it, that basically give up and say "well it's a known bug." Can you give us some pointers to some of these old posts? And tell us what version of Python you're using. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From timr at probo.com Fri Jan 19 03:35:59 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 19 Jan 2007 08:35:59 GMT Subject: Units of measurement References: <7x8xg1xr62.fsf_-_@ruckus.brouhaha.com> Message-ID: <8g01r2p6g6o1mujhicg2a6kuh32a2e7gdc@4ax.com> Paul Rubin wrote: > >I'm sure this has been done before, but it just struck my fancy, an >example of Python's "emulating numeric types", inspired by the old >Unix "units" utility, and the Frink language. >... ># could include more units but you get the idea >... >c = 186282*mile/second >print 'speed of light =', c/(furlong/fortnight), 'furlongs per fortnight' ># ... I could not skip to the next message without cutting, pasting, and executing that script to find out what the speed of light actually was in furlongs per fortnight. Now I need to figure out how to work that into a cocktail party conversation. "Hey, the deficit isn't the only thing that is approaching 1.8 trillion..." -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From hayes.tyler at gmail.com Sun Jan 21 17:09:01 2007 From: hayes.tyler at gmail.com (Tyler) Date: 21 Jan 2007 14:09:01 -0800 Subject: Reading Fortran Data Message-ID: <1169417341.339194.59560@q2g2000cwa.googlegroups.com> Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the delivery of Travis Oliphant's NumPy manual, I have a quick question (hopefully) regarding how to read in Fortran written data. The data files are not binary, but ASCII text files with no formatting and mixed data types (strings, integers, floats). For example, I have the following write statements in my Fortran code: I write the files as such: WRITE(90,'(A30)') fgeo_name WRITE(90,'(A30)') fmed_name WRITE(90,*) nfault,npoint WRITE(90,*) (xpt(n), n=1,npoint) WRITE(90,*) (ypt(n), n=1,npoint) and, WRITE(10,'(A30)') fname DO i=1,nfault WRITE(10,*) dbn(i),dtn(i),xfwnt(i),yfwnt(i),xfent(i),yfent(i),& & slpvlS(i),slpvlD(i),slpvlT(i),segdp1(i) END DO I then respectively read them into Fortran as: READ(70,'(A30)') fgeo_name READ(70,'(A30)') fmed_name READ(70,*) nfault,npoint READ(70,*) (x(n), n=1,npoint) READ(70,*) (y(n), n=1,npoint) and, READ(20,'(A30)') fname DO i=1,nfault READ(20,*) dbn(i),dtn(i),xfwnt(i),yfwnt(i),xfent(i),yfent(i),& & slpvlS(i),slpvlD(i),slpvlT(i),segdp1(i) END DO I also read them into IDL for visualization using the "READF" command. I was wondering how I might go about reading this into Python using NumPy. If this is not trivial, let me know and I'll just wait until the NumPy manual arrives. Cheers, t. From danb_83 at yahoo.com Tue Jan 2 21:30:04 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 2 Jan 2007 18:30:04 -0800 Subject: Iterate through list two items at a time In-Reply-To: References: Message-ID: <1167791404.814286.80570@n51g2000cwc.googlegroups.com> On Jan 2, 7:57 pm, "Dave Dean" wrote: > Hi all, > I'm looking for a way to iterate through a list, two (or more) items at a > time. Basically... > > myList = [1,2,3,4,5,6] > > I'd like to be able to pull out two items at a time... def pair_list(list_): return [list_[i:i+2] for i in xrange(0, len(list_), 2)] From facundo at taniquetil.com.ar Fri Jan 12 11:11:40 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Fri, 12 Jan 2007 16:11:40 +0000 (UTC) Subject: Rational Numbers References: Message-ID: Noud Aldenhoven wrote: > There are a (small) couple of other issues where rational numbers could be > handy. That's because rational numbers are exact, irrational numbers (in > python) aren't. But these issues are probably too mathematical to be used in For the sake of me being less ignorant, could you please point me a language where irrational numbers are exact? Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From rw at smsnet.pl Fri Jan 12 17:07:19 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 12 Jan 2007 23:07:19 +0100 Subject: module file References: <45a7ba78$0$316$426a74cc@news.free.fr> Message-ID: <87hcuv527c.fsf@smsnet.pl> Imbaud Pierre writes: > I am willing to retrieve the file an imported module came from; > module.__file__, or inspect.getfile(module) only gives me the > relative file name. How do I determine the path? >>> import os >>> os.path.abspath(module.__file__) -- HTH, Rob From grflanagan at yahoo.co.uk Wed Jan 3 01:32:36 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 2 Jan 2007 22:32:36 -0800 Subject: Iterate through list two items at a time In-Reply-To: References: Message-ID: <1167805956.358933.191000@i12g2000cwa.googlegroups.com> Dave Dean wrote: > Hi all, > I'm looking for a way to iterate through a list, two (or more) items at a > time. Basically... > > myList = [1,2,3,4,5,6] > > I'd like to be able to pull out two items at a time - simple examples would > be: > Create this output: > 1 2 > 3 4 > 5 6 > > Create this list: > [(1,2), (3,4), (5,6)] > A "padding generator" version: def chunk( seq, size, pad=None ): ''' Slice a list into consecutive disjoint 'chunks' of length equal to size. The last chunk is padded if necessary. >>> list(chunk(range(1,10),3)) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> list(chunk(range(1,9),3)) [[1, 2, 3], [4, 5, 6], [7, 8, None]] >>> list(chunk(range(1,8),3)) [[1, 2, 3], [4, 5, 6], [7, None, None]] >>> list(chunk(range(1,10),1)) [[1], [2], [3], [4], [5], [6], [7], [8], [9]] >>> list(chunk(range(1,10),9)) [[1, 2, 3, 4, 5, 6, 7, 8, 9]] >>> for X in chunk([],3): print X >>> ''' n = len(seq) mod = n % size for i in xrange(0, n-mod, size): yield seq[i:i+size] if mod: padding = [pad] * (size-mod) yield seq[-mod:] + padding ------------------------------------------------------------------ Gerard From syedamjad_a at yahoo.com Fri Jan 12 12:16:51 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 12 Jan 2007 09:16:51 -0800 Subject: parsing a file name Message-ID: <1168622211.188972.179680@38g2000cwa.googlegroups.com> I have a filename cairo-2.3.4.src.rpm Is there any way i can only get 2.3.4 from this file name thanks From hg at nospam.org Mon Jan 15 11:40:31 2007 From: hg at nospam.org (hg) Date: Mon, 15 Jan 2007 17:40:31 +0100 Subject: download win32file References: <_mTqh.49191$kn7.39312@newsfe23.lga> Message-ID: jim-on-linux wrote: > On Monday 15 January 2007 10:37, hg wrote: >> jim-on-linux wrote: >> > Where can I download win32file / win32ui? >> > >> > The links below are broken. Mark Hammond >> > should be made aware of this. >> > >> > >> > URL below has two links that send you no >> > place >> > http://mail.python.org/pipermail/python-list/ >> >2002-October/167638.html >> > >> > >> > Links: >> > http://starship.python.net/crew/mhammond/win3 >> >2/Downloads.html >> > >> > http://starship.python.net/crew/mhammond/down >> >loads/win32all-148.exe >> > >> > >> > Produce; >> > >> > The requested URL was not found on this >> > server. The link on the referring page seems >> > to be wrong or outdated. Please inform the >> > author of that page about the error. >> > >> > jim-on-linux >> >> Do you mean PyWin32 ? > > ?? Do I have to download pywin32 to get win32ui, > or win32file, or win32api > >> >> http://sourceforge.net/projects/pywin32/ To my knowledge, yes. hg From ndbecker2 at gmail.com Thu Jan 25 06:41:12 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 25 Jan 2007 06:41:12 -0500 Subject: MIME text attachment question Message-ID: I want to send a file (plain text) as an attachment. I'm using MIMEText. This attaches text OK, but I would like to have a filename attached to it, so that the recipient could save it without having to specify a filename. Any suggestions? From carsten at uniqsys.com Fri Jan 12 10:36:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 12 Jan 2007 10:36:38 -0500 Subject: Rational Numbers In-Reply-To: References: Message-ID: <1168616198.3382.55.camel@dot.uniqsys.com> On Fri, 2007-01-12 at 15:05 +0000, Nick Maclaren wrote: > In article , > Carsten Haese writes: > |> On Thu, 2007-01-11 at 23:47 +0000, Nick Maclaren wrote: > |> > In article , > |> > Facundo Batista writes: > |> > |> Python does not have rational numbers. > |> > |> > |> > |> There's a (rejected) PEP about this, PEP-239: > |> > |> > |> > |> http://www.python.org/dev/peps/pep-0239/ > |> > |> > |> > |> Maybe you also want to read the section "Why not rational?" of > |> > |> PEP-327... > |> > |> > |> > |> http://www.python.org/dev/peps/pep-0327/#why-not-rational > |> > > |> > Oh, God. Decimal delusions again :-( > |> > > |> > There are good arguments for not having a rational type, but the idea > |> > that decimal floating-point is in any way a replacement is cuckoo. > |> > |> You're putting words in Facundo's mouth. Facundo didn't say why we > |> should read that section of PEP 327. I think he merely pointed to the > |> slow performance of rational numbers that's explained in that section. > |> (Facundo is the author of PEP 327, so I find it unlikely that he has > |> delusions about what decimals can and can't do.) > > You're putting words in MY mouth! I didn't say that he did. But I > agree that my words could easily be read that way, so I apologise for > any misunderstanding. > [...] > The BDFL Pronouncement rejecting PEP 239 does, even if it does qualify > it by saying "to some extent". And it was that PEP that I was primarily > referring to in that remark. Ah, so now you're putting words in the BDFL's mouth. ;) The pronouncement does say "The needs outlined in the rationale section have been addressed to some extent by the acceptance of PEP 327 for decimal arithmetic," but it doesn't say to which extent, and it certainly doesn't claim that decimal arithmetic is a replacement for rational arithmetic. > The "Why not rational?" section of PEP 327 quotes Alex Martelli as saying > that Rational are not worth doing without Decimal, which makes no sense > at all. All it does is to plug Decimal for a purpose for which it is > completely unsuited; not all rational numbers have denumerators that are > powers of 10. The sentence you're referring to is "There are excellent Rational implementations [...]. Probably worth PEPping, not worth doing without Decimal." I agree that this sentence is poorly worded, but I think it means "Even if we had Rational, we'd still need Decimal" in the sense that Rational is not an adequate replacement for Decimal. The bottom line is that there are use cases for both Rational and Decimal, and neither one can replace the other, but there are more use cases for Decimal than for Rational. -Carsten From jstroud at mbi.ucla.edu Tue Jan 30 07:30:07 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 30 Jan 2007 12:30:07 GMT Subject: Help me understand this In-Reply-To: <1170146755.446429.90720@v45g2000cwv.googlegroups.com> References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> <1170146755.446429.90720@v45g2000cwv.googlegroups.com> Message-ID: Beej wrote: >>>> (2).__add__(1) Nice. I would have never thought to put parentheses around an integer to get at its attributes. James From dejan.wirusrodiger at ck.t-com.hr Mon Jan 22 15:28:51 2007 From: dejan.wirusrodiger at ck.t-com.hr (Dejan Rodiger) Date: Mon, 22 Jan 2007 21:28:51 +0100 Subject: SQLObject 0.8.0b2 In-Reply-To: <1169496151.864232.65190@m58g2000cwm.googlegroups.com> References: <1169496151.864232.65190@m58g2000cwm.googlegroups.com> Message-ID: Robert Hicks said the following on 22.1.2007 21:02: > Where is Oracle support? > What about DB2 UDB and DB2/400 >:o -- Dejan Rodiger - PGP ID 0xAC8722DC Delete wirus from e-mail address From steve at REMOVEME.cybersource.com.au Mon Jan 8 03:15:55 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 08 Jan 2007 19:15:55 +1100 Subject: regex question References: <1168232001.377605.236270@11g2000cwr.googlegroups.com> <45a1f0c6$0$18929$4c368faf@roadrunner.com> <1168243020.304940.212700@42g2000cwt.googlegroups.com> Message-ID: On Sun, 07 Jan 2007 23:57:00 -0800, proctor wrote: > it does work now...however, one more question: when i type: > > rx_a = re.compile(r'a|b|c') > it works correctly! > > shouldn't: > rx_a = re.compile(makeRE(test)) > give the same result since makeRE(test)) returns the string "r'a|b|c'" Those two strings are NOT the same. >>> s1 = r'a|b|c' >>> s2 = "r'a|b|c'" >>> print s1, len(s1) a|b|c 5 >>> print s2, len(s2) r'a|b|c' 8 A string with a leading r *outside* the quotation marks is a raw-string. The r is not part of the string, but part of the delimiter. A string with a leading r *inside* the quotation marks is just a string with a leading r. It has no special meaning. -- Steven D'Aprano From steve at holdenweb.com Sun Jan 28 04:51:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Jan 2007 09:51:07 +0000 Subject: Crunchy 0.8 release In-Reply-To: <1169932766.450129.259840@k78g2000cwa.googlegroups.com> References: <1169932766.450129.259840@k78g2000cwa.googlegroups.com> Message-ID: <45BC720B.5010909@holdenweb.com> Andr? wrote: > Version 0.8 of Crunchy has been released. It is available on > http://code.google.com/p/crunchy/ > > Crunchy, the Interactive Python Tutorial Maker, is an application that > transforms an ordinary html-based Python tutorial into an interactive > session within a web browser. Currently, only Firefox is supported. > Crunchy is developed and tested on Windows XP and Ubuntu Dapper Drake, > but should work on any suitable windows or UNIX system. > > Three major improvements have been made since version 0.7 had been > released. > > 1. New editor > > Instead of a simple html textarea, Crunchy now gives the option of > using a "real" editor, namely EditArea > (http://www.cdolivet.net/editarea/). EditArea support syntax coloring > and allows loading and saving local Python files among other features. > Within Crunchy, it is set up so that the tab key is translated into 4 > spaces. > > 2. Language support > > Crunchy now supports English and French, through the use of ".po" > files. When running Python code, some error messages have been > adapted/translated. EditArea itself support more languages > (currently: Danish, Dutch, English, French, German, Italian, Japanese, > Polish, Portuguese). > > 3. Graphical tutorial converter. > > Crunchy uses some supplementary markup to transform html files into > interactive tutorials. Whereas previous versions required a tutorial > maker to edit an html file "by hand", version 0.8 includes a tutorial > editor: with a few clicks, you can easily add to an html file the > chosen interactive elements and options for Crunchy. > > In addition to the above major improvements, the code has been > refactored significantly and a number of small bug fixes have been > made. Crunchy will be demonstrated at the upcoming Pycon 2007. > > Andr? Roberge and Johannes Woolard. > Very nice indeed, and a significant advance over 0.7 - I'll be trying to write Crunchy presentations myself (though possibly not as soon as PyCon). I found it a little strange that the top-level directory in the distribution is called "andre" rather than "crunchy", but that's a very minor point. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From nick at craig-wood.com Thu Jan 4 07:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 04 Jan 2007 06:30:07 -0600 Subject: code optimization (calc PI) References: Message-ID: mm wrote: > (Yes, I konw whats an object is...) > BTW. I did a translation of a pi callculation programm in C to Python. > (Do it by your own... ;-) > Calc PI for 800 digs(?). (german: Stellen) > int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5; > for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a, > f[b]=d%--g,d/=g--,--b;d*=b);} Below you'll find my translation. Note that I improved the algorithm greatly. Note the nice easy to read algorithm also! This calculated 800 digits of pi in 0.1 seconds and 10,000 digits in 20 seconds. ------------------------------------------------------------ """ Standalone Program to calculate PI using python only Nick Craig-Wood """ import sys from time import time class FixedPoint(object): """A minimal immutable fixed point number class""" __slots__ = ['value'] # __weakref__ digits = 25 # default number of digits base = 10**digits def __init__(self, value=0): """Initialise the FixedPoint object from a numeric type""" try: self.value = long(value * self.base) except (TypeError, ValueError), e: raise TypeError("Can't convert %r into long", value) def set_digits(cls, digits): """Set the default number of digits for new FixedPoint numbers""" cls.digits = digits cls.base = 10**digits set_digits = classmethod(set_digits) def copy(self): "Copy self into a new object" new = FixedPoint.__new__(FixedPoint) new.value = self.value return new __copy__ = __deepcopy__ = copy def __add__(self, other): """Add self to other returning the result in a new object""" new = self.copy() new.value = self.value + other.value return new __radd__ = __add__ def __sub__(self, other): """Subtract self from other returning the result in a new object""" new = self.copy() new.value = self.value - other.value return new def __rsub__(self, other): new = self.copy() new.value = other.value - self.value return new def __mul__(self, other): """ Multiply self by other returning the result in a new object. The number of digits is that of self. Note that FixedPoint(x) * int(y) is much more efficient than FixedPoint(x) * FixedPoint(y) """ new = self.copy() if isinstance(other, (int, long)): # Multiply by scalar new.value = self.value * other else: new.value = (self.value * other.value) // other.base return new __rmul__ = __mul__ def __div__(self, other): """ Divide self by other returning the result in a new object. The number of digits is that of self. Note that FixedPoint(x) / int(y) is much more efficient than FixedPoint(x) / FixedPoint(y) """ new = self.copy() if isinstance(other, (int, long)): # Divide by scalar new.value = self.value // other else: new.value = (self.value * other.base) // other.value return new def __rdiv__(self, other): if not isinstance(other, FixedPoint): other = FixedPoint(other, self.digits) return other.__div__(self) def __str__(self): """ Convert self into a string. This will be the integral part of the number possibly preceded by a - sign followed by a . then exactly n digits where n is the number of digits specified on creation. """ if self.value < 0: s = str(-self.value) else: s = str(self.value) s = s.zfill(self.digits + 1) s = s[:-self.digits] + "." + s[-self.digits:] if self.value < 0: s = "-" + s return s def __abs__(self): """Return the absolute value of self""" new = self.copy() if new.value < 0: new.value = - new.value return new def __cmp__(self, other): """Compare self with other""" return cmp(self.value, other.value) def sqrt(n): """ Return the square root of n. It uses a second order Newton-Raphson convgence. This doubles the number of significant figures on each iteration. This will work for any finite precision numeric type. """ x = n / 2 # FIXME find a better guess! old_delta = None while 1: x_old = x x = (x + n / x) / 2 delta = abs(x - x_old) if old_delta is not None and delta >= old_delta: break old_delta = delta return x def pi_agm(one = 1.0, sqrt=sqrt): """ Brent-Salamin Arithmetic-Geometric Mean formula for pi. This converges quadratically. FIXME can increase the number of digits in each iteration to speed up? """ _1 = one _2 = _1 + _1 a = _1 b = _1/sqrt(_2) t = _1/2 k = 1 two_to_the_k = 2L old_delta = None while 1: s = (a + b ) / 2 d = a - s d = d * d a = s s = s * s t = t - two_to_the_k * d b = sqrt(s - d) delta = abs(a - b) # print k, delta, old_delta if old_delta is not None and delta >= old_delta: break old_delta = delta k = k + 1 two_to_the_k *= 2 a = a + b return ( a * a ) / ( _2 * t) if __name__ == "__main__": try: digits = int(sys.argv[1]) except: digits = 100 print "Calculating",digits,"digits of pi" start = time() FixedPoint.set_digits(digits) _1 = FixedPoint(1) print pi_agm(_1, sqrt=sqrt) dt = time() - start print "That took",dt,"seconds" ------------------------------------------------------------ > But Python is much slower here then C here. I used a while-loop within a > while-loop. Not that much calculation here. There is more than one way to skin this cat. A better algorithm helps a lot. If I really wanted lots of digits of pi from python I'd do it like this. This is an example of the right tool for the job. 0.5ms looks pretty good to me! >>> import math, gmpy >>> bits = int(800/math.log10(2)) >>> start = time(); pi=gmpy.pi(bits); dt = time()-start >>> print "That took",dt,"seconds" That took 0.00055193901062 seconds >>> pi mpf('3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455e0',2657) >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From nagle at animats.com Fri Jan 19 20:20:34 2007 From: nagle at animats.com (John Nagle) Date: Sat, 20 Jan 2007 01:20:34 GMT Subject: More M2Crypto issues In-Reply-To: References: <6u7sh.264$4H1.150@newssvr17.news.prodigy.net> Message-ID: Heikki Toivonen wrote: > John Nagle wrote: > >> Actually, at the moment I'm having an M2Crypto problem related >>to a SWIG/OpenSSL conflict. Older versions of OpenSSL have an >>include file that needs __i386__ defined, which is something GCC >>does based on what platform you're on. SWIG uses CPP, but >>doesn't set the platform defines, so the SWIG phase of the >>M2Crypto build fails. I'm currently trying to get the shared >>host where that build took place upgraded to a later version of >>OpenSSL, but that requires a server restart, so it may take >>a few days. I'm doing something that requires M2Crypto to >>run on a range of machines, which turns out to be rather harder >>than expected. > > > Which version of OpenSSL is that? M2Crypto 0.17 requirements: Python 2.3 or newer o m2urllib2 requires Python 2.4 or newer OpenSSL 0.9.7 or newer o Some optional new features will require OpenSSL 0.9.8 or newer SWIG 1.3.24 or newer Server in use: Python version: "Python 2.5 (r25:51908, Jan 18 2007, 10:46:37)" OpenSSL version: "OpenSSL 0.9.7a Feb 19 2003" SWIG version: "SWIG Version 1.3.31" GCC version: "[GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2" Computer: Athlon 686 rackmount server. The actual build failure is: running build_ext building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:27: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 The problem is that "opensslconf.h" expects the compiler to define __i386__ when running the C preprocessor, and SWIG doesn't do that. Compare "opensslconf.h" in different versions of OpenSSL; it's changed considerably. John Nagle From sigzero at gmail.com Mon Jan 22 15:02:31 2007 From: sigzero at gmail.com (Robert Hicks) Date: 22 Jan 2007 12:02:31 -0800 Subject: SQLObject 0.8.0b2 In-Reply-To: References: Message-ID: <1169496151.864232.65190@m58g2000cwm.googlegroups.com> Where is Oracle support? From gagsl-py at yahoo.com.ar Mon Jan 22 14:35:49 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Jan 2007 16:35:49 -0300 Subject: closing a "forever" Server Socket In-Reply-To: <1169488142.312711.322320@51g2000cwl.googlegroups.com> References: <1169123381.930403.24170@38g2000cwa.googlegroups.com> <1169143715.222186.30530@51g2000cwl.googlegroups.com> <1169482385.253887.249030@51g2000cwl.googlegroups.com> <1169488142.312711.322320@51g2000cwl.googlegroups.com> Message-ID: <7.0.1.0.0.20070122162756.059d70a8@yahoo.com.ar> At Monday 22/1/2007 14:49, alessandro wrote: >Oh my God! it's really so complicated? > >3 modules (threading, SocketServer, select) only for design a way to >shutdown a TCP server???? >...but they told me that python was easy... :) You already have the answer: replace serve_forever with your own loop. >I'm working on a simulator and I have a monitor server that collects >information. I can shutdown it using Ctrl-C from the keyboard but for >my purpose could be very nice if I introduce a timer. So I could launch >my monitor like this: >./monitor 100 > >and my monitor will run for 100 seconds. For this I'm using the Timer This is simple enough, I presume: try: stopt = time.time()+100 while time.time() References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Message-ID: sturlamolden wrote: > Nick Maclaren wrote: > > I wonder if too much emphasis is put on thread programming these days. > Threads may be nice for programming web servers and the like, but not > for numerical computing. Reading books about thread programming, one > can easily get the impression that it is 'the' way to parallelize > numerical tasks on computers with multiple CPUs (or multiple CPU Most threads on this planet are not used for number crunching jobs, but for "organization of execution". Also if one wants to exploit the speed of upcoming multi-core CPUs for all kinds of fine grained programs, things need fast fine grained communication - and most important: huge data trees in memory have to be shared effectively. CPU frequencies will not grow anymore in the future, but we will see multi-cores/SMP. How to exploit them in a manner as if we had really faster CPU's: threads and thread-like techniques. Things like MPI, IPC are just for the area of "small message, big job" - typically sci number crunching, where you collect the results "at the end of day". Its more a slow network technique. A most challenging example on this are probably games - not to discuss about gaming here, but as tech example to the point: Would you do MPI, RPC etc. while 30fps 3D and real time physics simulation is going on? Robert From sturlamolden at yahoo.no Wed Jan 10 12:15:42 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: 10 Jan 2007 09:15:42 -0800 Subject: Parallel Python In-Reply-To: References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> Message-ID: <1168449342.414838.181050@p59g2000hsd.googlegroups.com> robert wrote: > Thats true. IPC through sockets or (somewhat faster) shared memory - cPickle at least - is usually the maximum of such approaches. > See http://groups.google.de/group/comp.lang.python/browse_frm/thread/f822ec289f30b26a > > For tasks really requiring threading one can consider IronPython. > Most advanced technique I've see for CPython ist posh : http://poshmodule.sourceforge.net/ In SciPy there is an MPI-binding project, mpi4py. MPI is becoming the de facto standard for high-performance parallel computing, both on shared memory systems (SMPs) and clusters. Spawning threads or processes is not recommended way to do numerical parallel computing. Threading makes programming certain tasks more convinient (particularly GUI and I/O, for which the GIL does not matter anyway), but is not a good paradigm for dividing CPU bound computations between multiple processors. MPI is a high level API based on a concept of "message passing", which allows the programmer to focus on solving the problem, instead on irrelevant distractions such as thread managament and synchronization. Although MPI has standard APIs for C and Fortran, it may be used with any programming language. For Python, an additional advantage of using MPI is that the GIL has no practical consequence for performance. The GIL can lock a process but not prevent MPI from using multiple processors as MPI is always using multiple processes. For IPC, MPI will e.g. use shared-memory segments on SMPs and tcp/ip on clusters, but all these details are hidden. It seems like 'ppsmp' of parallelpython.com is just an reinvention of a small portion of MPI. http://mpi4py.scipy.org/ http://en.wikipedia.org/wiki/Message_Passing_Interface From bruno.desthuilliers at websiteburo.com Wed Jan 17 11:38:16 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Wed, 17 Jan 2007 17:38:16 +0100 Subject: Python Web Frameworks In-Reply-To: <1169048071.353887.279160@q2g2000cwa.googlegroups.com> References: <1169048071.353887.279160@q2g2000cwa.googlegroups.com> Message-ID: <45ae50f7$0$4263$426a74cc@news.free.fr> Shortash a ?crit : > Hi Gurus, > > I want to build a Python web app but im not sure which one to go for. I > prefer something like asp.Net , which would allow me to fully seperate > the presentation layer from the logic. Please advise? Django, Turbogears, Pylons(HQ), web.py, etc, etc, etc... Welcome to Python, the language with more web frameworks than keywords !-) From gert.cuykens at gmail.com Fri Jan 5 23:45:47 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Sat, 6 Jan 2007 05:45:47 +0100 Subject: attribute decorators In-Reply-To: <1168058094.179442.173650@s34g2000cwa.googlegroups.com> References: <1168058094.179442.173650@s34g2000cwa.googlegroups.com> Message-ID: sorry for repost i just found out the news group comp.lang.python is the same as python-list at python.org :) On 5 Jan 2007 20:34:54 -0800, gert wrote: > Would it not be nice if you could assign decorators to attributes too ? > for example > > class C: > @staticattribute > data='hello' > > or > > class C: > @privateattribute > data='hello' > > -- > http://mail.python.org/mailman/listinfo/python-list > From george.sakkis at gmail.com Sun Jan 21 03:20:40 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Jan 2007 00:20:40 -0800 Subject: mmap caching Message-ID: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> I've been trying to track down a memory leak (which I initially attributed erroneously to numpy) and it turns out to be caused by a memory mapped file. It seems that mmap caches without limit the chunks it reads, as the memory usage grows to several hundreds MBs according to the Windows task manager before it dies with a MemoryError. I'm positive that these chunks are not referenced anywhere else; in fact if I change the mmap object to a normal file, memory usage remains constant. The documentation of mmap doesn't mention anything about this. Can the caching strategy be modified at the user level ? George From mensanator at aol.com Mon Jan 8 19:30:35 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Jan 2007 16:30:35 -0800 Subject: Bitwise expression References: Message-ID: <1168302635.083841.54290@38g2000cwa.googlegroups.com> Gigs_ wrote: > Can someone explain me bitwise expression? > few examples for every expression will be nice > > x << y Left shift > x >> y Right shift > x & y Bitwise AND > x | y Bitwise OR > x ^ y Bitwise XOR (exclusive OR) > ~x Bitwise negation > > > thanks people Here's some examples: ## What is BINARY? ## ## n base 2 ## -- -------- ## 0 00000000 ## 1 00000001 ## 2 00000010 ## 3 00000011 ## 4 00000100 ## 5 00000101 ## 6 00000110 ## 7 00000111 ## 8 00001000 ## 9 00001001 ## 10 00001010 ## 11 00001011 ## 12 00001100 ## 13 00001101 ## 14 00001110 ## 15 00001111 ## ## ## What does << do? ## ## 00000111 ## << 00000100 ## ------------ ## 01110000 ## ## What does >> do? ## ## 00100100 ## >> 00000010 ## ------------ ## 00001001 ## ## What does & do? ## ## 00011011 ## & 00001001 ## ------------ ## 00001001 ## ## 00011011 ## & 00001110 ## ------------ ## 00001010 ## ## What does | do? ## ## 00010001 ## | 00001010 ## ------------ ## 00011011 ## ## 00011011 ## | 00010001 ## ------------ ## 00011011 ## ## What does ^ do? ## ## 00011011 ## ^ 00011111 ## ------------ ## 00000100 ## ## 00011111 ## ^ 00001110 ## ------------ ## 00010001 ## ## Bitwise demo: the Collatz Conjecture ## ## 41 31 47 71 107 161 121 91 137 103 155 233 ## 175 263 395 593 445 167 251 377 283 425 319 ## 479 719 1079 1619 2429 911 1367 2051 3077 ## 577 433 325 61 23 35 53 5 1 bitwise.py import gmpy # has lots of neat bitwise operations # not found in standard Python def convert_to_binary(n,bits): s = gmpy.digits(n,2) # base 2 conversion s = '0'*(bits-len(s)) + s # add leading 0's return s def report(n,m,o,p): print ' %s' % (n) print '%3s %s' % (o,m) print '------------' print ' %s' % (p) print def Collatz(n): # if n is even, divide by 2 # if n is odd, multiply by 3 and add 1 # Collat Conjecture: n always reaches 1 while n>1: # find bit position of LS 1 bit f = gmpy.scan1(n) if f == 0: # then n is odd n = n*3 + 1 else: # n is even # remove all factors of 2 in one fell swoop n = n >> f print n, print print 'What is BINARY?' print """ n base 2 -- --------""" for n in xrange(16): print '%2d %s' % (n,convert_to_binary(n,8)) print print print 'What does << do?' print report(convert_to_binary(7,8), \ convert_to_binary(4,8), \ '<<', \ convert_to_binary(7<<4,8)) print 'What does >> do?' print report(convert_to_binary(36,8), \ convert_to_binary(2,8), \ '>>', \ convert_to_binary(36>>2,8)) print 'What does & do?' print report(convert_to_binary(27,8), \ convert_to_binary(9,8), \ '&', \ convert_to_binary(27&9,8)) report(convert_to_binary(27,8), \ convert_to_binary(14,8), \ '&', \ convert_to_binary(27&14,8)) print 'What does | do?' print report(convert_to_binary(17,8), \ convert_to_binary(10,8), \ '|', \ convert_to_binary(17|10,8)) report(convert_to_binary(27,8), \ convert_to_binary(17,8), \ '|', \ convert_to_binary(27|17,8)) print 'What does ^ do?' print report(convert_to_binary(27,8), \ convert_to_binary(31,8), \ '^', \ convert_to_binary(27^31,8)) report(convert_to_binary(31,8), \ convert_to_binary(14,8), \ '^', \ convert_to_binary(31^14,8)) print 'Bitwise demo: the Collatz Conjecture' print Collatz(27) From vithi99 at hotmail.com Mon Jan 15 00:11:31 2007 From: vithi99 at hotmail.com (vithi) Date: 14 Jan 2007 21:11:31 -0800 Subject: How to write code to get focuse the application which is open from server In-Reply-To: <45a0dae2$0$8948$4c368faf@roadrunner.com> References: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> <45a0dae2$0$8948$4c368faf@roadrunner.com> Message-ID: <1168837891.232014.270150@11g2000cwr.googlegroups.com> Hi Paul, Since your reply I try to use pywinauto. I was able to get the control of a window that is a good news but it is not working for sub window this main window create.(popup windows) eg) File -> print will open print window but the code is not clicking print button. I try several combination app,Print.OK.CloseClick() or app,Print.OK.Click() is not working my code goes like that app=application.Application() qi = app.window_(title_re = ".*arcMap.*") qi.TypeKeys("%FP") app,Print.OK.Click() the last line of code is not working same thing with file open to qi.TypeKeys("%FO") create popup window "open" but app,Open.Filename.SetEditText("test1,txt") is not working any help to overcome to this problem (Here the "Print" , "Open" are windows title I am using without any undestanding why I am using. Any help? Paul McGuire wrote: > "vinthan" wrote in message > news:1168143871.536432.252010 at v33g2000cwv.googlegroups.com... > > hi, > > I am new to python. I have to write test cases in python. An > > application is open in the desk top ( application writen in .Net) I > > have to write code to get focuse the application and click on the link > > which in the one side and it will load the map on the other and I have > > to check map is loaded. Any one tell me how do I use Dispatch or any > > other method to write a code. > > > If you are running on Windows, look into pywinauto > (http://www.openqa.org/pywinauto/). > > I have successfully used it to interact with a Flash animation running > within an IE browser. > > I also had to inspect the graphics displayed by the Flash animation, for > this I used PIL (http://www.pythonware.com/products/pil/). > > Good luck, > -- Paul From duncan.booth at invalid.invalid Tue Jan 9 13:43:58 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jan 2007 18:43:58 GMT Subject: Question about using "with" References: Message-ID: Laszlo Nagy wrote: > >> >> 591 > ./cat.py cat.py >> File "./cat.py", line 6 >> with open(sys.argv[nn]) as f: >> ^ >> SyntaxError: invalid syntax >> 592 > >> >> This example came from http://docs.python.org/tut/node10.html down in >> section 8.7 >> >> Am I missing something? >> > Are you using python 2.5? The with statement is not available before 2.5. > and even in Python 2.5 it isn't available unless you enable it. Add the following line before the 'import sys' line: from __future__ import with_statement From gagsl-py at yahoo.com.ar Tue Jan 23 13:56:12 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Jan 2007 15:56:12 -0300 Subject: Reading character from keyboard In-Reply-To: <1169576879.920810.306490@q2g2000cwa.googlegroups.com> References: <1169576879.920810.306490@q2g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070123155521.04227a68@yahoo.com.ar> At Tuesday 23/1/2007 15:28, consmash at gmail.com wrote: > > A very simple question. I would like to read a single character from the > > keyboard (y or n). I have tried to look in my Python books and a google > >Actually, if you want to read only one character from keyboard, you >will need to use terminal operations rather than plain input stream. >Unfortunately this is rather not portable solution. For Windows you >have to import msvcrt, on Unices curses module. The latter code is There is a portable getch implementation, search the Python Cookbook. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Wed Jan 10 02:00:43 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Jan 2007 04:00:43 -0300 Subject: File Closing Problem in 2.3 and 2.4, Not in 2.5 (Final report) In-Reply-To: <20070110053618.GA24572@chiclet.dreamhost.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A6D@eugsrv400.psc.pscnet.com> <7.0.1.0.0.20070109203637.0422acb8@yahoo.com.ar> <20070110053618.GA24572@chiclet.dreamhost.com> Message-ID: <7.0.1.0.0.20070110035559.03fcf550@yahoo.com.ar> At Wednesday 10/1/2007 02:36, Julio Biason wrote: >[Kinda stealing the thread] (at least a related question!) >If I use a file() in a for, how to I explicitely close the file? > > >for line in file('contents'): > print line > > >Would this work like the new 'with' statement or it will only be closed >when the GC finds it? Yes, the with statement is well suited for this: with open('contents') as f: for line in f: print line In earlier versions of Python you would write: f = open('contents') try: for line in f: print line finally: f.close() -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rzantow at gmail.com Fri Jan 19 22:33:26 2007 From: rzantow at gmail.com (rzed) Date: Fri, 19 Jan 2007 22:33:26 -0500 Subject: **argv can't work References: Message-ID: "Jm lists" wrote in news:mailman.2928.1169263231.32031.python-list at python.org: > hello members, > > See my script piece below: > > def testB(shift,**argv): > print "first argument is %s" %shift > print "all other arguments are:",argv > > testB('mails','Jen','Jen at att.com','Joe','Joe at aol.com') > > It can't work at all.please help tell me the reasons.thanks. > You have too many asterisks before argv. Use just one, like this: def testB(shift,*argv): print "first argument is %s" %shift print "all other arguments are:",argv testB('mails','Jen','Jen at att.com','Joe','Joe at aol.com') Two asterisks signifies keyword arguments, like this: def f(**c): for k,v in c.items(): print k,v f(a=1,b=2) From steve at holdenweb.com Wed Jan 10 19:03:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Jan 2007 00:03:26 +0000 Subject: what is the idiom for copy lots of params into self? In-Reply-To: <20070110234511.11447.2048857953.divmod.quotient.12511@ohm> References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> <20070110234511.11447.2048857953.divmod.quotient.12511@ohm> Message-ID: Jean-Paul Calderone wrote: > On 10 Jan 2007 14:46:54 -0800, Emin wrote: >> Dear Experts, >> >> When writing large classes, I sometimes find myself needing to copy a >> lot of parameters from the argument of __init__ into self. Instead of >> having twenty lines that all basically say something like self.x = x, I >> often use __dict__ via something like: >> >> class example: >> def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n): >> for name in >> ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']: >> self.__dict__[name] = locals()[name] >> >> This saves a lot of code and makes it easier to see what is going on, >> but it seems like there should be a better idiom for this task. Any >> suggestions? > > I use a helper, like > > http://divmod.org/trac/browser/trunk/Epsilon/epsilon/structlike.py#L35 > If you don't want to go that far then this might give you an idea or two: >>> class example: ... def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n): ... for name in inspect.getargspec(example.__init__)[0]: ... print name ... >>> x = example(1,2,3,4,5,6,7,8,9,10,11,12,13,14) self a b c d e f g h i j k l m n >>> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From webraviteja at gmail.com Tue Jan 9 02:07:17 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 8 Jan 2007 23:07:17 -0800 Subject: How to write temporary data to file? In-Reply-To: References: <1168324907.803841.79020@42g2000cwt.googlegroups.com> Message-ID: <1168326437.416524.154770@v33g2000cwv.googlegroups.com> Thomas Ploch wrote: > Ravi Teja schrieb: > > Thomas Ploch wrote: > >> Hi folks, > >> > >> I have a data structure that looks like this: > >> > >> d = { > >> 'url1': { > >> 'emails': ['a', 'b', 'c',...], > >> 'matches': ['d', 'e', 'f',...] > >> }, > >> 'url2': {... > >> } > >> > >> This dictionary will get _very_ big, so I want to write it somehow to a > >> file after it has grown to a certain size. > >> > >> How would I achieve that? > >> > >> Thanks, > >> Thomas > > > > Pickle/cPickle are standard library modules that can persist data. > > But in this case, I would recommend ZODB/Durus. > > > > (Your code example scares me. I hope you have benevolent purposes for > > that application.) > > > > Ravi Teja. > > > > Thanks, but why is this code example scaring you? > > Thomas The code indicates that you are trying to harvest a _very_ (as you put it) large set of email addresses from web pages. With my limited imagination, I can think of only one group of people who would need to do that. But considering that you write good English, you must not be one of those mean people that needed me to get a new email account just for posting to Usenet :-). Ravi Teja. From anthonydevine69 at hotmail.com Fri Jan 12 11:35:35 2007 From: anthonydevine69 at hotmail.com (tonydevlin) Date: Fri, 12 Jan 2007 08:35:35 -0800 (PST) Subject: ArchGenXML please help Message-ID: <8301441.post@talk.nabble.com> I am creating a workflow in plone using argouml and archgenxml. I have been following the steps on the site:- http://plone.org/documentation/tutorial/anonymously-adding-custom-content-types-with-argouml-and-archgenxml/creating-a-class-and-workflow-with-argouml However I am confused at step 9 in creating the class section, where it says: "Now, save this file as "ProcessImprovement.zargo". Pull up a command prompt and navigate to that directory. Make sure that you've added the ArchGenXML directory to your env path, and type the following: C:\Sandbox\Plone\Tutorial>ArchGenXML.py ProcessImprovement.zargo" I have saved the file in the location C:\Documents and Settings\Tony\Desktop\Test\ProcessImprovement.zargo However I dont know what to type in the python command prompt!!! Can anyone help my, I would be very greatful, or if I am in the wrong place do you know another forum where I could go as I have tried the plone online on and it is no good. Thank you. -- View this message in context: http://www.nabble.com/ArchGenXML-please-help-tf2966867.html#a8301441 Sent from the Python - python-list mailing list archive at Nabble.com. From ptmcg at austin.rr._bogus_.com Wed Jan 17 23:19:14 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 17 Jan 2007 22:19:14 -0600 Subject: example from the book References: <1169087861.453278.58680@a75g2000cwd.googlegroups.com> Message-ID: <45aef543$0$5176$4c368faf@roadrunner.com> "questions?" wrote in message news:1169087861.453278.58680 at a75g2000cwd.googlegroups.com... >I am a little confused by an example in python book: > > class wrapper: > def __init__(self,object): > self.wrapped=object > def __getattr__(self,attrname): > print "Trace:",attrname (<<<===) > print getattr(self.wrapped,attrname) (*) > return getattr(self.wrapped,attrname) (**) > > x=wrapper({"a":1, "b":2}) > print x.keys() (**) > > > (*) will output: > while two (**) statements together will print the keys of the > dictionary which is ['a','b'] > > why (*) doen't output the same result as (**)? > > Thanks Because the line (*) prints out the reference to a method, and the second line labeled (**) calls that method and prints that method's return value. As a hint, what does the line marked by (<<<===) print? I'm guessing it printed the attribute name 'keys'. __getattr__ didn't return the dict's keys, it returned the dict's "keys" method, which the calling code then invoked with ()'s, which invoked the wrapped object's "keys" method, which returned the wrapped object's keys, 'a' and 'b'. -- Paul From watsocd at gmail.com Mon Jan 15 19:06:34 2007 From: watsocd at gmail.com (Chuck) Date: 15 Jan 2007 16:06:34 -0800 Subject: ReportLab - Frames - Images In-Reply-To: <45AC0E9D.80104@jessikat.plus.net> References: <1168898486.300488.264920@a75g2000cwd.googlegroups.com> <45AC0E9D.80104@jessikat.plus.net> Message-ID: <1168905994.474726.46180@51g2000cwl.googlegroups.com> Thanks for the help. I made you changes but it still puts the picture above the text, not beside the text. I also found a user group at http://news.gmane.org/gmane.comp.python.reportlab.user . It may be the same. I have now posted there. Chuck From robert.kern at gmail.com Fri Jan 26 15:29:23 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 26 Jan 2007 14:29:23 -0600 Subject: Unicode error handler In-Reply-To: References: Message-ID: Rares Vernica wrote: > Is there an encode/decode error handler that can replace all the > not-ascii letters from iso-8859-1 with their closest ascii letter? No, but IBM's ICU library can transform one script to another in very flexible and capable ways. One such configuration can do what you ask. http://www-306.ibm.com/software/globalization/icu/index.jsp http://icu.sourceforge.net/userguide/Transform.html Unfortunately, I don't think any of the available ICU bindings for Python have exposed this functionality. If you wanted to contribute such, you might want to start with PyICU. It seems to be the most actively developed of the bindings. http://pyicu.osafoundation.org/ Of course, that's overkill for this problem. Those transformations can handle such things as this: ??????????? ????????? Alphab?tik?s Kat?logos The number of characters in iso-8859-1 that you would want to transliterate is not all that large. You could spend a little bit of time going through the character set and making a translation map for str.translate(). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at REMOVE.THIS.cybersource.com.au Tue Jan 16 04:53:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 16 Jan 2007 20:53:46 +1100 Subject: How to convert float to sortable integer in Python References: <1168939312.223194.184770@l53g2000cwa.googlegroups.com> Message-ID: On Tue, 16 Jan 2007 01:21:52 -0800, shellon wrote: > Hi all: > I want to convert the float number to sortable integer, like the > function float2rawInt() in java, but I don't know the internal > expression of float, appreciate your help! Google says: Your search - float2rawInt - did not match any documents. Are you sure about that function? What's a sortable integer? -- Steven. From basti.wiesner at gmx.net Tue Jan 2 11:17:37 2007 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Tue, 02 Jan 2007 17:17:37 +0100 Subject: How do I add users using Python scripts on a Linux machine References: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> <1167720155.296077.233010@42g2000cwt.googlegroups.com> <1167752161.755406.31470@v33g2000cwv.googlegroups.com> Message-ID: Ravi Teja typed > > Ivan Voras wrote: >> Ramdas wrote: >> > Well, >> > >> > I need to add users from a web interface for a web server, which >> > runs only Python. I need to add users, set quotas and in future >> > even look at managing ip tables to limit bandwidth. >> > >> > I know os.system(), but this has to be done through a form entry >> > through a web interface. >> > >> > Anyways thanks, do advise if there more pythonic solutions >> >> What you're looking for is actually a pretty complex thing. You >> *could* in theory manage /etc/passwd (and its "shadow" file) - you >> can find crypto primitives like MD5 and DES on the 'net, but note >> that you must run your script under the 'root' account in order to >> write (and even read!) the passwd database. The same goes for using >> os.system and the built-in OS utility. Be aware of security >> implications if you're running your web server under the root >> account. > > How about invoking scripts with SUID root set? Linux seems to ignore SUID bit on scripts: [lunar at nargond]-[17:03:23] >> ~/test --> cat uidtest.py #!/usr/bin/python import os print 'uid:', os.getuid() print 'effective uid:', os.geteuid() os.system('whoami') [lunar at nargond]-[17:03:28] >> ~/test --> ls -l uidtest.py -rwsr-xr-x 1 root root 112 2007-01-02 17:03 uidtest.py [lunar at nargond]-[17:03:46] >> ~/test --> /home/lunar/test/uidtest.py uid: 1000 effective uid: 1000 lunar Anyway, you should definitely think about security issues. Not all people out there are friendly... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From arkanes at gmail.com Mon Jan 8 15:52:49 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 8 Jan 2007 14:52:49 -0600 Subject: Fwd: Execute binary code In-Reply-To: <4866bea60701081251we2bf7f3vb55a285ee20e91f6@mail.gmail.com> References: <1168284300.638111.191440@38g2000cwa.googlegroups.com> <1168289145.319706.199950@11g2000cwr.googlegroups.com> <4866bea60701081251we2bf7f3vb55a285ee20e91f6@mail.gmail.com> Message-ID: <4866bea60701081252o3acf0470x4607613961da7b5e@mail.gmail.com> On 8 Jan 2007 12:45:45 -0800, citronelu at yahoo.com wrote: > Larry Bates wrote: > > > What you are asking is a virus/trojan "like" program. There's no reason > > you shouldn't be able to write the code to TEMP directory and execute it. > > > > -Larry > > > No, it is not about a trojan, but I guess it's pointless to try to > convince you otherwise. > > It's not about being able to write the code to TEMP directory and > execute it, it's about not wanting to do so. > > -Cornelius > Writing to a temp file will be at least 3 times as easy and twice as reliable as any other method you come up with. Repost. Is there any chance at all that ML could set the reply-to to the list instead of the sender? From laurent.pointal at limsi.fr Wed Jan 10 05:22:53 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 10 Jan 2007 11:22:53 +0100 Subject: convert binary data to int In-Reply-To: <1168424278.193439.216770@k58g2000hse.googlegroups.com> References: <1168424278.193439.216770@k58g2000hse.googlegroups.com> Message-ID: rubbishemail at web.de a ?crit : > Hello, > > > I need to convert a 3 byte binary string like > "\x41\x00\x00" to 3 int values ( (65,0,0) in this case). > The string might contain characters not escaped with a \x, like > "A\x00\x00" > > > Any ideas? >>> s = "\x41\x00\x00" >>> [ ord(c) for c in s ] [65, 0, 0] From bdesth.quelquechose at free.quelquepart.fr Thu Jan 18 15:41:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 18 Jan 2007 21:41:41 +0100 Subject: PyMeld for html templates? In-Reply-To: References: Message-ID: <45afd4f3$0$311$426a34cc@news.free.fr> Sean Schertell a ?crit : > I'm trying to decide which template system to get married to. I think > I've narrowed it down to PyMeld, Cheetah, or Jinja but leaning heavily > toward PyMeld because I love the idea that your templates are *totally* > clean and that get manipulated from behind the scenes. This seems to be > elegantly inline with the Sacred Creed of separation of logic from > presentation. "separating logic from presentation" is often misunderstood. It should really read "separating application logic from presentation logic", not "separating presentation logic from html code". > Of course I'm going to try them all The don't forget to have a look at Genshi and Mako too. My 2 cents... From altis at semi-retired.com Tue Jan 16 23:11:31 2007 From: altis at semi-retired.com (Kevin Altis) Date: Tue, 16 Jan 2007 20:11:31 -0800 Subject: OSCON 2007: Call for Proposals Message-ID: <45ada124$0$497$815e3792@news.qwest.net> OSCON 2007 http://conferences.oreillynet.com/os2007/ Save the date for the 9th annual O'Reilly Open Source Convention, happening July 23-27, 2007 at the Oregon Convention Center in beautiful Portland, Oregon. Call For Participation ---------------------- Submit a proposal-fill out the form at: http://conferences.oreillynet.com/cs/os2007/create/e_sess Important Dates: * The submission deadline for all proposals is February 5, 2007. * Speakers will be notified by February 26, 2007. * Final session details and speaker bios due May 20, 2007. * Tutorial materials are due June 15, 2007. * Conference: July 23-27, 2007 Proposals --------- We want to hear about your winning techniques, favorite life-savers, and the system you've made that everyone will be using next year. We'll have tracks for sessions and tutorials on Linux, PHP, Perl, Python, Ruby, Java, Databases, Desktop Applications, Web Applications (client-side and server-side), Windows, Administration, Security, and Emerging Topics. We are considering proposals for 45 minute sessions and 3 hour tutorials. We rarely accept 90 minute proposals, as most general sessions are 45 minutes in length. Your proposals are examined by a committee which draws from them and which also solicits proposals to build the program. Proposals are due by midnight (PST), Feb. 5, 2007. The OSCON Speaker Manager, Vee McMillen, emails notification of the status of your talk (accepted or otherwise) by February 26, 2007. Unless the content of your talk is particularly timely (e.g., features of a product that will be launched at OSCON), you are required to send us your slides several weeks before the conference begins. Submit proposals via the form below. http://conferences.oreillynet.com/cs/os2007/create/e_sess Don't wait until the last moment to submit your proposal for the Python track at OSCON 2007. The proposal deadline is less than three weeks away and we have a limited number of tutorial and session slots available for Python talks. From gandalf at designaproduct.biz Mon Jan 22 15:18:35 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 22 Jan 2007 21:18:35 +0100 Subject: mmap caching In-Reply-To: <45B3FDA7.9030702@v.loewis.de> References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <45B3DD4D.3010009@v.loewis.de> <1169422167.683707.264180@a75g2000cwd.googlegroups.com> <45B3FDA7.9030702@v.loewis.de> Message-ID: <45B51C1B.2000705@designaproduct.biz> > In fact, memory that is read in because of mmap should *never* cause > a MemoryError. This is certainly not true. You can run out of virtual address space by reading data from a memory mapped file. > Python calls MapViewOfFile when mmap.mmap is invoked, > at which point the operating commits to providing that much address > space to the application, along with backing storage on disk > (typically, from the file being mapped, unless it is an anonymous > map). Later access to the mapped range cannot fail (except for > hardware errors), and if it would, you wouldn't see a MemoryError. > Hmm, maybe I'm wrong. Are you sure that Windows allocates the size of the whole file in terms of memory address space? I also wrote a program before (in Delphi). That program was playing a memory mapped wave file. From the task manager, I have seen that "used memory" was growing as the program was playing the wave file. For me, this indicates that Windows extends the mapped address space in chunks. Regards, Laszlo From steve at REMOVEME.cybersource.com.au Tue Jan 30 02:47:33 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 30 Jan 2007 18:47:33 +1100 Subject: Help me understand this References: <1170140737.027139.14920@h3g2000cwc.googlegroups.com> Message-ID: On Mon, 29 Jan 2007 23:05:37 -0800, ArdPy wrote: > Hi, > > Pls tell me whats going on in the code snippet below: > >>>> n = 10 >>>> statstr = "N = ",n >>>> type(statstr) #case1 > >>>> print statstr > ('N = ', 10) >>>> print "N = ",n #case 2 > N = 10 > > In the first case the result is printed as a tuple and in the second > it appears as an ordinary string. The print statement takes one or more comma-delimited objects, and prints each one separated with a space, and then finally prints a newline. If you end the list with a comma, no newline is printed. So when you execute the line: print "N = ", n Python prints "N = ", then a space, then 10, then a newline. Outside of a print statement (and also an "except" statement), commas create tuples. So when you execute the line: statstr = "N = ", n the right-hand side is a tuple with two items. The first item is the string "N = " and the second item is the integer currently named n (in your case, 10). Do not be fooled that brackets make tuples -- they don't. With the exception of the empty tuple () which is a special case, it is commas that make tuples. So these two lines have identical effects: t = 1, 2, 3 t = (1, 2, 3) That is why these two statements print something different: print 1,2,3 print (1,2,3) In the second case, the brackets force the expression "1,2,3" to be evaluated before the print statement sees it, so the print statement sees a single argument which is a tuple, instead of three int arguments. (But notice that the brackets still aren't creating the tuple, the commas are. The brackets just change the order of evaluation.) -- Steven D'Aprano From stargaming at gmail.com Mon Jan 29 10:25:26 2007 From: stargaming at gmail.com (Stargaming) Date: Mon, 29 Jan 2007 16:25:26 +0100 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170046719.708692.243290@s48g2000cws.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> Message-ID: NoName schrieb: > Perl: > @char=("A".."Z","a".."z",0..9); > do{print join("", at char[map{rand @char}(1..8)])}while(<>); > > !!generate passwords untill U press ctrl-z > > > > Python (from CookBook): > > from random import choice > import string > print ''.join([choice(string.letters+string.digits) for i in > range(1,8)]) > > !!generate password once :( > > who can write this smaller or without 'import'? > If you really want a hack, here it is: while 1:print ''.join(__import__('random').choice(__import__('string').letters+'1234567890') for x in xrange(8)),;n=raw_input() This is a one-liner (though mail transmission may split it up), no import statements. If someone can come up with an even smaller version, feel free to post. :) -- Stargaming From jeremy+complangpython at jeremysanders.net Fri Jan 19 15:00:54 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Fri, 19 Jan 2007 20:00:54 +0000 Subject: when format strings attack References: <1169207467.989977.162940@q2g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > os.system('dir -l %s' % 'text.txt') > > > Now, there is a security risk: you might set command1 yourself, and > allow the user to set args. If command1 is an external application > with a security hole, and the user provides arguments that trigger that > bug, then naturally your application will inherit whatever security > vulnerabilities the external application suffers from. No surprises there. There are also big risks like this filename = 'foo; rm importantfile' cmd = 'ls %s' % filename os.system(cmd) oops! -- Jeremy Sanders http://www.jeremysanders.net/ From jura.grozni at gmail.com Tue Jan 16 12:07:50 2007 From: jura.grozni at gmail.com (azrael) Date: 16 Jan 2007 09:07:50 -0800 Subject: help needed for pymorph In-Reply-To: <1168963625.800116.231490@a75g2000cwd.googlegroups.com> References: <1168963625.800116.231490@a75g2000cwd.googlegroups.com> Message-ID: <1168967269.727462.230290@51g2000cwl.googlegroups.com> here is the traceback http://barok.foi.hr/~ikljaic/untitled.jpg From roland.hedberg at adm.umu.se Wed Jan 3 06:09:11 2007 From: roland.hedberg at adm.umu.se (Roland Hedberg) Date: Wed, 03 Jan 2007 12:09:11 +0100 Subject: import order or cross import In-Reply-To: References: Message-ID: <459B8ED7.4090306@adm.umu.se> Duncan Booth wrote: > > Remember that all statements in Python are executed at the time they are > encountered: there are no declarations (apart from 'global') so no looking > ahead to see what classes or functions are coming up. Yes, I've seen this time and time again. > One other complication in your particular instance: when you run a ONE.py > as a script the script is loaded in a module called '__main__', so 'import > ONE' will actually load a separate module which is NOT the same as the > __main__ module. Likewise when you run TWO.py as a script you have three > modules __main__ (loaded from TWO.py), ONE, and TWO. Hmm, that's interesting. > > The fix in this sort of case is usually to extract the base class out to a > third module. If you put BaseColor in base.py then you can safely import > that anywhere you want it. OK, so I'll go for this option. Takes some more intelligence in the marshalling code but it should be doable. > An alternative in this case would be to edit ONE.py and move the line > 'import TWO' down below the definition of BaseColor: nothing before that > actually requires TWO to have been imported yet. Since no person is involved, in creating files like ONE.py and TWO.py, this also has to be done by the marshalling code. I've no clear idea which alternative would be best/easiest but your first one seems clearer. > However, you really should try to separate scripts from modules otherwise > the double use as both __main__ and a named module is going to come back > and bite you. Oh, that was only there as an example, so you could see the intent usage. Thanks Duncan! -- Roland From jura.grozni at gmail.com Tue Jan 16 13:14:31 2007 From: jura.grozni at gmail.com (azrael) Date: 16 Jan 2007 10:14:31 -0800 Subject: help needed for pymorph In-Reply-To: References: <1168963625.800116.231490@a75g2000cwd.googlegroups.com> Message-ID: <1168971270.440015.176640@51g2000cwl.googlegroups.com> yes, in the PIL directory Dennis Lee Bieber je napisao/la: > On 16 Jan 2007 08:07:09 -0800, "azrael" > declaimed the following in comp.lang.python: > > > > > > does anyone have any idea how to fix it. > > > Well, the last line of your traceback indicates that the error is > somewhere in the PIL libraries -- do you have a _imagingtk.pyd file? > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From ljz at asfast.com Thu Jan 11 05:48:47 2007 From: ljz at asfast.com (Lloyd Zusman) Date: Thu, 11 Jan 2007 05:48:47 -0500 Subject: Joining threads but allowing signals to main thread? References: <87irfeawrj.fsf@asfast.com> <7.0.1.0.0.20070111040620.058d6cc0@yahoo.com.ar> Message-ID: <87wt3thm9c.fsf@asfast.com> Gabriel Genellina writes: > At Thursday 11/1/2007 03:43, Lloyd Zusman wrote: > >> while threading.activeCount() > 1: >> time.sleep(0.001) >> >> sys.exit(0) >> >>Is there any way to allow my program to respond to signals without >>having to busy-wait in the main thread? > > Don't worry too much, this is *not* a busy wait, because you use > sleep. You can use a longer sleep, it will be terminated by any > signal. But not too long, or the check for activeCount() will be delayed > in excess. (I use sleep(1) usually but your needs may be different) Well, if this is the best that we can currently do in python, then so be it. My sincere thanks. -- Lloyd Zusman ljz at asfast.com God bless you. From thn at mail.utexas.edu Sun Jan 28 16:21:31 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 28 Jan 2007 13:21:31 -0800 Subject: Trouble with max() and __cmp__() In-Reply-To: References: <1170017167.165222.325800@a34g2000cwb.googlegroups.com> Message-ID: <1170019291.084041.150780@h3g2000cwc.googlegroups.com> On Jan 28, 3:13?pm, Wojciech Mu?a wrote: >Define method __gt__. This works, thanks. I was a little surprised though. is __cmp__ used by any builtin functions? Thanks, THN From http Mon Jan 8 04:35:08 2007 From: http (Paul Rubin) Date: 08 Jan 2007 01:35:08 -0800 Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> <7x3b6mzwkl.fsf@ruckus.brouhaha.com> <1168189375.843789.306180@51g2000cwl.googlegroups.com> <7xps9q19wf.fsf@ruckus.brouhaha.com> <1168248244.134804.138050@51g2000cwl.googlegroups.com> Message-ID: <7xslelq2sz.fsf@ruckus.brouhaha.com> "Paul Boddie" writes: > Has this ever been reported as a bug in Python? I could imagine more > sophisticated "name mangling": something to do with the identity of the > class might be sufficient, although that would make the tolerated > "subversive" access to private attributes rather difficult. If you mean the object id, I don't think you can use it for name mangling, since the mangled names have to survive code marshalling and you may end up with different object id's. I've just never encountered any legitimate use for the "subversive" access and if it's really necessary, it's better to do it through some kind of well-designed reflection interface in the class, rather than with a crock like name mangling. From gherron at digipen.edu Mon Jan 22 18:46:21 2007 From: gherron at digipen.edu (Gary Herron) Date: Mon, 22 Jan 2007 15:46:21 -0800 Subject: How to get self reference from within a module? In-Reply-To: <3ca9bbe50701221526p4bb7cffdx767d6737bed0a6a2@mail.gmail.com> References: <3ca9bbe50701221526p4bb7cffdx767d6737bed0a6a2@mail.gmail.com> Message-ID: <45B54CCD.5000701@digipen.edu> Lavoie ?rick wrote: > Hi, > > i would like to now how to get a self reference from within a > module. The goal is to be able to generate a list of all declared > function within the module. > > Thanks, > > Erick I think this is what you're asking for: If you import a module, say import sys then sys is an object you can refer to. Like man objects in Python, you can do some ,so called, introspection. For instance you can ask for the list of all the attributes (function, classes, and such) with the vars builtin print vars(sys) That yields a dictionary of all objects in the module, from which you can access and iterate through the names (keys) and values. If you want more capabilities, you should also look at the inspect module. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From bbands at gmail.com Fri Jan 26 12:54:02 2007 From: bbands at gmail.com (BBands) Date: 26 Jan 2007 09:54:02 -0800 Subject: time series data and NumPy In-Reply-To: <51us3uF1mdcpsU1@mid.uni-berlin.de> References: <1169830757.220964.196540@m58g2000cwm.googlegroups.com> <51us3uF1mdcpsU1@mid.uni-berlin.de> Message-ID: <1169834042.396351.12660@h3g2000cwc.googlegroups.com> On Jan 26, 9:29 am, "Diez B. Roggisch" wrote: > What you could do would be to convert the date-column into a timestamp, > which is a int/long, and use that. Would that help? Actually that might help, as all I need the date for is to index values. Thanks, I'll give it a spin. jab From max at alcyone.com Tue Jan 23 15:02:40 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 23 Jan 2007 12:02:40 -0800 Subject: Overloading assignment operator In-Reply-To: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> References: <45b652fa$0$27614$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Achim Domma wrote: > I want to use Python to script some formulas in my application. The user > should be able to write something like > > A = B * C > > where A,B,C are instances of some wrapper classes. Overloading * is no > problem but I cannot overload the assignment of A. I understand that > this is due to the nature of Python, but is there a trick to work around > this? > All I'm interested in is a clean syntax to script my app. Any ideas are > very welcome. Are you sure you even need to do that? >>> class C: ... def __init__(self, x): ... self.x = x ... def __mul__(self, other): ... return C(self.x*other.x) ... >>> result = C(2)*C(3) >>> print result <__main__.C instance at 0x402e13ec> >>> result.x 6 -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Life is something to do when you can't get to sleep. -- Fran Lebowitz From greg at cosc.canterbury.ac.nz Sat Jan 27 20:18:50 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 28 Jan 2007 14:18:50 +1300 Subject: ANN: Plex 1.1.5 (Repost) In-Reply-To: References: Message-ID: (Reposting to supply the URL that I forgot to include.:-() I have released a small update to Plex to fix the problem of assignment to None causing syntax warnings or errors in Python 2.3 and later. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex What is Plex? Plex is a Python module for lexical analysis that provides similar functionality to Lex and Flex. -- Greg From risomt at gmail.com Wed Jan 31 02:23:55 2007 From: risomt at gmail.com (risomt at gmail.com) Date: 30 Jan 2007 23:23:55 -0800 Subject: PY Zip In-Reply-To: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> References: <1170220732.552072.163560@k78g2000cwa.googlegroups.com> Message-ID: <1170228235.788320.136370@m58g2000cwm.googlegroups.com> On Jan 31, 12:18 am, "GISDude" wrote: > Hi all. > > I am trying to find a module that has a Zip utility that I can use in > Python. I would like to be able to call the module and ZIP up a > directory. I thought there was such a module, but I have not been able > to find it. > > I need this to be able to be used in Python Win. Is there a ZIP utilty > already stored with a basic PYTHON download? > > Thanks all. the module is named "zipfile" (http://docs.python.org/lib/module- zipfile.html) http://docs.python.org/lib/zipfile-objects.html#zipfile-objects has more indepth information on all functions I can't say i've ever used it, but it seems pretty straightforward and mostly reminiscent of the basic read/write file modules. From gagsl-py at yahoo.com.ar Mon Jan 29 23:54:53 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Jan 2007 01:54:53 -0300 Subject: deepcopy alternative? References: <45be808e$0$27074$4c368faf@roadrunner.com> Message-ID: En Mon, 29 Jan 2007 20:17:11 -0300, <"none <"@bag.python.org> escribi?: > I have a very complex data structure which is basically a class object > containing (sometimes many) other class objects, What are "class objects"? instances of a given class, or a class itself? > function references, > ints, floats, etc. The man for the copy module states pretty clearly > that it will not copy methods or functions. I've looked around for a > while (prob just using the wrong keywords) and haven't found a good > solution. As a workaround I've been using cPickle, loads(dumps(obj)) > which is incredibly slow (~8 sec for a 1000 elem list). > > I believe the only thing stopping me from doing a deepcopy is the > function references, but I'm not sure. If so is there any way to > transform a string into a function reference(w/o eval or exec)? What do you mean by "function reference"? A module-level function works fine both with pickle and copy. Methods do not; but it's not common to take methods out of a class and put them inside a tuple, by example... > > Example > from copy import deepcopy > a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj[funcRef]) > b = deepcopy(a) > TypeError: function() takes at least 2 arguments (0 given) Please provide a *running* example. I've added some definitions, corrected some syntax errors, and this full example works for me: --- cut --- from copy import deepcopy class ClassObj(object): def __init__(self, args): self.data = args def funcRef(x): print x a = ClassObj([ClassObj([3.2, 'str', funcRef]), 4, ClassObj([funcRef])]) b = deepcopy(a) print a is b a.data.append('hello') print len(a.data), len(b.data) --- cut --- > PS: If the answer to this is in __getstate__() or __setstate__() is > there some reference to how these should be implemented besides the > library reference? Until you provide more info on your problem it's hard to tell. -- Gabriel Genellina From vgvr620034 at gmail.com Thu Jan 11 23:48:19 2007 From: vgvr620034 at gmail.com (raghu) Date: 11 Jan 2007 20:48:19 -0800 Subject: Explanation about for loop Message-ID: <1168577299.485773.8160@q2g2000cwa.googlegroups.com> can any one help me explaining for loop and its execution and its syntax with a simple example. From gagsl-py at yahoo.com.ar Mon Jan 15 18:00:24 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 20:00:24 -0300 Subject: whats wrong with my reg expression ? In-Reply-To: References: Message-ID: <7.0.1.0.0.20070115195902.05c75aa0@yahoo.com.ar> At Monday 15/1/2007 19:41, Gert Cuykens wrote: >rex2=re.compile('^"(?P[^]*)"$',re.M) [^set-of-forbidden-characters] -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From basschulte at gmail.com Wed Jan 31 14:49:14 2007 From: basschulte at gmail.com (Bas-i) Date: 31 Jan 2007 11:49:14 -0800 Subject: emulate a serial port in windows (create a virtual 'com' port) In-Reply-To: References: Message-ID: <1170272954.367718.275310@l53g2000cwa.googlegroups.com> On Jan 30, 7:34 am, Pom wrote: > how can I emulate a serial port in windows? Google for ComEmulDrv3 This may do what you want. From nogradi at gmail.com Tue Jan 23 05:25:06 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 23 Jan 2007 11:25:06 +0100 Subject: Noob Question: Force input to be int? In-Reply-To: <1169546377.017596.43840@k78g2000cwa.googlegroups.com> References: <1169546377.017596.43840@k78g2000cwa.googlegroups.com> Message-ID: <5f56302b0701230225x4da5ac21r33393668ed4bf312@mail.gmail.com> > I have a piece of code that looks like this: > > if len(BuildList) > 0: > print "The script found %d game directories:" % len(BuildList) > print > num = 0 > for i in BuildList: > print str(num) +" " + i > num = num + 1 > print > print "Select a build number from 0 to " + str(len(BuildList) - 1) > buildNum = int(raw_input('Select build #> ')) > > while buildNum > (len(BuildList) -1) or buildNum <= -1: > print > print "Error: Invalid build number!" > print "Select a build number from 0 to " + str(len(BuildList) - > 1) > print > buildNum = int(raw_input('Select build: ')) > > The problem is with the while buildNum-loop. If the user enters a > non-numeric value in the buildNum input, the scripts throws an > exception. I need to constrict the user to ONLY use integers in the > input box. How can I solve this issue? How about this: while True: try: x = int( raw_input( 'Enter an integer: ' ) ) break except: pass print 'Okay, now I have this integer: %d' % x HTH, Daniel From michael at mustun.ch Sun Jan 7 18:23:38 2007 From: michael at mustun.ch (Michael M.) Date: Mon, 08 Jan 2007 00:23:38 +0100 Subject: how to find the longst element list of lists In-Reply-To: <45a169f0$0$309$426a34cc@news.free.fr> References: <45a169f0$0$309$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > > Err... this makes three distinct lists, not a list of lists. > Sure. Logically spoken. Not in Python code. Or a number of lists. Sure not [[ bla... ] [bla.]] etc. From bearophileHUGS at lycos.com Fri Jan 19 15:29:38 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 Jan 2007 12:29:38 -0800 Subject: Iterator length In-Reply-To: References: <1169162762.997894.180320@q2g2000cwa.googlegroups.com> <1169167258.553202.190130@m58g2000cwm.googlegroups.com> <1169168139.350836.79790@s34g2000cwa.googlegroups.com> <1169211840.951796.87080@q2g2000cwa.googlegroups.com> Message-ID: <1169238578.595673.307650@l53g2000cwa.googlegroups.com> Steven D'Aprano: > since g is not an arbitrary iterator, one can easily do this: > print [(h,len(list(g))) for h,g in groupby(s)] > No need for a special function. If you look at my first post you can see that I have shown that solution too, but it creates a list that may be long, that may use a lot of of memory, and then throws it away each time. I think that's a bad solution. It goes against the phylosophy of iterators too, they are things created to avoid managing true lists of items too. > If you, the iterator > creator, know enough about the iterator to be sure it has a predictable > length, you know how to calculate it. I don't agree, sometimes I know I have a finite iterator, but I may ignore how many elements it gives (and sometimes they may be a lot). See the simple example with the groupby. Bye, bearophile From wise at hyperformix.com Thu Jan 11 18:35:27 2007 From: wise at hyperformix.com (Tim Wise) Date: Thu, 11 Jan 2007 17:35:27 -0600 Subject: py2exe: zipfile=None raised ImportError Message-ID: I clean before a compile. The exe contains all the modules (pyc) listed in the trace back message (linecache, zipextimporter, and optparse), except boot_common.py. Should that be in the exe? I'm trying to build on Windows XP using Python 2.4.4 and py2exe 0.6.5 Thanks. -- Tim Wise -----Original Message----- From: Thomas Heller [mailto:theller at ctypes.org] Sent: Thursday, January 11, 2007 2:13 PM To: Tim Wise Cc: python-list at python.org Subject: Re: py2exe: zipfile=None raised ImportError (I forgot to copy the list ;-) Tim schrieb: > > I'm at the end of my limited experience... > > > > I'm using py2exe to create an executable. I'm using bundle level 1. > > When I don't use the zipfile option, the executable and library.zip get > > created and the executable works correctly. > > > > When I add the zipfile=None option to put everything into the exe, the > > exe doesn't work. It raises an ImportError whose traceback is: > > > > File "c:\Python24\...\py2exe\boot_common.py" ... no module name linecache > > File " ... no module named zipextimporter > > File "my.py" ... no module name optparse > > > > It looks like the imported modules are not being found in the zip, or > > something didn't get included that needed to be included. > > > > Does anybody know what's happening and how to fix it? I have don't know if this helps or not, but you should better clean everything (remove the build and the dist subdirectories) when you are changing the options in the setup script and 'recompile'. Another tip: You can examine what is in the zipfile, or the exe (if using zipfile=None) when you rename the file to a *.zip file, and open it with winzip or another archiver. Thomas From gagsl-py at yahoo.com.ar Thu Jan 11 23:09:45 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 12 Jan 2007 01:09:45 -0300 Subject: Python nuube needs Unicode help In-Reply-To: <1168558927.031778.240940@i56g2000hsf.googlegroups.com> References: <1168550858.233814.292900@p59g2000hsd.googlegroups.com> <50nv1uF1hje7oU1@mid.uni-berlin.de> <1168558927.031778.240940@i56g2000hsf.googlegroups.com> Message-ID: <7.0.1.0.0.20070112010621.0597d950@yahoo.com.ar> At Thursday 11/1/2007 20:42, gheissenberger at gmail.com wrote: > Progress! You managed to change the error message. > > File "./acc_test_script_generator.py", line 106, in loadData > print u.encode('utf-8') >AttributeError: Utterance instance has no attribute 'encode' > >I'm missing somethign really obvious here, but I don't know what it >is... Then you're not "printing a line from a file we are parsing", which should be a string or unicode object. You're printing some "Utterance" instance; probably it has a __str__ method, and there, you're mixing unicode+strings. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From adonis at REMOVETHISearthlink.net Sun Jan 28 22:19:53 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Mon, 29 Jan 2007 03:19:53 GMT Subject: Ip address In-Reply-To: References: Message-ID: Scripter47 wrote: > How do i get my ip address? > > in cmd.exe i just type "ipconfig" then it prints: > ... > IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 > ... > how can i do that in python?? > If you want to get your external IP you can do: import urllib checkIP = urllib.urlopen("http://checkip.dyndns.org").read() externalIP = checkIP.split()[-1].strip("") print externalIP Hope this helps. Adonis From gandalf at designaproduct.biz Fri Jan 5 12:01:38 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 05 Jan 2007 18:01:38 +0100 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: <459E8472.4010000@designaproduct.biz> W. Watson wrote: > What do I download to use Python with MX XP Pro on an ASUS 4 year old > motherboard? I would guess a good book source for starters would be the > O'Reilly book. > You mean Microsoft XP Pro? For a beginner, the motherboard does not really matter. First of all, you should download Python itself: http://www.python.org/download/ or more probably: http://www.python.org/ftp/python/2.5/python-2.5.msi Then you should download a good editor. There are many, listed here: http://wiki.python.org/moin/PythonEditors Under Windows, for a beginner, I would recommend pythonwin, but you can decide. Finally, you can start practicing. A book is always good. You can read online tutorials too: http://docs.python.org/tut/ http://www.awaretek.com/tutorials.html Regards, Laszlo From wolf_tracks at invalid.com Wed Jan 24 16:02:54 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Wed, 24 Jan 2007 21:02:54 GMT Subject: Python Windows Editors In-Reply-To: References: <1169415514.562496.248950@a75g2000cwd.googlegroups.com> Message-ID: <2QPth.66061$qO4.59545@newssvr13.news.prodigy.net> Hertha Steck wrote: > Am Mon, 22 Jan 2007 00:33:12 +0000 schrieb W. Watson: > >> mensanator at aol.com wrote: >>> W. Watson wrote: >>>> I downloaded python-2.5.msi and installed it. I believe its editor is IDE. I >>>> understand there's a Win editor called pythonwin. I believe it's in the >>>> download pywin32-210.win32-py2.5.exe, but I'm not sure if this exe file has >>>> just the editor or all of Python. Comments? If not how do I get the >>>> PythonWin editor by itself? > > By "IDE" you mean IDLE, don't you? > >>> Print your files from Notepad, after all, they're just text files. >>> But IDLE has more usefull Formatting options. >> Thanks. Already did it, but used Word. I can get line numbers in that way. > > And you are absolutely certain you won't never, ever, detect a typo when > you have your script open in Word, correct it, save the file and try to > use the resulting mess as a Python script? Or does Word leave it as a text > file in such a case? I never dare to open source code in Word, so I'm not > really sure. > > Hertha > Yes, looking at it again, it's IDLE in my Start (Programs) menu. When I put it into Word, I print the document with line #s and then mark up the listing. I never try to use a Word doc in Python. Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "Depend upon it, there is nothing so unnatural as the commonplace." -- Sherlock Holmes, in "A Case of Identity" -- Web Page: From gagsl-py at yahoo.com.ar Fri Jan 5 06:08:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 08:08:57 -0300 Subject: Memoization in Python In-Reply-To: References: Message-ID: <7.0.1.0.0.20070105074253.03abd3c8@yahoo.com.ar> At Friday 5/1/2007 06:50, Alec Mihailovs wrote: >Following Antti Karttunen suggestion, I wrote the following simple decorator >for creating functions with cache (something like 'option remember' in >Maple). Just wanted to share it: Nice. There is already a memoize decorator in the Python wiki: http://wiki.python.org/moin/PythonDecoratorLibrary, you can get some ideas from there. Using the functools module (2.5) or the decorator module by M. Simoniato (http://www.phyast.pitt.edu/~micheles/python/documentation.html) you can improve it so the decorated function looks more like the original. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jtravs at gmail.com Wed Jan 10 03:36:26 2007 From: jtravs at gmail.com (jtravs at gmail.com) Date: 10 Jan 2007 00:36:26 -0800 Subject: distutils and ctypes In-Reply-To: <45A48ACE.9000404@v.loewis.de> References: <1168368375.380664.100460@i56g2000hsf.googlegroups.com> <45A3FF17.2070509@v.loewis.de> <45a41b1f$0$19653$9b622d9e@news.freenet.de> <45A48ACE.9000404@v.loewis.de> Message-ID: <1168418186.490383.148470@p59g2000hsd.googlegroups.com> Martin v. L?wis wrote: > Robert Kern schrieb: > > To which I say that doing the type-checking and error handling is much easier in > > Python than using the C API. Add to that the tediousness of the edit-compile-run > > cycle of C and the finickiness of refcounting. > > Sure: edit-compile-run is tedious, but in the given case, it is > necessary anyway. Also, refcounting is finicky, but with ctypes, > you often have to use just as finicky memory management APIs. > (such as using specific allocation and deallocation routines, > or having to do memory management at all when in C you would > do stack allocation). > > My main concern with ctypes is that you have to duplicate > information from the header files, which is error-prone, > especially when the header files may change (either across > versions or across target systems). > I have looked at: building an extension module, using pyrex and using ctypes. Initially ctypes won because I was under the impression that to use pyrex or build an extension module required the same compiler as python was compiled with. This is not a problem on linux, but under windows this is much too great a problem for potential users (who will also need to compile the module). I now have discovered that I can use mingw32 (without patching) under windows (with python2.5) though I'm not clear if this is by chance or has been implemented as a new feature (can't find suitable documentation). Anyway, at this point I think I will stick with ctypes purely out of simplicity. My c library is for some legacy lab hardware control. I only need to call three functions. With ctypes, I can check the data in python (which I do anyway to validate it) and pass it onto the library in about 10 lines of code. Writing an extension module I believe would be much more difficult. Anyway, Thanks both for your help. John From gagsl-py at yahoo.com.ar Fri Jan 26 13:56:17 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 26 Jan 2007 15:56:17 -0300 Subject: how to remove c++ comments from a cpp file? References: <1169801197.941449.303000@v33g2000cwv.googlegroups.com><1169805244.879280.235660@v45g2000cwv.googlegroups.com><45ba1cfe$0$5084$ba4acef3@news.orange.fr> Message-ID: "Peter Otten" <__peter__ at web.de> escribi? en el mensaje news:epd751$518$03$1 at news.t-online.com... > Laurent Rahuel wrote: > >> And using the codecs module > > Why would you de/encode at all? I'd say the otherwise: why not? This is the recommended practice: decode inputs as soon as possible, work on Unicode, encode only when you write the output. In this particular case, it's not necesary and you get the same results, only because these two conditions are met: - the encoding used is utf-8 - we're looking for '//', and no unicode character contains '/' in its representation using that encoding apart from '/' itself Looking for the byte sequence '//' into data encoded with a different encoding (like utf-16 or ucs-2) could give false positives. And looking for other things (like '??') on utf-8 could give false positives too. The same applies if one wants to skip string literals looking for '"' and '\\"'. Anyway for a toy script like this, perhaps it does not make any sense at all - but one should be aware of the potential problems. -- Gabriel Genellina From ptmcg at austin.rr.com Sat Jan 27 14:26:46 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Jan 2007 11:26:46 -0800 Subject: extracting from web pages but got disordered words sometimes In-Reply-To: <1169896727.567159.239160@a34g2000cwb.googlegroups.com> References: <1169896727.567159.239160@a34g2000cwb.googlegroups.com> Message-ID: <1169926006.739252.57360@p10g2000cwp.googlegroups.com> After looking at the pyparsing results, I think I see the problem with your original code. You are selecting only the characters after the rightmost "-" character, but you really want to select everything to the right of "- -". In some of the titles, the encoded Chinese includes a "-" character, so you are chopping off everything before that. Try changing your code to: title=full_title.split("- -")[1] I think then your original program will work. -- Paul From jonc at icicled.net Thu Jan 18 13:58:04 2007 From: jonc at icicled.net (Jonathan Curran) Date: Thu, 18 Jan 2007 12:58:04 -0600 Subject: spidering script In-Reply-To: <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d@fdn.com> References: <8N6dnSE2eO6QKDLYnZ2dnUVZ_uejnZ2d@fdn.com> Message-ID: <200701181258.04264.jonc@icicled.net> On Thursday 18 January 2007 11:57, David Waizer wrote: > Hello.. > > I'm looking for a script (perl, python, sh...)or program (such as wget) > that will help me get a list of ALL the links on a website. > > For example ./magicscript.pl www.yahoo.com and outputs it to a file, it > would be kind of like a spidering software.. > > Any suggestions would be appreciated. > > David David, this is a touchy topic but whatever :P Look into sgmllib, and you can filter on the "A" tag. The book 'Dive Into Python' covers it quite nicely: http://www.diveintopython.org/html_processing/index.html Jonathan From john.pye at gmail.com Thu Jan 25 18:53:27 2007 From: john.pye at gmail.com (John Pye) Date: 25 Jan 2007 15:53:27 -0800 Subject: Catching floating point errors from linked C code In-Reply-To: References: <1169696243.262973.188540@s48g2000cws.googlegroups.com> <1169702669.027065.65990@v33g2000cwv.googlegroups.com> Message-ID: <1169769207.261208.241560@a34g2000cwb.googlegroups.com> Hi John I think you're right, and I need to place FPE 'brackets' around my code. The thing that was confusing me was that python has division by zero exceptions (for which I assumed fenv.h was being used), but when from python I reach down into my SWIG code and do a 1/0, no SIGFPE is thrown. I will experiment with the _controlfp stuff (and linux equivs) and see how it goes. Thanks for your help. Cheers JP On Jan 25, 5:12 pm, John Nagle wrote: > John Pye wrote: > > Hi John, > > > On Jan 25, 3:43 pm, John Nagle wrote: > > >>Python is probably running with floating point exceptions disabled, > >>but you can enable them in your C code, and restoring the floating > >>point mode when you leave, if you want. This is probably > >>only worth doing under a debugger, because otherwise you just end > >>up with an aborted instance of Python. > > > So as far as you know, Python doesn't switch stuff like > > feenableexcept(FE_EXCEPT_ALL)? Does Python use the > > internally, or are all its FPEs detected by explicit checks beforehand? I have no idea what state Python leaves the FPU in, but whatever > the state is, you can read it, set your own state, and restore > the previous state before returning to Python. > > The last time I had to do this, I used > > unsigned int oldstate = // make almost all FPU errors fatal > _controlfp ((~_EM_INVALID) & _CW_DEFAULT, _MCW_EM); > ... > _controlfp(oldstate); // restore old state > > on Windows 2000. > > John Nagle From Barry.Carroll at psc.com Thu Jan 25 13:41:44 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 25 Jan 2007 10:41:44 -0800 Subject: Overloading assignment operator Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595AA6@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: Gabriel Genellina [mailto:gagsl-py at yahoo.com.ar] > Sent: Tuesday, January 23, 2007 9:24 PM > To: python-list at python.org > Subject: Re: Overloading assignment operator > > "Carroll, Barry" escribi? en el mensaje > news:2BBAEE949D384D40A2B851287ADB6A4304595AA4 at eugsrv400.psc.pscnet.com... > > > * ... the assignment operator is used to assign an > > * object to a name in the current namespace... IOW, you cannot "overload > > * the assignment operator." > > (wesley chun) > This is the key concept, if you want to be able to "see" assignments, you > should work with a namespace (a dictionary is enough...) > > > * result = property(get_result, set_ result, doc='result of operations') > > > > I have tested this using the admittedly simple-minded code snipped > > below. <> > Notice that you can delete ALL those lines of code, leaving a bare: > > class Aclass: passs > > and you will get EXACTLY the same results. In this case -and this are not > my > words- properties are a waste of programmer time, processor time and disk > space. > Of course properties are very useful, but when you need to do something > "more" than just storing and retrieving a single value. > > -- > Gabriel Genellina Greetings: Gabriel is right, and my definitions of get_result and set_result were deficient. Something like this would have been better: * def get_result(self): * do_stuff_before_returning(self) * return self.__result * * def set_result (self, expression): * do_stuff_before_storing(self, expression) * self.__result = expression * Achim didn't go into the details of his result class(es), so I don't know what the do_stuff_* functions would actually do. Sorry for the omission. Regards, Barry From __peter__ at web.de Thu Jan 18 02:46:32 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Jan 2007 08:46:32 +0100 Subject: generate tuples from sequence References: <1169037661.987259.106790@v45g2000cwv.googlegroups.com> Message-ID: Alan Isaac wrote: > "Peter Otten" <__peter__ at web.de> wrote in message > news:eol9ac$v3l$02$1 at news.t-online.com... >> I like >> >> >>> items = range(9) >> >>> N = 3 >> >>> zip(*[iter(items)]*N) >> [(0, 1, 2), (3, 4, 5), (6, 7, 8)] > > Except that it is considered implementation dependent: > http://mail.python.org/pipermail/python-list/2005-February/307550.html Use itertools.izip() then instead of zip(). I think that the occurence of this idiom on the examples page counts as a blessing :-) But still, to help my lack of fantasy -- what would a sane zip() implementation look like that does not guarantee the above output? Peter From Jstone at 3web.com Wed Jan 31 15:54:30 2007 From: Jstone at 3web.com (JoJo) Date: Thu, 1 Feb 2007 04:54:30 +0800 Subject: How to sort using hash's key? Message-ID: <1170276870.45c102069d9e6@webmail.3web.com> Hello, I want to sort a dict via its key,but I have no idea on how to do it. Please help me,thanks. --------------------------------------------------------------------------- 3webXS HiSpeed Dial-up...surf up to 5x faster than regular dial-up alone... just $14.90/mo...visit www.get3web.com for details From ian.inglis at gmail.com Thu Jan 18 11:58:39 2007 From: ian.inglis at gmail.com (Cruelemort) Date: 18 Jan 2007 08:58:39 -0800 Subject: Catching wx events References: <1169129536.879657.113130@v45g2000cwv.googlegroups.com> Message-ID: <1169139519.586990.219110@q2g2000cwa.googlegroups.com> Chris Mellon wrote: > On 18 Jan 2007 06:12:17 -0800, Cruelemort wrote: > > Hello all, > > > > I am new to this group (and new to Python) and was hoping someone would > > be able to help me with something, it is not so much a problem it is > > more of a general interest query about something i have a solution too > > but am not sure it is the correct one. > > > > I have a class that contains a string ID and a name, and a list > > containing a few objects of this type, i need to loop through this list > > and create a button for each object (with the name as the label) i have > > done this with the following code - > > > > for chan in self._channellist: > > channelbutton = wx.Button(self, id=-1, > > label=chan.getName()) > > > > channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged) > > > > My question is this - in the _channelChanged method, how do i know > > which button has been pressed when i enter the channel changed method, > > and so how do i retrieve the appropriate object depending on which > > button has been pressed? > > > > I have potentially solved this problem using the UserData property in a > > sizer, i have added all the buttons to a sizer for display purposes and > > so SizerItem objects have been created, i can then set the original > > object to the UserData object by putting the following line of code in > > the loop > > > > sizeritem = > > self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan) > > > > This way i can retrieve the item in the _channelChanged method with the > > following - > > > > def _channelChanged(self, event): > > eventobj = event.GetEventObject() > > chan = self.topsizer.GetItem(eventobj).GetUserData() > > > > > > This works fine but by looking at the API it would appear the UserData > > property is not really designed for this use ("userData - Allows an > > extra object to be attached to the sizer item, for use in derived > > classes when sizing information is more complex than the proportion and > > flag will allow for"). > > > > Another option would be to derive my own Button class and include the > > object in there. > > > > Any advice on the best way to solve this problem would be appreciated. > > > > Exactly how I would do it depends on the rest of the application. I > would probably derive my own button - never be afraid to subclass. > > You could also generate the buttons IDs up front, and maintain a > mapping between the IDs and the channels, like so: > > self.mapper = {} > for channel in self.channels: > id = wx.NewId() > self.mapper[id] = channel > channelbutton = wx.Button(self, id=id, label=channel.getName()) > > > def channelChanged(self, event): > channel = self.mapper[event.Id] > > > You could also use closures (lambdas or via a factory function) to > bind the channel at the time you create the button: > > for channel in self.channels: > channelbutton = wx.Button(self, label=channel.getName()) > self.Bind(wx.EVT_BUTTON, lambda event: > self.channelChanged(channel), source=channelbutton) > > def channelChanged(self, channel): > print "Channel changed to ", channel.getName() Two good ideas, i used the mapping system, works and seems like a slightly more elegant way of doing things. Many thanks! Ian From Bulkan at gmail.com Tue Jan 16 07:07:50 2007 From: Bulkan at gmail.com (placid) Date: 16 Jan 2007 04:07:50 -0800 Subject: Projects anyone? Message-ID: <1168949268.618793.102890@l53g2000cwa.googlegroups.com> Hi all, I'm looking for anyone who is working on a project at the moment that needs help (volunteer). The last project i worked on personally was screen-scraping MySpace profiles (read more at the following link) http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles but that didn't go all to well, so im kinda bored and need something to do, with Python. So any suggestions anyone? Cheers From __peter__ at web.de Mon Jan 22 02:42:40 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Jan 2007 08:42:40 +0100 Subject: class explorer for automating IE References: <1169448532.869501.190530@v45g2000cwv.googlegroups.com> <1169449585.832667.325370@11g2000cwr.googlegroups.com> Message-ID: John wrote: > Is there an analogue of IE Mechanize in python? http://www.google.com/search?q=python%20mechanize&btnI=I%27m+Feeling+Lucky From nobody at localhost.localdomain Fri Jan 12 06:56:43 2007 From: nobody at localhost.localdomain (Steven Wayne) Date: Fri, 12 Jan 2007 05:56:43 -0600 Subject: Learning Python book, new edition? References: Message-ID: On Fri, 12 Jan 2007 22:44:33 +1100, Steven D'Aprano wrote: > On Fri, 12 Jan 2007 04:50:21 -0600, Steven Wayne wrote: > > [snip stupid disclaimer and response to it] > >> Unlawful how? You've already given permission for an "agent responsible >> for delivering the message" to broadcast it around the world. >> >> Sorry for the rant, but I'm an email admin and I've just been told about >> the change to UK law. > > What change to UK law? http://www.theregister.co.uk/2006/12/21/new_web_email_regulation/ Steven -- .''`. : :' : `. `'` `- From akhavr at kds.com.ua Wed Jan 17 11:00:23 2007 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Wed, 17 Jan 2007 18:00:23 +0200 Subject: Python Web Frameworks References: <1169048071.353887.279160@q2g2000cwa.googlegroups.com> Message-ID: Shortash, "S" == Shortash wrote: S> I want to build a Python web app but im not sure which one to go for. I S> prefer something like asp.Net , which would allow me to fully seperate S> the presentation layer from the logic. Please advise? Django? http://www.djangoproject.com -- Andrey V Khavryuchenko Software Development Company http://www.kds.com.ua/ From ruan at jcmills.com Wed Jan 31 12:09:21 2007 From: ruan at jcmills.com (Dongsheng Ruan) Date: Wed, 31 Jan 2007 12:09:21 -0500 Subject: What is the dummy statement that do nothing in Python? References: <4ccf86300701310904s3d6c7aecscc31644cc84dade7@mail.gmail.com> Message-ID: <008601c7455a$8d6f8e20$0300000a@HPLaptop> Yes, that's just what I want. Thanks! ----- Original Message ----- From: Analog Kid To: Dongsheng Ruan Cc: python-list at python.org Sent: Wednesday, January 31, 2007 12:04 PM Subject: Re: What is the dummy statement that do nothing in Python? hey dongsheng: not too sure what you are looking for ... but i guess a simple "pass" statement should do it ... if a > b: pass hth, -ajay On 1/31/07, Dongsheng Ruan wrote: I remember that in python there is some kind of dummy statement that just holds space and does nothing. I want it to hold the place after a something like if a>b: do nothing I can't just leave the space blank after if statement because there will be error message. Does anybody know what to insert there? Thanks! -- http://mail.python.org/mailman/listinfo/python-list -- BBQ - "Spare (My) Ribs" being contemplated -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Wed Jan 10 01:31:20 2007 From: nagle at animats.com (John Nagle) Date: Wed, 10 Jan 2007 06:31:20 GMT Subject: Wierd M2Crypto bug - phony "peer did not return certificate" error Message-ID: Here's a wierd problem: I have a little test case for M2Crypto, which just opens up SSL connections to web servers and reads their certificates. This works fine. But if I execute socket.setdefaulttimeout(5.0) so that the sockets don't wait too long if there's no SSL server, I get a "peer did not return certificate" exception every time. Environment: Windows 2000 SP 4 M2Crypto: M2Crypto-0.17.win32-py2.4.exe Python: Python 2.4.4 (#71, Oct 18 2006, 08:34:43) OpenSSL: Win32 OpenSSL v0.9.8d Notes: Running M2Crypto does NOT use the version of OpenSSL that comes with Python. You have to install OpenSSL separately, or M2Crypto's DLL won't find the OpenSSL DLLS. There's a good chance that this may be related to: [ python-Bugs-1098618 ] socket.setdefaulttimeout() breaks smtplib.starttls() But that should have been fixed in Python 2.4.4, right? Or did that patch not make it in? John Nagle (And no, I can't run Python 2.5, because MySQLdb support doesn't work for 2.5 yet.) From gagsl-py at yahoo.com.ar Fri Jan 5 09:12:18 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Jan 2007 11:12:18 -0300 Subject: CPU management In-Reply-To: <00ce01c730bf$cca10560$a5059296@IBM75CFA6491AB> References: <00ce01c730bf$cca10560$a5059296@IBM75CFA6491AB> Message-ID: <7.0.1.0.0.20070105103802.05c9cd08@yahoo.com.ar> At Friday 5/1/2007 08:51, Fulvio D'Antonio wrote: >I usally develop a lot of expensive (in terms of CPU usage) >algorithms. I would like to develop something that allows my >application to run quietly all day long with a little CPU usage, so >that I can work in the meanwhile! >I'm running Python2.4 on Windows XP. Call the function SetPriorityClass; documentation is on msdn.microsoft.com -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Thu Jan 11 17:19:42 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Jan 2007 19:19:42 -0300 Subject: IDLE Python and Environment Variables In-Reply-To: <1168526728.313917.309340@o58g2000hsb.googlegroups.com> References: <1168482248.828858.161320@i39g2000hsf.googlegroups.com> <1168526728.313917.309340@o58g2000hsb.googlegroups.com> Message-ID: <7.0.1.0.0.20070111191636.01d6cd48@yahoo.com.ar> At Thursday 11/1/2007 11:45, Tristan wrote: >I considered to use it, thanks!! Incidentally (beg your pardon if it >sounds to ignorance), can I define Environment variables in a config >file and then apply to my python program? Yes, read them from the config file and then use os.environ['name']=value See http://docs.python.org/lib/os-procinfo.html -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From berteun at gmail.com Mon Jan 22 04:48:05 2007 From: berteun at gmail.com (Berteun Damman) Date: 22 Jan 2007 01:48:05 -0800 Subject: PQueue and Python 2.5 In-Reply-To: References: <1169216890.617239.209170@51g2000cwl.googlegroups.com> Message-ID: <1169459285.031773.108620@v45g2000cwv.googlegroups.com> Gabriel Genellina wrote: > Python got in 2.3 a heapq module in its standard library; I think it is what > Ah! then I bet: > - There is some C code involved. > - It carelessly mixes PyMem_Malloc with PyObject_Free or similar as > described in > http://docs.python.org/whatsnew/ports.html > > So do yourself a favor and forget about such old piece of code... I would be happy to do so, but it does suit my needs quite well. :) But everybody thanks for pointing out the probable cause, I never did anything with C-extentions before, so I wasn't aware of the 2.5 changes. But I'll look into the code. Berteun From watsocd at gmail.com Mon Jan 15 17:01:28 2007 From: watsocd at gmail.com (Chuck) Date: 15 Jan 2007 14:01:28 -0800 Subject: ReportLab - Frames - Images Message-ID: <1168898486.300488.264920@a75g2000cwd.googlegroups.com> I have been trying all day to get this to work. My complete code is below. I can get my text into the PDF, I can get my image in the PDF. What I can't get to work is frames so that the image (logo) appears to the right of the text. The image always appears first and then the text below on the next line. Please help. Chuck *************** CUT *********************** from reportlab.pdfgen import * from reportlab.platypus import * from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate from reportlab.platypus import flowables from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY from reportlab.lib.pagesizes import letter #precalculate some basics top_margin = letter[1] - inch bottom_margin = inch left_margin = inch right_margin = letter[0] - inch frame_width = right_margin - left_margin def bill(canvas, doc): canvas.saveState() canvas.restoreState() def run(): doc = [] from reportlab.lib.styles import ParagraphStyle from reportlab.platypus import Image pdf = SimpleDocTemplate('bill2.pdf', pagesize = letter) #need a style normal = ParagraphStyle('normal') doc.append(Image("pic.jpg", 100, 71)) #Logo para = Paragraph("Some text1", normal) doc.append(para) para = Paragraph("Some text2", normal) doc.append(para) para = Paragraph("Some text3", normal) doc.append(para) para = Paragraph("Some text4", normal) doc.append(para) para = Paragraph(" ", normal) doc.append(para) doc.append(HRFlowable(color="black", thickness=3, width="100%")) pdf.build(doc,bill) run() *************************** CUT *********************************** From jzgoda at o2.usun.pl Thu Jan 25 16:22:10 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 25 Jan 2007 22:22:10 +0100 Subject: Python does not play well with others In-Reply-To: References: Message-ID: Harry George napisa?(a): > You experience isn't shared by everyone. Some of us find Python the > most functional and portable of the candidates you mention. The point on MySQLdb is rather common, many people who used it with SQLObject will confirm. Fortunately for MySQLdb, the MySQL on its own is much worse. Fortunately for us, the MySQLdb library is not a part of Python distribution, so Python can not be blamed for its deficiencies. ;) -- Jarek Zgoda http://jpa.berlios.de/ From bruno.desthuilliers at websiteburo.com Thu Jan 25 07:31:25 2007 From: bruno.desthuilliers at websiteburo.com (Bruno Desthuilliers) Date: Thu, 25 Jan 2007 13:31:25 +0100 Subject: While loop with "or"? Please help! In-Reply-To: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> Message-ID: <45b8a31d$0$2401$426a74cc@news.free.fr> wd.jonsson at gmail.com a ?crit : > Hmm, my while loop with "or" doesn't seem to work as I want it to... > How do I tell the while loop to only accept "Y" or "y" or "N" or "n" > input from the str(raw_input)? > > Thank's in advance! > > Snippet of code: > > import os > > def buildfinder(): > os.system("CLS") > GameRoot = os.getenv("GAME_ROOT") + "\\" > > print "Do you want to use " + GameRoot + " as your source > directory?" > usr = str(raw_input('Y/N: ')) > return usr > > #Runs the buildfinder function > usrinp = buildfinder() > > def buildwhiler(): > > while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM Yes, obviously. The above reads as: while (usrinp != "y") or ("Y") or ("N") or ("n"): What you want is something like: while usrinp != "y" and usrinp != "Y" \ and usrinp != "n" and usrinp != "N" : which is better written as while not (usrinp == "y" or usrinp == "Y" \ or usrinp == "n" or usrinp == "N") : which can be simplified using str.lower: while not (usrinp.lower() == "y" or usrinp.lower() == "n"): and simplified again thanks to Python 'in' operator: while not usrinp.lower() in "yn": > print "Enter Y or N!" > usr = str(raw_input('Y/N: ')) > else: > code continues While we're at it, there are other problems in your code. One of them is that buildwhiler() will go in an infinite loop if the usr first typed anything else than "y", "Y", "n" or "N". I let you try to find out why, and just give you two hints : - globals are Bad(tm) - don't mix application logic with user-interface logic (ie: a function should only deal with one or the other, not mix both). HTH From sergey at fidoman.ru Wed Jan 24 11:02:28 2007 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Wed, 24 Jan 2007 19:02:28 +0300 Subject: module email Message-ID: Hello. Why does not work? -------------- import email.message import smtplib import time m=email.message.Message() m.set_type("multipart/mixed") m["From"]="Sergey Dorofeev " m["To"]="Sergey Dorofeev " m["Date"]=time.asctime() m["Subject"]="test" p1=email.message.Message() p1.set_payload("message text", "us-ascii") m.attach(p1) p2=email.message.Message() p2.set_payload("message text 2", "us-ascii") m.attach(p2) del p1,p2 print m.as_string() print "*"*50 x=email.message.Message() x.set_type("multipart/mixed") x["From"]="Sergey Dorofeev " x["To"]="Sergey Dorofeev " x["Date"]=time.asctime() x["Subject"]="test" p1=email.message.Message() p1.set_payload("message text !", "us-ascii") print p1 x.attach(p1) p2=email.message.Message() p2.set_type("message/rfc822") p2.set_payload(m) print p2 x.attach(p2) print "*"*50 print x.as_string() -------------- I'm using Python 2.5 From rubbishemail at web.de Wed Jan 10 05:38:23 2007 From: rubbishemail at web.de (rubbishemail at web.de) Date: 10 Jan 2007 02:38:23 -0800 Subject: convert binary data to int In-Reply-To: References: <1168424278.193439.216770@k58g2000hse.googlegroups.com> Message-ID: <1168425503.067695.31080@p59g2000hsd.googlegroups.com> [ord(x) for ...] perfect, thank you Daniel From MI5Victim at mi5.gov.uk Thu Jan 4 02:25:54 2007 From: MI5Victim at mi5.gov.uk (MI5Victim at mi5.gov.uk) Date: 4 Jan 2007 07:25:54 GMT Subject: MI5 Persecution: Counter-surveillance sweep by Nationwide Investigations Group Message-ID: Counter-surveillance sweep by Nationwide Investigations Group In July 1994 the private detective agency Nationwide Investigations Group conducted an electronic counter-surveillance sweep of my parents' home in London. They checked for radio transmitter devices, and tested the telephone line for attached bugs. They found nothing. I am afraid that I was unsurprised at their not finding any evidence of covert surveillance. It had been made very clear to me, particularly during 1990-92, that audio, and almost certainly video, surveillance of my parents' home was taking place. But this would not have been made quite so obvious unless the persecutors were confident of their apparatus being undetectable using the technology the police, or a private agency like Nationwide, would be using. I don't know very much about the surveillance technology that has been used against me, but I understand that devices can be built which switch off on receiving a coded command, and may switch on again after a counter- surveillance sweep has completed; that devices may rapidly alter the frequency of transmission, "frequency-hopping" devices which presumably cannot be detected in a sequential scan of the sort employed by Nationwide; and of course "probe" microphones can be inserted "through-the-wall", although I hesitate to believe our neighbours would permit this. We paid Nationwide ?411.25 (including VAT) for the surveillance sweep, which took them about an hour and a half to complete, using a "Professional 5000 multi-scanner, CCL UHF scanner and Guideline telephone tap detector." As I said above, I don't know very much about these things, so I can't comment on the capabilities or otherwise of this equipment. But clearly the "watchers" are using technology which in 1994 was beyond the detection capabilities of a good private detective agency. 386 From paul at boddie.org.uk Thu Jan 18 05:39:36 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 18 Jan 2007 02:39:36 -0800 Subject: Distributed computation of jobs References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> <1169046239.405261.81740@m58g2000cwm.googlegroups.com> Message-ID: <1169116776.675766.50320@l53g2000cwa.googlegroups.com> robert wrote: > > as many libs are restriced to certain OS'es, and/or need/rely on > extension modules, few tags would probably improve: OS'es, > pure-python, dependeniess I've added some platform notes, although the library dependencies of various MPI and PVM solutions are sort of obvious, but I'll get round to adding those at some point unless you beat me to it. ;-) Paul From goodidea1950 at hotmail.spam.com Sat Jan 27 20:53:47 2007 From: goodidea1950 at hotmail.spam.com (AKA gray asphalt) Date: Sat, 27 Jan 2007 17:53:47 -0800 Subject: Do I need Python to run Blender correctly? References: <5%4uh.75582$wP1.6882@newssvr14.news.prodigy.net> Message-ID: "John Nagle" wrote in message news:5%4uh.75582$wP1.6882 at newssvr14.news.prodigy.net... > AKA gray asphalt wrote: >> I downloaded Blender but there was no link for python. Am I on the right >> track? > > Blender doesn't require Python, but if you have Python, you can > write plug-ins for Blender. Get "The Blender Book"; otherwise > you'll never figure Blender out. > > John Nagle I'm thinking about not upgrading "Strata 3D" because it still doesn't export textures with obj files and it just created an undo of more than one action, believe it or not... Am I expectiong too much of a $400+ program, to export textures with obj files? Does Blender do this? I see the BBook on Amazon for $30. That's probably my best bet, no? From aahz at pythoncraft.com Wed Jan 31 12:40:40 2007 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2007 09:40:40 -0800 Subject: how to "free" an object/var ? References: Message-ID: In article , John Nagle wrote: >Steven D'Aprano wrote: >> On Tue, 30 Jan 2007 15:48:37 -0800, James Stroud wrote: >> >> >>>Stef Mientki wrote: >>> >>>>If I create a large array of data or class, >>>>how do I destroy it (when not needed anymore) ? > > If your data structure has no backlinks, it will go away >as soon as the last reference to it disappears. If your >data structure has backlinks, it will hang around until >garbage collection runs. If your backlinks are >weak references (see "weakref"), the data structure will >be released much sooner. Note that exceptions create links. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM From duncan.booth at invalid.invalid Fri Jan 12 06:06:29 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Jan 2007 11:06:29 GMT Subject: Learning Python book, new edition? References: Message-ID: Steven Wayne wrote: > Don't take this the wrong way, but this isn't an email, it's a usenet > posting. It is now, but it started as an email. If you examine its headers he sent it to the list but the list administrator had set up software up to copy the email to a newsgroup. Fortunately, as you said, the email gave him permission to do that otherwise the entire legal profession might have collapsed under its own weight. From joshua at eeinternet.com Thu Jan 11 20:05:44 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 11 Jan 2007 16:05:44 -0900 Subject: PDF rendering toolkit? References: <509gkmF1eufvtU1@mid.uni-berlin.de> Message-ID: <45a6d236$0$4777$88260bb3@free.teranews.com> Jorge Vargas wrote: > On 1/6/07, Diez B. Roggisch wrote: >> > I'm looking for a tool to take an actual .pdf file and display it in a >> > window (I'm using wxwidgets at the moment) >> >> No idea if there is a one-shot-kills-them-all solution out there - but >> if you have a way to go for windows, you might checkout PyQt and PyKDE >> to embed a kpfd-view in a window of yours. >> >> I agree that it is less than desirable to switch toolkits - but if you >> _have_ to... >> > yes indeed the problem with that is I want my code to be portable that > is the reason I'm working on top of wx. Qt3 (and PyQt3) is available on all platforms. Qt4 (and PyQt4) is GPL on all platforms for GPL projects. You no longer *have* to stick with wx for cross platform GPL goodness. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE -- Posted via a free Usenet account from http://www.teranews.com From gagsl-py at yahoo.com.ar Tue Jan 23 18:57:06 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Jan 2007 20:57:06 -0300 Subject: How to instantiate a different class in a constructor? In-Reply-To: <45B6951C.4030100@gentlemail.com> References: <1169563525.644251.118250@v45g2000cwv.googlegroups.com> <45B6951C.4030100@gentlemail.com> Message-ID: <7.0.1.0.0.20070123205039.04665f30@yahoo.com.ar> At Tuesday 23/1/2007 20:07, GiBo wrote: >BTW When is the subclass.__init__() method invoked if I don't explicitly >call it from __new__()? Apparently not from baseclass.__new__() nor from >object.__new__(). At instance creation, when type(name, bases, ns) is invoked, after the __new__ call, but only if the returned object is an instance of type. This happens in function type_call (in typeobject.c) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From jairodsl at gmail.com Tue Jan 16 18:08:58 2007 From: jairodsl at gmail.com (jairodsl) Date: 16 Jan 2007 15:08:58 -0800 Subject: How can i eval subindex on list[ ][ ] ? Message-ID: <1168988937.512029.192800@q2g2000cwa.googlegroups.com> Excuse me, i was trying in too many ways but i couldnt access subindex on a list , the problem is the next: I have indif=[[0,'A'],[1,'B'],[2,'C'],[3,'D']] and indic=[[0,'B'],[1,'C'],[2,'D'],[3,'E']] i need to eval if indic[i][j] is equal to indif[i][j] I used a double for but i had got "list index out of range". How can i do ??? Thanks a lot, Cordially, jDSL From grahn+nntp at snipabacken.dyndns.org Sun Jan 7 09:39:50 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 7 Jan 2007 14:39:50 GMT Subject: Why less emphasis on private data? References: <1168128425.058049.221320@v33g2000cwv.googlegroups.com> <7xd55rzke9.fsf@ruckus.brouhaha.com> Message-ID: On 06 Jan 2007 17:38:06 -0800, Paul Rubin wrote: > "BJ?rn Lindqvist" writes: >> It is given that emphasizing private data (encapsulation) leads to >> more internal complexity and more lines of code because you have to >> write getters and setters and stuff. > > You can have public variables in Java if you choose to. Writing > private variables with public setters and getters is just a style choice. Privates with getters/setters are (as I think someone else hinted) pretty pointless. The interesting stuff is the private data that *is* private, i.e. not meant for users at all. But yes, I don't mind not having 'private:' in Python. I don't have compile-time type checking anyway. In fact, I don't always know what the attributes of my objects /are/ until runtime. And besides, this is pretty close to a compile-time check: find -name \*.py | \ xargs egrep '\._[_a-z]' | \ fgrep -v self._ /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From python at hope.cz Fri Jan 12 04:36:17 2007 From: python at hope.cz (Lad) Date: 12 Jan 2007 01:36:17 -0800 Subject: How to run external program? Message-ID: <1168594577.397453.320380@a75g2000cwd.googlegroups.com> How can I run external program from Python? I use Python with XP Thank you for help LB From patrick.down at gmail.com Fri Jan 5 18:57:14 2007 From: patrick.down at gmail.com (Patrick Down) Date: 5 Jan 2007 15:57:14 -0800 Subject: What is proper way to require a method to be overridden? References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> Message-ID: <1168041434.385029.55870@38g2000cwa.googlegroups.com> jeremito wrote: > I am writing a class that is intended to be subclassed. What is the > proper way to indicate that a sub class must override a method? > > Thanks, > Jeremy Decorators to the rescue? def must_override(f): def t(*args): raise NotImplementedError("You must override " + f.__name__) return t class Foo: @must_override def Bar(x,y): pass Foo().Bar() Traceback (most recent call last): File "testit.py", line 14, in ? Foo().Bar() File "testit.py", line 5, in t raise NotImplementedError("You must override " + f.__name__) NotImplementedError: You must override Bar From oliphant.travis at ieee.org Thu Jan 25 12:58:40 2007 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Thu, 25 Jan 2007 10:58:40 -0700 Subject: Two dimensional lists In-Reply-To: <45B8DDE4.9000903@designaproduct.biz> References: <45B8DDE4.9000903@designaproduct.biz> Message-ID: Laszlo Nagy wrote: >># shouldn't I be able to fill the lists simply by pointing to a location? >> >>matrix[a_idx, p_idx] = 0x219 # and so on? >> > > Lists are not matrices. For example: > > L = [ [1,2,3], ['a','b','c'], 10 ] > print L[1][2] # Prints 'c', you will like this syntax but... > print L[2][5] # TypeError: 10 is not subscriptable > > You can create a function that creates a "list of lists" filled with > zeros, and then use this data structure as a matrix. > > BUT! If you need to use matrices filled with numbers, try numarray: > > http://www.stsci.edu/resources/software_hardware/numarray > > Numarray is much more efficient for this task. It is also out-dated. For new code users are strongly encouraged to use NumPy. The numarray people are transitioning their own code to use NumPy and numarray will cease being supported at some point. http://numpy.scipy.org http://www.numpy.org --- sourceforge site. -Travis From shansen at advpubtech.com Tue Jan 16 00:48:33 2007 From: shansen at advpubtech.com (Stephen Hansen) Date: Mon, 15 Jan 2007 21:48:33 -0800 Subject: RotatingFileHandler + subprocess module problems In-Reply-To: <7.0.1.0.0.20070111231652.05977e10@yahoo.com.ar> References: <7a9c25c20701111059q1186377nde4021eaf768d345@mail.gmail.com> <7.0.1.0.0.20070111231652.05977e10@yahoo.com.ar> Message-ID: <7a9c25c20701152148g371ce875gf96e84bcf320472d@mail.gmail.com> That was perfect-- it now all behaves as it should. Thanks! On 1/11/07, Gabriel Genellina wrote: > > At Thursday 11/1/2007 15:59, Stephen Hansen wrote: > > >If I run app1, and then app2, it all works fine. Specifically, the > >apps are logging correctly and I can see with Process Explorer that > >each has a handle to the appropriate files. > > > >However, I have a setting to make App2 run App1 in the background > >for convienance. This is using the subprocess module. When this > >setting is on, App2 will die horribly the first time that the > >doRollover comes along: specifically it gets a permission denied > >error when it tries to rename App2.log to App2.log.1 > > > >After doing some debugging, it appears that App1 (if started by App2 > >using the subprocess module) has a handle to App2.log /somehow/. It > >never starts it, or touches it (verified through debug messages), > >but seems to inherit it. > > That's subprocess fault. You menctioned Process Explorer, it appears > you're using Windows. > Using subprocess, the child process always inherits all file handles > from its parent. This may or may not be desirable, and in your case, > it's not. App1 inherits the open file handle to App2.log. > Inside subprocess.py, near line 789, there is a call to > CreateProcess; its 5th parameter is called bInheritHandles and it's > set to 1. The comment "must inherit handles to pass std handles" is > wrong AFAIK, and setting STARTF_USESTDHANDLES in startupinfo should > be enough. (It may be that some lines above, STARTF_USESTDHANDLES is > not correctly set). > I'll try to investigate a bit more and file a bug report or a patch. > In the meantime, you could replace that 1 in CreateProcess by a 0. > Specially if you don't use PIPE or redirects, your problem should go away. > > > -- > Gabriel Genellina > Softlab SRL > > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Wed Jan 31 11:01:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 31 Jan 2007 17:01:59 +0100 Subject: another newbie question: why should you use "*args" ? References: <4b4a3$45c0b94c$83aef404$20934@news1.tudelft.nl> Message-ID: In <4b4a3$45c0b94c$83aef404$20934 at news1.tudelft.nl>, stef wrote: > Eugene Antimirov wrote: > >> And one note more. Just to be more pythonic you shouldn't use form >> range(len(blabla)). Instead use: >> >> for i in list: >> ....blabla... >> >> > I would love that, > but please tell me how (I need an integer counter for something else too): > > def chunk_plot(*args): > if len(args) == 1: list = args[0] > else: list = args > > color = ['g','r','b','y','m'] > plot ( list[0], color[0]) > hold (True) > for i in range ( 1, len(list) ): > plot ( list[i], color[i] ) No need for the counter here. for args in zip(list[1:], color[1:]): plot(*args) Ciao, Marc 'BlackJack' Rintsch From sean at datafly.net Wed Jan 24 03:06:17 2007 From: sean at datafly.net (Sean Schertell) Date: Wed, 24 Jan 2007 17:06:17 +0900 Subject: How to use dynamic properties? <-- Noob In-Reply-To: <45B5C1CD.6010009@islandtraining.com> References: <45B5C1CD.6010009@islandtraining.com> Message-ID: <67CD438D-08B4-492B-B96C-9A3D844A4EA0@datafly.net> Yep, that was it. Thanks Gary :-) Sean On Jan 23, 2007, at 5:05 PM, Gary Herron wrote: > Sean Schertell wrote: >> person.name = 'Joe' >> person.age = 20 >> person.sex = 'm' >> >> info_I_need = name >> >> print person.info_I_need >> >> # How can I make it print 'Joe' ? >> >> >> Sean >> >> >> :::: DataFly.Net :::: >> Complete Web Services >> http://www.datafly.net >> >> > Like this: > > info_I_need = 'name' > > print getattr(person, info_I_need) > > Related to getattr are setattr and hasattr. > Gary Herron > > > > :::: DataFly.Net :::: Complete Web Services http://www.datafly.net From jorge.vargas at gmail.com Mon Jan 8 10:57:45 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 8 Jan 2007 11:57:45 -0400 Subject: PDF rendering toolkit? In-Reply-To: <4866bea60701080747s380f909ana6559da75d8d894f@mail.gmail.com> References: <32822fe60701051252s6353f10drc101109adc376fdb@mail.gmail.com> <4866bea60701080747s380f909ana6559da75d8d894f@mail.gmail.com> Message-ID: <32822fe60701080757s35f6054dx606ee6ae19e1e08a@mail.gmail.com> On 1/8/07, Chris Mellon wrote: > On 1/5/07, Jorge Vargas wrote: > > Hi > > > > I'm looking for a tool to take an actual .pdf file and display it in a > > window (I'm using wxwidgets at the moment) > > > > I have found several project but none seem to do what I need. > > > > http://sourceforge.net/projects/pdfplayground seems like a nice > > toolkit to edit pdf files with python code, but nothing about > > rendering. > > > > I have find out http://poppler.freedesktop.org/ but there seems to be > > no python bindings for it. > > > > there is also an example at http://www.daniweb.com/code/snippet618.html > > using wx.lib.pdfwin but that is windows only, I need at least Linux > > support better if it's platform independant as python *should* be > > > > and the reportlabs BSD packages can't do this. > > http://www.reportlab.org/devfaq.html#2.1.5 > > > > anyone knows of a toolkit to do this? bonus points if's it is already > > integrated into wxpython > > -- > > Rendering PDF is quite hard, much harder than writing it. yes indeed > There are > relatively few PDF rendering solutions for any platform, and it's > non-trivial to merge one with a specific UI solution. So I'm not aware > of any cross-platform solution. Most PDF usage either embeds the Adobe > ActiveX control (on windows) or just shunts it off the user to find a > working PDF viewer. I guess for now I'll use the ActiveX code on windows and try out Martin's suggestion on embedding a window of acrobat reader on the linux part. On the other hard I'm going to email the poppler guys to see if they are interested in some python and/or wxwidgets integration. > http://mail.python.org/mailman/listinfo/python-list > From cvanarsdall at mvista.com Tue Jan 30 14:28:37 2007 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 30 Jan 2007 11:28:37 -0800 Subject: The reliability of python threads In-Reply-To: <%OLvh.67202$qO4.51886@newssvr13.news.prodigy.net> References: <%OLvh.67202$qO4.51886@newssvr13.news.prodigy.net> Message-ID: <45BF9C65.5080800@mvista.com> John Nagle wrote: > Aahz wrote: > >> In article , >> Carl J. Van Arsdall wrote: >> My point is that an app that dies only once every few months under load >> is actually pretty damn stable! That is not the kind of problem that >> you are likely to stimulate. >> > > This has all been so vague. How does it die? > Well, before operating on most of the data I perform type checks, if the type check fails, my system flags an exception. Now i'm in the process of finding out how the data went bad. I gotta wait at this point though, so I was investigating possibilities so I could find a new way of throwing the kitchen sink at it. > It would be useful if Python detected obvious deadlock. If all threads > are blocked on mutexes, you're stuck, and at that point, it's time > to abort and do tracebacks on all threads. You shouldn't have to > run under a debugger to detect that. > > Then a timer, so that if the Global Python Lock > stays locked for more than N seconds, you get an abort and a traceback. > That way, if you get stuck in some C library, it gets noticed. > > Those would be some good basic facilities to have in thread support. > I agree. That would be incredibly useful. Although doesn't this spark up the debate on threads killing threads? From what I understand, this is frowned upon (and was removed from java because it was dangerous). Although I think that if there was a master or control thread that watched the state of the system and could intervene, that would be powerful. One way to do this could be to use processes, and each process could catch a kill signal if it appears to be stalled, although I am absolutely sure there is more to it than that. I don't think this could be done at all with python threads though, but as a fan of python threads and their ease of use, it would be a nice and powerful feature to have. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From steve at holdenweb.com Thu Jan 11 17:49:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 11 Jan 2007 22:49:01 +0000 Subject: Matching Directory Names and Grouping Them In-Reply-To: <1168554244.459131.190440@k58g2000hse.googlegroups.com> References: <1168554244.459131.190440@k58g2000hse.googlegroups.com> Message-ID: J wrote: > Hello Group- > > I have limited programming experience, but I'm looking for a generic > way to search through a root directory for subdirectories with similar > names, organize and group them by matching their subdirectory path, and > then output their full paths into a text file. For example, the > contents of the output text file may look like this: > > \Input1\2001\01\ > \Input2\2001\01\ > \Input3\2001\01\ > > \Input1\2002\03\ > \Input2\2002\03\ > \Input3\2002\03\ > > \Input2\2005\05\ > \Input3\2005\05\ > > \Input1\2005\12\ > \Input3\2005\12\ > > I tried working with python regular expressions, but so far haven't > found code that can do the trick. Any help would be greatly > appreciated. Thanks! > Define "similar". regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com From gigs at hi.t-com.hr Tue Jan 9 17:46:45 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 09 Jan 2007 23:46:45 +0100 Subject: find.find Message-ID: import fnmatch, os def find(pattern, startdir=os.curdir): matches = [] os.path.walk(startdir, findvisitor, (matches, pattern)) matches.sort() return matches def findvisitor((matches, pattern), thisdir, nameshere): # for name in nameshere: if fnmatch.fnmatch(name, pattern): fullpath = os.path.join(thisdir, name) matches.append(fullpath) can someone explain why (matches, pattern) is doing in this two funct? thanks From gandalf at designaproduct.biz Mon Jan 29 10:24:18 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 29 Jan 2007 16:24:18 +0100 Subject: Random passwords generation (Python vs Perl) =) In-Reply-To: <1170082420.420688.109910@l53g2000cwa.googlegroups.com> References: <1170046719.708692.243290@s48g2000cws.googlegroups.com> <1170064302.264009.12650@p10g2000cwp.googlegroups.com> <7xveiqapwi.fsf@ruckus.brouhaha.com> <1170082420.420688.109910@l53g2000cwa.googlegroups.com> Message-ID: <45BE11A2.70806@designaproduct.biz> NoName ?rta: > Hmmm.. > In the Perl example password generates after user hit ENTER not > continously like in Python you wrote... :) > > i want see various ways to generate passwords even if they some > indirect like using BASE64 > I copied this from a recipe, I do not remember which one. I like it very much because it creates password that are easy to type in. You can type every odd letter with your left hand and every even letter with your right hand. Best, Leslie from random import Random PASSWORD_LENGTH = 10 rng = Random() def generatePassword(length=PASSWORD_LENGTH,alternate_hands=True): righthand = '23456qwertasdfgzxcvbQWERTASDFGZXCVB' lefthand = '789yuiophjknmYUIPHJKLNM' allchars = righthand + lefthand res = "" for i in range(length): if not alternate_hands: res += rng.choice(allchars) else: if i%2: res += rng.choice(lefthand) else: res += rng.choice(righthand) return res if __name__ == '__main__': for i in range(10): print generatePassword() From ramdaz at gmail.com Mon Jan 1 14:33:42 2007 From: ramdaz at gmail.com (Ramdas) Date: 1 Jan 2007 11:33:42 -0800 Subject: How do I add users using Python scripts on a Linux machine Message-ID: <1167680022.061496.164160@v33g2000cwv.googlegroups.com> How do I add users using Python scripts on a Linux machine? Someone has a script? From malaclypse2 at gmail.com Fri Jan 19 17:35:02 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 19 Jan 2007 17:35:02 -0500 Subject: OT Annoying Habits (Was: when format strings attack) In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A4304595A9C@eugsrv400.psc.pscnet.com> References: <2BBAEE949D384D40A2B851287ADB6A4304595A9C@eugsrv400.psc.pscnet.com> Message-ID: <16651e80701191435y63fe725bwbd541b6011992713@mail.gmail.com> On 1/19/07, Carroll, Barry wrote: > Secondly, can someone point me to the Standard Usenet Convention that > mandates against top-posting. This is not sarcasm; I would really like > to see it. For what (very little) it's worth, see RFC 1855. -- Jerry From __peter__ at web.de Tue Jan 2 12:49:06 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Jan 2007 18:49:06 +0100 Subject: how to use execfile with argument under windows References: <1167757591.465076.314700@h40g2000cwb.googlegroups.com> Message-ID: baur79 wrote: > i need to execute this command line (different source for n times) > > filename.exe -type png -source sourcearg -file filename.png > i try with python (python script and filename.exe in same directory) > execfile("filename.exe -type png -source sourcearg -file filename.png") That does not do what you think it does, see http://docs.python.org/lib/built-in-funcs.html#l2h-26 You need os.system() or, for more complex applications, the subprocess module. Peter From paul at boddie.org.uk Thu Jan 11 13:36:22 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Jan 2007 10:36:22 -0800 Subject: Read from database, write to another database, simultaneously References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> <1168519760.894380.303990@i39g2000hsf.googlegroups.com> <33vph.8825$pQ3.2190@newsread4.news.pas.earthlink.net> Message-ID: <1168540582.125402.78850@p59g2000hsd.googlegroups.com> Dennis Lee Bieber wrote: > > "need"? No... the "copy ... from ..." statement "needs" such, but do > you really "need" to use "copy ... from ..." to load the data -- or is > this just a concept that caught your fancy? In chapter 13 of the PostgreSQL 8.1 documentation ("Performance Tips"), descending into section 13.4 ("Populating a Database"), whose introduction may not admittedly coincide precisely with the inquirer's use case ("first populating a database" doesn't strictly apply, but it may yet describe a situation that is close enough given the kind of data involved), and within section 13.4.2 ("Use COPY"), the text reads as follows: "Use COPY to load all the rows in one command, instead of using a series of INSERT commands." http://www.postgresql.org/docs/8.1/static/populate.html#POPULATE-COPY-FROM > If you can get Oracle to dump the data in the form of SQL insert > statements, maybe with some clean-up done by a script, and feed them to > PostgreSQL the entire job starts to look something like: > > odump theDatabase | python cleanup.py | psql theNewDatabase The problem with this approach (as the manual notes) is that COPY is a lot faster than lots of INSERT statements: "Note that loading a large number of rows using COPY is almost always faster than using INSERT, even if PREPARE is used and multiple insertions are batched into a single transaction." My experience with inserting large numbers of records into PostgreSQL suggests that this advice should not be readily ignored. Paul From deets at nospam.web.de Fri Jan 19 06:07:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 Jan 2007 12:07:07 +0100 Subject: How to find out if another process is using a file References: Message-ID: <51bn2rF1jn1paU1@mid.uni-berlin.de> Tom Wright wrote: > js wrote: >> How about using lock? >> Let writing process locks the files before writing, and unlock after >> the job's done. > > Is locking mandatory or co-operative? I don't have any control over the > process which is doing the writing, so if it's co-operative it's no good > to me. > > If it's mandatory, then I can try to acquire a lock on the file - if this > fails or blocks, then the other process must have it open. Will this > work? AFAIK it's cooperative. Diez From martin at v.loewis.de Mon Jan 22 16:43:35 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 22 Jan 2007 22:43:35 +0100 Subject: mmap caching In-Reply-To: References: <1169367640.895556.34160@l53g2000cwa.googlegroups.com> <45B3DD4D.3010009@v.loewis.de> <1169422167.683707.264180@a75g2000cwd.googlegroups.com> <45B3FDA7.9030702@v.loewis.de> Message-ID: <45B53007.4050004@v.loewis.de> Nick Craig-Wood schrieb: > So presumably it is python generating a MemoryError. It is asking for > a new bit of memory and it is failing so it throws a MemoryError. > > Could memory allocation under windows be affected by a large chunk of > mmap()ed file which is physically swapped in at the time of the > allocation? To my knowledge, no. There might be virtual memory quotas, but I don't think Windows supports such a concept. More likely, this is entirely unrelated to the mmap issue. I would guess that the machine on which the problem occurs is close to exhausting its swap file (because of other activities in the system), so Python occasionally manages to exhaust the swap file, through regular allocations (memory-mapped files don't contribute to swap file usage, as they have their own disk-backing, namely in the file being mapped). Regards, Martin From borntonetwork at gmail.com Sat Jan 20 19:47:40 2007 From: borntonetwork at gmail.com (borntonetwork) Date: 20 Jan 2007 16:47:40 -0800 Subject: The proper use of QSignalMapper In-Reply-To: <86ec2$45b24bc1$54d1d767$19264@news.chello.no> References: <1169045073.138626.60770@l53g2000cwa.googlegroups.com> <1169049100.393777.269350@v45g2000cwv.googlegroups.com> <1169085859.586698.149400@51g2000cwl.googlegroups.com> <1169135947.039984.108930@51g2000cwl.googlegroups.com> <1169305392.100624.295850@11g2000cwr.googlegroups.com> <86ec2$45b24bc1$54d1d767$19264@news.chello.no> Message-ID: <1169340460.317597.161580@l53g2000cwa.googlegroups.com> How simple. I will remember that sender() function for future reference. Thanks, David. David Boddie wrote: > On Saturday 20 January 2007 16:03, borntonetwork wrote: > > > David, thanks for your help. Unfortunately, all attempts of making this > > solution work have failed. I would be interested to know if anyone has > > used QSignalMapper successfully in a similar situation. > > Looking again at what you originally wrote, and looking at your > solution below, I don't think it's really appropriate to use a > QSignalMapper for this purpose. (That's what I understood from the > signature of the deleteProductIngredient() method you had in your > original code.) > > What you appear to want is a way of being notified about state > changes to widgets that also identifies the individual widget > that changed. You can do that by connecting the individual widgets > to the same slot and call sender() to find out which object emitted > the signal; for example: > > # ... > > for idx in range(1, maxIngredients+1): > wName = 'chkProductIngredientsDelete_'+str(idx) > w = self.__dict__[wName] > self.connect(w, QtCore.SIGNAL("stateChanged(int)"), > self.deleteProductIngredient) > > def deleteProductIngredient(self, state): > """Delete a product ingredient.""" > print self.sender(), "changed state to", state > > What QSignalMapper does is collect signals from different objects, > assigning an ID to each of them, and emits a single signal with > an ID whenever it receives a signal from one of those objects. > In other words, it allows the actions of a group of objects to be > described by a parameter but discards the signal's arguments. > It's most useful for things like collections of push buttons where > you only need to know that they were clicked. > > > For any interested, I worked around the problem using a closure, > > which seems a bit cleaner from a coding point of view, although > > I don't have any idea if it is more efficient or not: > > [...] > > > Each iteration then created a new function based on the closure: > > [...] > > It's good to know that you got something working in the end. There's > also another solution that involves QSignalMapper, but it may not make > the resulting code any simpler. > > David From timr at probo.com Tue Jan 9 03:35:42 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 09 Jan 2007 08:35:42 GMT Subject: Module to read svg References: <1168225193.883421.185140@s80g2000cwa.googlegroups.com> <45a1f746$0$27874$9b622d9e@news.freenet.de> Message-ID: Robert Kern wrote: >Martin v. L?wis wrote: >> schpok at gmail.com schrieb: >>> Does anyone know if there's an actual free implementation of this? >> >> For the dom module in it, xml.dom.minidom should work. Depending on >> your processing needs, that might be sufficient. > >I don't think it quite fits what the OP is asking for. SVG defines some non-XML >structure for some of its contents. For example: > > Why is that non-XML? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gert.cuykens at gmail.com Tue Jan 16 13:20:49 2007 From: gert.cuykens at gmail.com (Gert Cuykens) Date: Tue, 16 Jan 2007 19:20:49 +0100 Subject: whats wrong with my reg expression ? In-Reply-To: References: <7.0.1.0.0.20070115195902.05c75aa0@yahoo.com.ar> Message-ID: thx it works now From konrad.hinsen at laposte.net Fri Jan 12 08:49:59 2007 From: konrad.hinsen at laposte.net (Konrad Hinsen) Date: Fri, 12 Jan 2007 14:49:59 +0100 Subject: Parallel Python In-Reply-To: <1168597288.571937.176430@s34g2000cwa.googlegroups.com> References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> <1168558876.033624.178010@k58g2000hse.googlegroups.com> <1168597288.571937.176430@s34g2000cwa.googlegroups.com> Message-ID: <820B079C-AB6B-4685-86F1-8B87EA04A11B@laposte.net> On Jan 12, 2007, at 11:21, Paul Boddie wrote: > done. My own experience with regard to releasing software is that even > with an open source licence, most people are likely to ignore your > projects than to suddenly jump on board and take control, and even if My experience is exactly the same. And looking into the big world of Open Source programs, the only case I ever heard of in which a project was forked by someone else is the Emacs/XEmacs split. I'd be happy if any of my projects ever reached that level of interest. > Related to your work, I've released a parallel execution solution > called parallel/pprocess [1] under the LGPL and haven't really heard > about anyone really doing anything with it, let alone forking it and That's one more project... It seems that there is significant interest in parallel computing in Python. Perhaps we should start a special interest group? Not so much in order to work on a single project; I believe that at the current state of parallel computing we still need many different approaches to be tried. But an exchange of experience could well be useful for all of us. Konrad. -- --------------------------------------------------------------------- Konrad Hinsen Centre de Biophysique Mol?culaire, CNRS Orl?ans Synchrotron Soleil - Division Exp?riences Saint Aubin - BP 48 91192 Gif sur Yvette Cedex, France Tel. +33-1 69 35 97 15 E-Mail: hinsen at cnrs-orleans.fr --------------------------------------------------------------------- From no-spam at no-spam-no-spam.invalid Wed Jan 10 08:25:34 2007 From: no-spam at no-spam-no-spam.invalid (robert) Date: Wed, 10 Jan 2007 14:25:34 +0100 Subject: Is there a way to protect a piece of critical code? In-Reply-To: References: Message-ID: Hendrik van Rooyen wrote: > Hi, > > I would like to do the following as one atomic operation: > > 1) Append an item to a list > 2) Set a Boolean indicator I doubt you have to worry at all about this in such simple single-single queue - if there is not a much more complex condition upon the insert order. And what should the indicator tell? that a new element is there? The list itself tells its the length, its guaranteed to be increased _after_ .append() And you can .pop(0) just so - catching/retring at Key/IndexError at least. List .append() and .pop() will be atomic in any Python though its not mentioned explicitely - otherwise it would be time to leave Python. There is also Queue.Queue - though it has unneccessary overhead for most purposes. A function to block Python interpreter thread switching in such VHL language would be nice for reducing the need for spreading locks in some cases (huge code - little critical sections). Yet your example is by far not a trigger for this. I also requested that once. Implementation in non-C-Pythons may be difficult. Generally there is also technique for optimistic unprotected execution of critical sections - basically using an atomic counter and you need to provide code for unrolling half executions. Search Google. Robert > It would be almost like getting and holding the GIL, > to prevent a thread swap out between the two operations. > - sort of the inverted function than for which the GIL > seems to be used, which looks like "let go", get control > back via return from blocking I/O, and then "re - acquire" > > Is this "reversed" usage possible? > Is there some way to prevent thread swapping? > > The question arises in the context of a multi threaded > environment where the list is used as a single producer, > single consumer queue - I can solve my problem in various > ways, of which this is one, and I am curious as to if it is > possible to prevent a thread swap from inside the thread. > > - Hendrik > From sschwarzer at sschwarzer.net Sat Jan 6 20:45:57 2007 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 07 Jan 2007 02:45:57 +0100 Subject: clarification on open file modes In-Reply-To: References: Message-ID: <45A050D5.1070603@sschwarzer.net> On 2007-01-05 03:46, tubby wrote: > Is this the safest, most portable way to open files on any platform: > > fp = open(file_name, 'rb') > fp.close() > > I understand that doing the following on Windows to a binary file (a > jpeg or exe files for example) can cause file corruption, is that correct? > > fp = open(file_name, 'r') > fp.close() Rule of thumb: If the file is a text file (usually has a concept of "text lines"), read and write it in text mode (without "b" in the mode argument). So line endings will be converted, so that your Python code can process the text data identically on all platforms. On the other hand, if you process binary files (as you mention, for example jpg or exe files), read and write them in binary mode, so the data won't be corrupted. > How can a simple open in read mode corrupt data??? You won't corrupt the data in the file, but you will kind of corrupt the data that arrives in your program. Stefan From sjdevnull at yahoo.com Mon Jan 29 18:07:14 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 29 Jan 2007 15:07:14 -0800 Subject: ctypes: Setting callback functions in C libraries In-Reply-To: <1169704047.486695.157820@l53g2000cwa.googlegroups.com> References: <1169704047.486695.157820@l53g2000cwa.googlegroups.com> Message-ID: <1170112034.337112.109070@q2g2000cwa.googlegroups.com> I realized my wrapping was broken, fixing that below... On Jan 25, 12:47 am, "sjdevn... at yahoo.com" wrote: > I'm trying to wrap GNU readline withctypes(the Python readline > library doesn't support the callback interface), but I can't figure out > how to set values to a variable inside the library. This is Python 2.5 > on Linux. Here's what I have so far--if you comment out the memmove > call (3 lines) it works as expected: [SNIP] > I need to assign ourfunc to RL_ATTEMPTED_COMPLETION_FUNCTION, but > obviously simple assignment rebinds the name rather than assigning it > to the C variable. > > Usingctypes.memmove to overwrite it(as I have here) will run the > function but segfault when ourfunc goes to return (poking around with > the debugger shows it's dying inctypes' callbacks.c at line 216, "keep > = setfunc(mem, result, 0);" because setfunc is NULL). I'm not entirely > sure that's not because of some error in the prototyping or restype > setting rather than as a result of memmove, but the memmove seems > sketchy enough (only sets the function pointer itself presumably, not > anything thatctypeswrappers need) that I'm looking for a better way > to do it. > > As it is, returning rv directly or simply returning None causes the > same segfault. > > Any idea? > > Thanks very much for your time! # START #!/usr/local/bin/python2.5 import ctypes ctypes.cdll.LoadLibrary("libcurses.so")#, mode=ctypes.RTLD_GLOBAL) ctypes.CDLL("libcurses.so", mode=ctypes.RTLD_GLOBAL) ctypes.cdll.LoadLibrary("libreadline.so") readline = ctypes.CDLL("libreadline.so") RL_COMPLETION_FUNC_T = \ ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_char_p), ctypes.c_char_p, ctypes.c_int, ctypes.c_int) RL_LINE_BUFFER = ctypes.c_char_p.in_dll(readline, "rl_line_buffer") RL_ATTEMPTED_COMPLETION_FUNCTION = \ RL_COMPLETION_FUNC_T.in_dll(readline, "rl_attempted_completion_function") def our_complete(text, start, end): print "Test", text, start, end rv = None arrtype = ctypes.c_char_p*4 globals()["rv"] = arrtype("hello", "hatpin", "hammer", None) globals()["crv"]=ctypes.cast(rv, ctypes.POINTER(ctypes.c_char_p)) return rv ourfunc = RL_COMPLETION_FUNC_T(our_complete) _readline = readline.readline _readline.argtypes = [ctypes.c_char_p] _readline.restype = ctypes.c_char_p ctypes.memmove(ctypes.addressof(RL_ATTEMPTED_COMPLETION_FUNCTION), ctypes.addressof(ourfunc), 4) line = _readline("Input: ") print "INPUT was: ", line #END From gagsl-py at yahoo.com.ar Mon Jan 15 14:49:03 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 15 Jan 2007 16:49:03 -0300 Subject: How to write code to get focuse the application which is open from server In-Reply-To: <1168887206.135633.182600@s34g2000cwa.googlegroups.com> References: <1168143871.536432.252010@v33g2000cwv.googlegroups.com> <45a0dae2$0$8948$4c368faf@roadrunner.com> <1168837895.073936.270330@11g2000cwr.googlegroups.com> <1168887206.135633.182600@s34g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20070115163649.03274e60@yahoo.com.ar> At Monday 15/1/2007 15:53, vithi wrote: >I am sorry that was a typing error. I try like that >app.Print.OK.Click() but it was not working. The printer window was not >IdentifiedIs their any method I can use to achive the same goal. How >the window title was used as class name?. Could you please help me to >solve this problem. app.Print looks for a window whose title contains the word "Print" (does it exist?), inside, looks for a control with "OK" (presumably a button), and sends it a mouse click event. There is a forum specific for pywinauto questions - see its homepage. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From subscriber100 at rjs.org Mon Jan 8 00:44:55 2007 From: subscriber100 at rjs.org (Ray Schumacher) Date: Sun, 07 Jan 2007 21:44:55 -0800 Subject: multi-threaded webcam with SimpleAsyncHTTPServer.py Message-ID: <6.2.3.4.2.20070107203507.02e77240@pop-server.san.rr.com> The class seems to work pretty well - very basic and fast, it just serves images from the specified port and camera device (USB cam). I added an ImageServer class and some code to __main__ class ImageServer(RequestHandler): def __init__(self, conn, addr, server): asynchat.async_chat.__init__(self,conn) self.client_address = addr self.connection = conn self.server = server self.set_terminator ('\r\n\r\n') self.incoming = deque() self.outgoing = deque() self.rfile = None self.wfile = writewrapper(self.outgoing, -self.use_buffer or self.blocksize) self.found_terminator = self.handle_request_line self.request_version = "HTTP/1.1" self.code = None def send_head(self): buff, width, height = cam.dev.getbuffer() imPIL = (Image.frombuffer("RGB", (width, height), buff, "raw", "BGR", 0, -1) ) imPIL.save(PILFile, "JPEG") self.send_response(200) self.send_header("Content-type", "image/jpeg") self.send_header("Content-Length: ", str(PILFile.len)) self.end_headers() self.wfile.write(PILFile.getvalue()) return in __main__ ... parser.add_option('-3', dest='server', help='Run the server for only cam images', action='store_const', const=3) ... if options.server==3: from StringIO import StringIO from PIL import Image if sys.platform == 'win32': import VideoCapture try: del(cam) gc.collect() print "deleted old cam instance" except: pass cam = VideoCapture.Device(devnum=options.devNum, showVideoWindow=0) print cam buff, width, height = cam.dev.getbuffer() PILFile = StringIO() else: pass else: if options.root is None: parser.error("Need root path to start server") if not os.path.isdir(options.root): parser.error("Root path does not exist") os.chdir(options.root) I run it with: >python SimpleAsyncHTTPServer.py -p8888 -3 I'll be trying implementing some streaming next. Question, though: how can I unblock asyncore.loop(), or at least be able to interrupt it? To kill this server I need to hit CNTRL-C and then attempt to GET an image from Firefox, Python then throws KetboardInterrupt. Note that I haven't tried it on *NIX so the sys.platform bit needs more implementing as well. Other suggestions? Ray -------------- next part -------------- """ Get an updated version of this server from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440665 Original pseudo-async* version by Pierre Quentel, available from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259148 * It would only be async while reading requests, it would switch to a synchronous write to a socket when writing a response to a socket. Ick. Features this version offers: 1. Uses asynchronous reading and writing to/from sockets all the time. 2. Performs sectioned reads from on-disk files, allowing for serving files of unlimited size. 3. More informative logging. 4. A quick wrapper for logging to a file and stdout/stderr. 5. Trailing-slash redirects on directories. 6. Optional built-in favicon.ico (to reduce the number of spurious log entries). 7. Subclass which does not allow any directory lists or redirecting to /index.htm[l] . 8. Subclass which does not allow any directory lists, but does automatic redirection to /index.htm[l] . 9. Doesn't try to open reserved names on Windows. 10. Has a tuning mechanism to change buffer performance depending on small or large files. For most people, one can run this from the command line and get a reasonably functioning web server with minor issue. I benchmarked this version in my personal projects folder, which contains around a gig of files, sizes ranging from a few kilobytes, to 100 megabytes. I then performed two concurrent "wget -m http://localhost/" calls (from different paths) on Windows 2k (machine is a P4 2.8ghz with hyperthreading, 1.5 gigs memory, reading from an 80 gig SATA drive, writing to a 120 gig PATA drive). On small files, it was able to serve up 15-30 files/second. On larger (10+ meg) files, it was able to serve up at 15+ megs/second (so says adding the speed reported by wget). The server never broke 7 megs of resident memory, and tended to hang below 10% processor utilization. There exists a live host running this web server: nada.ics.uci.edu """ import asynchat, asyncore, socket, SimpleHTTPServer import sys, cgi, cStringIO, os, traceback, zlib, optparse __version__ = ".5" try: #Python 2.4 has a deque from collections import deque except: #Python 2.3 and earlier don't # #limited deque, trimmed version of Raymond Hettinger's recipe: #http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179 class deque(object): def __init__(self, iterable=()): self.left = self.right = 0 self.data = {} self.extend(iterable) def append(self, x): self.data[self.right] = x self.right += 1 def appendleft(self, x): self.left -= 1 self.data[self.left] = x def pop(self): if self.left == self.right: raise IndexError('cannot pop from empty deque') self.right -= 1 elem = self.data[self.right] del self.data[self.right] return elem def popleft(self): if self.left == self.right: raise IndexError('cannot pop from empty deque') elem = self.data[self.left] del self.data[self.left] self.left += 1 return elem def clear(self): self.data.clear() self.left = self.right = 0 def extend(self, iterable): for elem in iterable: self.append(elem) def __len__(self): return self.right - self.left reserved_names = dict.fromkeys(('com1 com2 com3 com4 com5 com6 com7 com8 com9 ' 'lpt1 lpt2 lpt3 lpt4 lpt5 lpt6 lpt7 lpt8 lpt9 ' 'con nul prn').split()) def popall(self): #Preallocate the list to save memory resizing. r = len(self)*[None] for i in xrange(len(r)): r[i] = self.popleft() return r class writewrapper(object): def __init__(self, d, blocksize=4096): self.blocksize = blocksize self.d = d def write(self, data): if self.blocksize in (None, -1): self.d.append(data) else: BS = self.blocksize xtra = 0 if len(data)%BS: xtra = len(data)%BS + BS buf = self.d for i in xrange(0, len(data)-xtra, BS): buf.append(data[i:i+BS]) if xtra: buf.append(data[-xtra:]) # class ParseHeaders(dict): if 1: """Replacement for the deprecated mimetools.Message class Works like a dictionary with case-insensitive keys""" def __init__(self, infile, *args): self._ci_dict = {} lines = infile.readlines() for line in lines: k,v=line.split(":",1) self._ci_dict[k.lower()] = self[k] = v.strip() self.headers = self.keys() def getheader(self,key,default=""): return self._ci_dict.get(key.lower(),default) def get(self,key,default=""): return self._ci_dict.get(key.lower(),default) # class RequestHandler(asynchat.async_chat, SimpleHTTPServer.SimpleHTTPRequestHandler): if 1: server_version = "SimpleAsyncHTTPServer/"+__version__ protocol_version = "HTTP/1.1" MessageClass = ParseHeaders blocksize = 4096 #In enabling the use of buffer objects by setting use_buffer to True, #any data block sent will remain in memory until it has actually been #sent. use_buffer = False use_favicon = True def __init__(self, conn, addr, server): #print 'init RequestHandler' asynchat.async_chat.__init__(self,conn) self.client_address = addr self.connection = conn self.server = server # set the terminator : when it is received, this means that the # http request is complete ; control will be passed to # self.found_terminator self.set_terminator ('\r\n\r\n') self.incoming = deque() self.outgoing = deque() self.rfile = None self.wfile = writewrapper(self.outgoing, -self.use_buffer or self.blocksize) self.found_terminator = self.handle_request_line self.request_version = "HTTP/1.1" self.code = None # buffer the response and headers to avoid several calls to select() def update_b(self, fsize): if fsize > 1048576: self.use_buffer = True self.blocksize = 131072 def collect_incoming_data(self,data): """Collect the data arriving on the connexion""" if not data: self.ac_in_buffer = "" return self.incoming.append(data) def prepare_POST(self): """Prepare to read the request body""" bytesToRead = int(self.headers.getheader('content-length')) # set terminator to length (will read bytesToRead bytes) self.set_terminator(bytesToRead) self.incoming.clear() # control will be passed to a new found_terminator self.found_terminator = self.handle_post_data def handle_post_data(self): """Called when a POST request body has been read""" self.rfile = cStringIO.StringIO(''.join(popall(self.incoming))) self.rfile.seek(0) self.do_POST() def do_GET(self): """Begins serving a GET request""" # Check for query string in URL qspos = self.path.find('?') if qspos>=0: self.body = cgi.parse_qs(self.path[qspos+1:], keep_blank_values=1) self.path = self.path[:qspos] #print self.path.find('confer') self.handle_data() def do_POST(self): """Begins serving a POST request. The request data must be readable on a file-like object called self.rfile""" ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) length = int(self.headers.getheader('content-length')) if ctype == 'multipart/form-data': self.body = cgi.parse_multipart(self.rfile, pdict) elif ctype == 'application/x-www-form-urlencoded': qs = self.rfile.read(length) self.body = cgi.parse_qs(qs, keep_blank_values=1) else: self.body = '' # Unknown content-type #self.handle_post_body() self.handle_data() def handle_data(self): """Class to override""" if self.use_favicon and self.path == '/favicon.ico': self.send_response(200) self.send_header("Content-type", 'text/html') self.send_header("Content-Length", len(favicon)) self.end_headers() self.log_request(self.code, len(favicon)) self.outgoing.append(favicon) self.outgoing.append(None) return f = self.send_head() if f: # do some special things with file objects so that we don't have # to read them all into memory at the same time...may leave a # file handle open for longer than is really desired, but it does # make it able to handle files of unlimited size. try: size = os.fstat(f.fileno())[6] except AttributeError: size = f.len self.update_b(size) self.log_request(self.code, size) self.outgoing.append(f) elif options.log: self.log_request(self.code) # signal the end of this request self.outgoing.append(None) def handle_request_line(self): """Called when the http request line and headers have been received""" # prepare attributes needed in parse_request() self.rfile = cStringIO.StringIO(''.join(popall(self.incoming))) self.rfile.seek(0) self.raw_requestline = self.rfile.readline() self.parse_request() if self.command in ['GET','HEAD']: # if method is GET or HEAD, call do_GET or do_HEAD and finish method = "do_"+self.command if hasattr(self,method): getattr(self,method)() elif self.command=="POST": # if method is POST, call prepare_POST, don't finish yet self.prepare_POST() else: self.send_error(501, "Unsupported method (%s)" %self.command) def end_headers(self): """Send the blank line ending the MIME headers, send the buffered response and headers on the connection""" if self.request_version != 'HTTP/0.9': self.outgoing.append("\r\n") def handle_error(self): traceback.print_exc(sys.stderr) self.close() def writable(self): return len(self.outgoing) and self.connected def handle_write(self): O = self.outgoing while len(O): a = O.popleft() #handle end of request disconnection if a is None: #Some clients have issues with keep-alive connections, or #perhaps I implemented them wrong. #If the user is running a Python version < 2.4.1, there is a #bug with SimpleHTTPServer: # http://python.org/sf/1097597 #So we should be closing anyways, even though the client will #claim a partial download, so as to prevent hung-connections. ## if self.close_connection: self.close() return #handle file objects elif hasattr(a, 'read'): _a, a = a, a.read(self.blocksize) if not a: del _a continue else: O.appendleft(_a) break #handle string/buffer objects elif len(a): break else: #if we get here, the outgoing deque is empty return #if we get here, 'a' is a string or buffer object of length > 0 try: num_sent = self.send(a) if num_sent < len(a): if not num_sent: # this is probably overkill, but it can save the # allocations of buffers when they are enabled O.appendleft(a) elif self.use_buffer: O.appendleft(buffer(a, num_sent)) else: O.appendleft(a[num_sent:]) except socket.error, why: if isinstance(why, (str, unicode)): self.log_error(why) elif isinstance(why, tuple) and isinstance(why[-1], (str, unicode)): self.log_error(why[-1]) else: self.log_error(str(why)) self.handle_error() def send_head(self): path = self.translate_path(self.path) if sys.platform == 'win32': if os.path.split(path)[1].lower().split('.')[0] in reserved_names: self.send_error(404, "File not found") return if os.path.isdir(path): if not self.path.endswith('/'): self.send_response(302) x = ''%self.path self.send_header("Content-Location", self.path + '/') self.send_header("Content-Length", len(x)) self.end_headers() self.wfile.write(x) return None return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self) def send_response(self, code, message=None): if self.code: return self.code = code if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': self.wfile.write("%s %d %s\r\n" % (self.protocol_version, code, message)) #print 'send resp', (self.protocol_version, code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string()) def log_message(self, format, *args): sys.stderr.write("%s - - [%s] %s \"%s\" \"%s\"\n" % (self.address_string(), self.log_date_time_string(), format%args, self.headers.get('referer', ''), self.headers.get('user-agent', '') )) # class OnlyExactFiles(RequestHandler): def send_head(self): path = self.translate_path(self.path) if os.path.isdir(path): self.send_error(404, "File not found") return None return RequestHandler.send_head(self) # class ExactFilesAndIndex(RequestHandler): def list_directory(self, path): self.send_error(404, "File not found") return None # class ImageServer(RequestHandler): def __init__(self, conn, addr, server): #print 'init ImageServer' asynchat.async_chat.__init__(self,conn) self.client_address = addr self.connection = conn self.server = server # set the terminator : when it is received, this means that the # http request is complete ; control will be passed to # self.found_terminator self.set_terminator ('\r\n\r\n') self.incoming = deque() self.outgoing = deque() self.rfile = None self.wfile = writewrapper(self.outgoing, -self.use_buffer or self.blocksize) self.found_terminator = self.handle_request_line self.request_version = "HTTP/1.1" self.code = None def send_head(self): buff, width, height = cam.dev.getbuffer() imPIL = (Image.frombuffer("RGB", (width, height), buff, "raw", "BGR", 0, -1) ) imPIL.save(PILFile, "JPEG") self.send_response(200) self.send_header("Content-type", "image/jpeg") self.send_header("Content-Length: ", str(PILFile.len)) self.end_headers() self.wfile.write(PILFile.getvalue()) return # class Server(asyncore.dispatcher): if 1: """Copied from http_server in medusa""" def __init__ (self, ip, port, handler): self.ip = ip self.port = port self.handler = handler asyncore.dispatcher.__init__ (self) self.create_socket (socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind ((ip, port)) # Quoting the socket module documentation... # listen(backlog) # Listen for connections made to the socket. The backlog argument # specifies the maximum number of queued connections and should # be at least 1; the maximum value is system-dependent (usually # 5). self.listen (5) def handle_accept (self): try: conn, addr = self.accept() except socket.error: self.log_info ('warning: server accept() threw an exception', 'warning') return except TypeError: self.log_info ('warning: server accept() threw EWOULDBLOCK', 'warning') return # creates an instance of the handler class to handle the request/response # on the incoming connexion self.handler(conn,addr,self) favicon = zlib.decompress( 'x\x9c\xb5\x93\xcdN\xdb@\x14\x85\x07\x95\x07\xc8\x8amYv\xc9#\xe4\x11x\x04\x96}' '\x8c\x88\x1dl\xa0\x9b\xb6A\xa2)\x0bVTB\xa9"\xa5?*I\x16\xad"\x84d\x84DE\x93' '\x14;v\xc01M\xe2$\x988\xb1l\x9d\xde;v\\\x03\x89TU\xea\xb5N\xe4\xb9\x9a\xef' '\x1c\xcfO\x84X\xa0\'\x95\x12\xf4\xbb,\x9e/\n\xb1$\x84xF\xa2\x16u\xc2>WzQ\xfc' '\xf7\xca\xad\xafo\x91T\xd2\x1ai\xe5\x1fx[\xf9\xf4\x01\xc57\xbb\xd8\xdf\xd8' '\x00\x8d\x11\xf9\x95\x12\xda\x9a\xc3\xae\xe5_\xbdDpk\x03\xc3\xaeT\xd0\xb3\xd0' '>?\x83Z\xfd\x86Z\xa5\x84\x1fG_\xa4\xe7\x1c^\xa9W\xbfJ\xfe\xb4\xf0\x0e^\xdb' '\x88}0 \xafA\x0f\xa3+c&O\xbd\xf4\xc1\xf6\xb6d\x9d\xc6\x05\xdcVSz\xb0x\x1c\x10' '\x0fo\x02\xc7\xd0\xe7\xf1%\xe5\xf3\xc78\xdb\xf9Y\x93\x1eI\x1f\xf8>\xfa\xb5' '\x8bG<\x8dW\x0f^\x84\xd9\xee\xb5~\x8f\xe1w\xaf{\x83\x80\xb2\xbd\xe1\x10\x83' '\x88\'\xa5\x12\xbcZ?9\x8e\xb3%\xd3\xeb`\xd4\xd2\xffdS\xb9\x96\x89!}W!\xfb\x9a' '\xf9t\xc4f\x8aos\x92\x9dtn\xe0\xe8Z\xcc\xc8=\xec\xf7d6\x97\xa3]\xc2Q\x1b(\xec' 'd\x99_\x8dx\xd4\x15%\xce\x96\xf9\xbf\xacP\xd1:\xfc\xf1\x18\xbe\xeb\xe2\xaey' '\x89;]\xc5\xf1\xfb<\xf3\x99\xe9\x99\xefon\xa2\xdb6\xe5\x1c\xbb^\x8b}FV\x1b' '\x9es+\xb3\xbd\x81M\xeb\xd1\xe0^5\xf1\xbd|\xc4\xfca\xf2\xde\xf0w\x9cW\xabr.' '\xe7\xd9\x8dFx\x0e\xa6){\x93\x8e\x85\xf1\xb5\x81\x89\xd9\x82\xa1\x9c\xc8;\xf9' '\xe0\x0cV\xb8W\xdc\xdb\x83\xa9i\xb1O at g\xa6T*\xd3=O\xeaP\xcc(^\x17\xfb\xe4\xb3' 'Y\xc9\xb1\x17{N\xf7\xfbo\x8b\xf7\x97\x94\xe3;\xcd\xff)\xd2\xf2\xacy\xa0\x9b' '\xd4g=\x11B\x8bT\x8e\x94Y\x08%\x12\xe2q\x99\xd4\x7f*\x84O\xfa\r\xb5\x916R' ) # decide which type of server to run which = (RequestHandler, OnlyExactFiles, ExactFilesAndIndex, ImageServer) class to_logfile: if 1: fl = True def __init__(self, fileobj): self.f = fileobj def write(self, data): data = data.encode('utf-8') sys.__stdout__.write(data) self.f.write(data) if self.fl: self.f.flush() if __name__=="__main__": usage = "usage: \%prog -r [-p] [-d] [-0|-1|-2]" parser = optparse.OptionParser(usage) parser.add_option('-r', '--root', dest='root', help='Root path of the web server', action='store') parser.add_option('-p', '--port', dest='port', type='int', help='Port to listen on (default 80)', default=80, action='store') parser.add_option('-d', '--dev', dest='devNum', type='int', help='Device to serve images from (default 0)', default=0, action='store') parser.add_option('-l', '--log', dest='log', type='int', help='log requests? (default 0)', default=0, action='store') parser.add_option('-0', dest='server', help='Run the standard server (default)', action='store_const', const=0, default=0) parser.add_option('-1', dest='server', help='Run the server which only serves exact file names specified', action='store_const', const=1) parser.add_option('-2', dest='server', help='Run the server which will serve exact files and directory->index files', action='store_const', const=2) parser.add_option('-3', dest='server', help='Run the server which will serve only cam images', action='store_const', const=3) options, args = parser.parse_args() print 'server options:', options.server if options.server==3: from StringIO import StringIO from PIL import Image if sys.platform == 'win32': import VideoCapture try: del(cam) gc.collect() print "deleted old cam instance" except: pass cam = VideoCapture.Device(devnum=options.devNum, showVideoWindow=0) print cam buff, width, height = cam.dev.getbuffer() PILFile = StringIO() else: pass # try http://laurent.pointal.org/python/projets/pyvideograb/index.pih # or fg #import fg #cam = fg.Grabber() #cam.set_source(options.devNum) # or video4linux.video_capture / v4lctl else: if options.root is None: parser.error("Need root path to start server") if not os.path.isdir(options.root): parser.error("Root path does not exist") os.chdir(options.root) req_handler = which[options.server] s=Server('',options.port,req_handler) print req_handler.__name__, "running on port", options.port, "with root path", options.root asyncore.loop() From timr at probo.com Tue Jan 23 02:33:44 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 23 Jan 2007 07:33:44 GMT Subject: python grammar References: <1169466630.014322.232500@l53g2000cwa.googlegroups.com> Message-ID: "tpochep" wrote: > >In 'augop' non-terminal : > >http://docs.python.org/ref/augassign.html > >the delimiter '//=' was skipped. Why? Probably an oversight. //= is relatively new. >In 'Boolean operations': > >http://docs.python.org/ref/Booleans.html > >In 'expression' rule - what does 'if', 'else' mean? I guess 'if' and >'else' must be keywords, not non-terminals. Yes, those refer to literal keywords. I'd judge both of those as errors in the web page. There is a link on the page for reporting problems. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From smusnmrNOSPAM at yahoo.com Thu Jan 4 04:56:43 2007 From: smusnmrNOSPAM at yahoo.com (siggi) Date: Thu, 4 Jan 2007 10:56:43 +0100 Subject: pow() works but sqrt() not!? References: <1167899693.759071.51450@31g2000cwt.googlegroups.com> <1167903337.816250.196540@51g2000cwl.googlegroups.com> Message-ID: Thank you T?nis, both for the link and your patient explanation :-) Siggi "tonisk" schrieb im Newsbeitrag news:1167903337.816250.196540 at 51g2000cwl.googlegroups.com... > >if you want math functions to your current namespace use: > >>> from math import *What is a "namespace" and what is the difference > >>> between ">>>import math" > and ">>>from math import *" ? for namespaces read this http://www.network-theory.co.uk/docs/pytut/tut_68.html import math creates new namespace "math" for names in that module, so you can acess them by prefixing them with "math", like math.sqrt(9). from math import * imports all names to your local scope, so you do not have to prefix them, sqrt(9) -- T?nis From __peter__ at web.de Mon Jan 8 12:13:14 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 Jan 2007 18:13:14 +0100 Subject: Walking The Right Path References: Message-ID: Tim Daneliuk wrote: > IOW, is there a way to return a symlink-based path which contains > the symlink pointer as is was *defined* not as it expands? os.readlink() Peter From not at set.se Thu Jan 25 13:50:44 2007 From: not at set.se (Daniel) Date: Thu, 25 Jan 2007 19:50:44 +0100 Subject: While loop with "or"? Please help! References: <1169720769.490434.91650@j27g2000cwj.googlegroups.com> Message-ID: 2007-01-25 11:26:09 wd.jonsson at gmail.com wrote in message <1169720769.490434.91650 at j27g2000cwj.googlegroups.com> > Hmm, my while loop with "or" doesn't seem to work as I want it to... > How do I tell the while loop to only accept "Y" or "y" or "N" or "n" > input from the str(raw_input)? > > Thank's in advance! > > Snippet of code: > > import os > > def buildfinder(): > os.system("CLS") > GameRoot = os.getenv("GAME_ROOT") + "\\" > > print "Do you want to use " + GameRoot + " as your source > directory?" > usr = str(raw_input('Y/N: ')) > return usr > > #Runs the buildfinder function > usrinp = buildfinder() > > def buildwhiler(): > > while usrinp != "y" or "Y" or "N" or "n": <<<<----PROBLEM > print "Enter Y or N!" > usr = str(raw_input('Y/N: ')) > else: > code continues Thanks for the help everyone! :) This forum rules! From chris.cavalaria at free.fr Thu Jan 4 05:21:27 2007 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 04 Jan 2007 11:21:27 +0100 Subject: Sorting on multiple values, some ascending, some descending In-Reply-To: <1167855055.615746.105410@48g2000cwx.googlegroups.com> References: <1167850127.745463.3520@k21g2000cwa.googlegroups.com> <1167852652.416990.158610@k21g2000cwa.googlegroups.com> <1167855055.615746.105410@48g2000cwx.googlegroups.com> Message-ID: <459cd53c$0$308$426a74cc@news.free.fr> bearophileHUGS at lycos.com a ?crit : > Raymond Hettinger: >> The simplest way is to take advantage of sort-stability and do >> successive sorts. For example, to sort by a primary key ascending and >> a secondary key decending: >> L.sort(key=lambda r: r.secondary, reverse=True) >> L.sort(key=lambda r: r.primary) > > That's probably the faster and simpler way. > The following solution is probably slow, memory-hungry, and it's not > tested much so it may be buggy too, but it shows my idea, and bugs can > be fixed: > > class Inverter: > def __init__(self, item, reversed=False): > self.item = item > self.reversed = reversed > def __cmp__(self, other): > if self.reversed: > return cmp(other.item, self.item) > else: > return cmp(self.item, other.item) > > data = [[1, "a", "b"], [1, "b", "d"], [1, "d", "a"]] > reverses = [True, False, False] > > print sorted(data, key=lambda subseq: map(Inverter, subseq, reverses)) Nice trick, but don't get too caught up using classes ;) Try that one instead for much better performance : class Inverter: def __init__(self, item): self.item = item def __cmp__(self, other): return cmp(other, self.item) def invert_if(item, reversed=False): if reversed: return Inverter(item) return item data = [[1, "a", "b"], [1, "b", "d"], [1, "d", "a"]] reverses = [True, False, False] print sorted(data, key=lambda subseq: map(invert_, subseq, reverses)) From exarkun at divmod.com Thu Jan 18 12:46:59 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 18 Jan 2007 12:46:59 -0500 Subject: How to find out if another process is using a file In-Reply-To: Message-ID: <20070118174659.11447.1665846096.divmod.quotient.20979@ohm> On Thu, 18 Jan 2007 14:34:52 -0300, Gabriel Genellina wrote: >"Tom Wright" escribi? en el mensaje >news:eoo6vd$33u$1 at gemini.csx.cam.ac.uk... > >> I'm writing a program which reads a series of data files as they are >> dumped >> into a directory by another process. At the moment, it gets sporadic bugs >> when it tries to read files which are only partially written. >> >> I'm looking for a function which will tell me if a file is opened in >> write-mode by another process - if it is, my program will ignore it for >> now >> and come back to it later. This needs to work on linux and windows. Mac >> OS would be a bonus too. An os-independent solution would be good, but I >> could write os-specific options and have it pick the appropriate one. > >Use os.open with the O_EXCL flag; will fail if the other process has the >file still open (and will fail if another process is reading the file, too, >not just if someone is writing). On what platform is this true? A better solution is to name or place files which are begin written in a which is recognizable and only rename or move them to their final location when they have been completely written. For example, name files ".new" as they are being written. When they are fully written, drop the ".new" suffix. On the reader side, ignore any file with a name ending in ".new". Jean-Paul From steven.bethard at gmail.com Tue Jan 16 21:22:03 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 16 Jan 2007 19:22:03 -0700 Subject: [ANN] argparse 0.5 - Command-line parsing library Message-ID: Announcing argparse 0.5 ----------------------- argparse home: http://argparse.python-hosting.com/ argparse single module download: http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw argparse bundled downloads at PyPI: http://www.python.org/pypi/argparse/ About this release ================== This release adds support for required options, better support for opening files (deprecating the 'outfile' type), better control over help formatting and better support for negative number arguments. New in this release =================== * Required options may now be created by specifying required=True in calls to add_argument. http://argparse.python-hosting.com/wiki/ArgumentParser/add_argument/required * The 'outfile' type has been deprecated. Use the new FileType factory which can be used to specify both file mode and buffer size, and knows how to convert '-' into sys.stdin or sys.stout as appropriate. The 'outfile' type will be removed in a future release. http://argparse.python-hosting.com/wiki/FileType * The ArgumentParser constructor now accepts a ``formatter_class`` keyword argument which can be set to argparse.RawDescriptionHelpFormatter to keep argparse from line-wrapping your description. * The algorithm in parse_args() has been enhanced to understand that negative numbers are usually positional arguments, not misspelled optional arguments. About argparse ============== The argparse module is an optparse-inspired command line parser that improves on optparse by: * handling both optional and positional arguments * supporting parsers that dispatch to sub-parsers * producing more informative usage messages * supporting actions that consume any number of command-line args * allowing types and actions to be specified with simple callables instead of hacking class attributes like STORE_ACTIONS or CHECK_METHODS as well as including a number of other more minor improvements on the optparse API. To whet your appetite, here's a simple program that sums its command-line arguments and writes them to a file:: parser = argparse.ArgumentParser() parser.add_argument('integers', nargs='+', type=int) parser.add_argument('--log', default=sys.stdout, type=argparse.FileType('w')) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() From wleftwich at gmail.com Thu Jan 4 07:33:00 2007 From: wleftwich at gmail.com (Wade Leftwich) Date: 4 Jan 2007 04:33:00 -0800 Subject: Iterate through list two items at a time References: <12pmahqc7kclbfc@corp.supernews.com> <1167882211.696350.271620@s34g2000cwa.googlegroups.com> Message-ID: <1167913980.320964.264860@s34g2000cwa.googlegroups.com> Wade Leftwich wrote: > Jeffrey Froman wrote: > > Dave Dean wrote: > > > > > I'm looking for a way to iterate through a list, two (or more) items at a > > > time. > > > > Here's a solution, from the iterools documentation. It may not be the /most/ > > beautiful, but it is short, and scales well for larger groupings: > > > > >>> from itertools import izip > > >>> def groupn(iterable, n): > > ... return izip(* [iter(iterable)] * n) > > ... > > >>> list(groupn(myList, 2)) > > [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] > > >>> list(groupn(myList, 3)) > > [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)] > > >>> list(groupn(myList, 4)) > > [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)] > > >>> for a,b in groupn(myList, 2): > > ... print a, b > > ... > > 0 1 > > 2 3 > > 4 5 > > 6 7 > > 8 9 > > 10 11 > > >>> > > > > Jeffrey > > This works great except you lose any 'remainder' from myList: > > >>> list(groupn(range(10),3)) > [(0, 1, 2), (3, 4, 5), (6, 7, 8)] # did not include (9,) > > The following might be more complex than necessary but it solves the > problem, and like groupn() > it works on infinite lists. > > from itertools import groupby, imap > def chunk(it, n=0): > if n == 0: > return iter([it]) > grouped = groupby(enumerate(it), lambda x: int(x[0]/n)) > counted = imap(lambda x:x[1], grouped) > return imap(lambda x: imap(lambda y: y[1], x), counted) > > >>> [list(x) for x in chunk(range(10), 3)] > [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] > > Note the chunks are iterators, not tuples as in groupn(): > > >>> [x for x in chunk(range(10), 3)] > [, > , > , > ] > > > -- Wade Leftwich > Ithaca, NY Or, using generator expressions instead of imap and getting rid of the lambdas -- from itertools import groupby def chunk(it, n=0): if n == 0: return iter([it]) def groupfun((x,y)): return int(x/n) grouped = groupby(enumerate(it), groupfun) counted = (y for (x,y) in grouped) return ((z for (y,z) in x) for x in counted) >>> [list(x) for x in chunk(range(10), 3)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] >>> [x for x in chunk(range(10), 3)] [, , , ] From kw at codebykevin.com Wed Jan 24 09:40:40 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 24 Jan 2007 09:40:40 -0500 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: Message-ID: <45B76FE8.5080701@codebykevin.com> Daniel Jonsson wrote: > So, I've reached the point where my building pipeline tools actually > needs to be used by other people in my company. By this reason I > actually need to think about the usability, and I've come to the > conclusion that I need a GUI. So, which of the two packages should I > learn, and which one is easier to pick up? > Thanks in advance! > > Daniel I recommend Tkinter. By itself, Tkinter is too basic (it only supports buttons, labels, frames, and so on), but if you add extension packages such as Tablelist (for data display), Tile (for platform-native theming), and TkTreeCtrl (for tree views), it can produce GUI's that are just as rich as those available from wx or Qt. Here are some links for more info: Tile: http://tktable.sourceforge.net/tile Tile for Tkinter: http://tkinter.unpythonic.net/wiki/TileWrapper Tablelist: http://www.nemethi.de/ Tabelist for Tkinter (with Tile support): http://tkinter.unpythonic.net/wiki/TableListTileWrapper Tktreectrl: http://tktreectrl.sourceforge.net/ Treectrl for Tkinter: http://klappnase.zexxo.net/TkinterTreectrl/index.html All these libraries are open-source and available under commercial-friendly terms (BSD-style licenses). I make heavy use of Tile and Tablelist in my applications. Tktreectrl is incredibly powerful, but is also quite complex, and I have not used it myself in an application. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jan 31 12:24:19 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 31 Jan 2007 18:24:19 +0100 Subject: "Correct" db adapter In-Reply-To: <1170262532.590048.247580@a75g2000cwd.googlegroups.com> References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> <1170262532.590048.247580@a75g2000cwd.googlegroups.com> Message-ID: <45c0d078$0$435$426a74cc@news.free.fr> king kikapu a ?crit : > Thanks for the replies. > > I think i do not need something like ORM, but just a db-module that i > can "work" the database with it. FWIW, SQLAlchemy is not an ORM, but an higher-level API for SQL integration. The ORM part is an optional feature built on top of this API. But I'm not sure SQLAlchemy supports SQL Server anyway !-) > I just want to know if pyodbc is the "correct" solution to do so or if > it is another db-module that is more > usefull for this job. AFAICT: * there's an experimental MS SQL Server db-module: http://www.object-craft.com.au/projects/mssql/ * the Win32 extensions offers support for ADO, but then it's not db-api compliant * unless you use adodbapi, but I don't know if it's still supported (last release is 3+ years old): http://adodbapi.sourceforge.net/ HTH From uymqlp502 at sneakemail.com Wed Jan 17 20:11:29 2007 From: uymqlp502 at sneakemail.com (Russ) Date: 17 Jan 2007 17:11:29 -0800 Subject: Units of measurement In-Reply-To: References: <7x8xg1xr62.fsf_-_@ruckus.brouhaha.com> Message-ID: <1169082689.148793.312130@51g2000cwl.googlegroups.com> Robert Kern wrote: > Paul Rubin wrote: > > I'm sure this has been done before, but it just struck my fancy, an > > example of Python's "emulating numeric types", inspired by the old > > Unix "units" utility, and the Frink language. > > Oh yeah, it's been done before. Several times over, in fact. > And there was another one announced here sometime in the past year or so, IIRC, > but I don't recall the name of it or that of the author. :-( Perhaps you are referring to the scalar class at http://RussP.us/scalar.htm The nice thing about this one (which I wrote myself) is that after you do your development and are ready for "production" runs, you can easily disable the unit checks and get the efficiency of built-in numeric types. That can be two orders of magnitude faster! It comes with a complete user manual too (pdf and html). I'm using it for my engineering work, and it's working great! From m.elston at advantest-ard.com Fri Jan 5 13:58:13 2007 From: m.elston at advantest-ard.com (Mark Elston) Date: Fri, 05 Jan 2007 10:58:13 -0800 Subject: What is proper way to require a method to be overridden? In-Reply-To: <1167978050.971481.111880@q40g2000cwq.googlegroups.com> References: <1167965523.427735.167890@q40g2000cwq.googlegroups.com> <1167974907.497878.61070@i15g2000cwa.googlegroups.com> <1167978050.971481.111880@q40g2000cwq.googlegroups.com> Message-ID: <12pt7nijd12dq5d@corp.supernews.com> * Paddy wrote (on 1/4/2007 10:20 PM): > belinda thom wrote: > >> On Jan 4, 2007, at 9:28 PM, Carl Banks wrote: >> >>> jeremito wrote: >>>> I am writing a class that is intended to be subclassed. What is the >>>> proper way to indicate that a sub class must override a method? >>> You can't (easily). >>> >>> If your subclass doesn't override a method, then you'll get a big fat >>> AttributeError when someone tries to call it. But this doesn't stop >>> someone from defining a subclass that fails to override the method. >>> Only when it's called will the error show up. You can, as others have >>> noted, define a method that raises NotImplementedError. But this >>> still >>> doesn't stop someone from defining a subclass that fails to override >>> the method. The error still only occurs when the method is called. >>> >>> There are some advantages to using NotImplementedError: >>> >>> 1. It documents the fact that a method needs to be overridden >>> 2. It lets tools such as pylint know that this is an abstract method >>> 3. It results in a more informative error message >>> >>> But, in the end, if someone wants to define a class that defiantly >>> refuses to declare a method, you can't stop them. >> This is the con of a dynamic language... > In a language that has statements to force the user to over-ride a > method when a class is sub-classed, what is to stop the lazy > sub-classer from doing the equivalent of: > > define override_me(self, ...): > pass > > And so get code through the compiler,, allowing them to 'meet their > targets'? > And this *could* be perfectly suitable if the class really doesn't make use of the method. (I have seen this in poorly designed super classes and interface classes - sigh.) > - Paddy. > From http Thu Jan 25 16:04:45 2007 From: http (Paul Rubin) Date: 25 Jan 2007 13:04:45 -0800 Subject: Python does not play well with others References: <1169722875.237123.98680@v45g2000cwv.googlegroups.com> <1169726842.719104.304300@v45g2000cwv.googlegroups.com> <1169755188.989078.75510@v33g2000cwv.googlegroups.com> <7xveiudg4o.fsf@ruckus.brouhaha.com> Message-ID: <7xzm864y36.fsf@ruckus.brouhaha.com> John Nagle writes: > That's the problem. We now have four SSL implementations for > Python, none of which let you do all the things OpenSSL can do. I'm aware of some OpenSSL wrappers plus TLSlite. Am I missing a couple more? I guess maybe the OpenSSL wrappers also work on GnuTLS. > Can you build the built-in SSL package without building all of > Python? I thought there was no built-in SSL package-- it just calls OpenSSL. From firefoxxer at gmail.com Fri Jan 12 15:05:24 2007 From: firefoxxer at gmail.com (Coby) Date: 12 Jan 2007 12:05:24 -0800 Subject: How to respond to a confirmation prompt automatically Message-ID: <1168632324.226733.130870@a75g2000cwd.googlegroups.com> Just to give you some background about my problem: I execute os.system(command), where command is a string. On the command line in windows, I get: "Continue, and unload these objects? [no]" I need to respond 'y' to continue, but I am uncertain on how to output the 'y' automatically. Thanks in advance. From rrr at ronadam.com Thu Jan 18 10:57:42 2007 From: rrr at ronadam.com (Ron Adam) Date: Thu, 18 Jan 2007 09:57:42 -0600 Subject: Module name to filename and back? Message-ID: Is there a function to find a filename from a dotted module (or package) name without importing it? The imp function find_module() doesn't work with dotted file names. And it looks like it may import the file as it raises an ImportError error exception if it can't find the module. (Shouldn't it raise an IOError instead?) What I'm looking for is to be able to get the full module name when I have a filename. And get the full filename when I have the module name. And do both of these without importing the module. modulename <==> filename filename <==> modulename Ron From alexisbrion at gmail.com Mon Jan 8 05:15:26 2007 From: alexisbrion at gmail.com (alex) Date: 8 Jan 2007 02:15:26 -0800 Subject: How to get file name on a remote server with ftplib? In-Reply-To: <1168009814.236723.105280@51g2000cwl.googlegroups.com> References: <1168008952.020516.130890@s80g2000cwa.googlegroups.com> <1168009814.236723.105280@51g2000cwl.googlegroups.com> Message-ID: <1168251326.729345.278600@38g2000cwa.googlegroups.com> Thanks guys for the help! I used nlst(). The ftputil seems to be very helpfull, but getting a new library in an organization like the one I work at is big issue. Thanks anyway :) wittempj at hotmail.com wrote: > alex wrote: > > Hello, > > > > My script is trying to get a file from a remote server, every day it > > ftps from a directory. My code works perfect if I know the name of the > > file in the remote directory. > > > > ftp.retrbinary('RETR ' + filename, handleDownload) > > > > The problem is that in the future the name of the file is going to be > > aleatory. How can I get the file's name (only one file is in that > > directory) and store it in a variable before executing ftp.retrbinary? > > > > Thanks a lot for your help, > > > > Alex > > You can use the nlst(dirname) method to retrieve a directory listing on > the remote server. If the remote server doesn't support NLST command > rhen you could do ftp.retrlines('LIST') and parse the results to get a > directory listing. From martin.witte at gmail.com Mon Jan 29 14:38:56 2007 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 29 Jan 2007 11:38:56 -0800 Subject: List Behavior when inserting new items In-Reply-To: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> References: <1170097056.581394.249110@a75g2000cwd.googlegroups.com> Message-ID: <1170099535.989235.35800@a75g2000cwd.googlegroups.com> On Jan 29, 7:57 pm, "Drew" wrote: > I'm looking to add an element to list of items, however I'd like to > add it at a specific index greater than the current size: > > list = [1,2,3] > list.insert(10,4) > > What I'd like to see is something like: > > [1,2,3,,,,,,4] > > However I see: > > [1,2,3,4] > > Is there any way to produce this kind of behavior easily? > > Thanks, > Drew You could write your own class mimicing a list with your desired behaviour, something like: py>class llist(object): py> def __init__(self, arg = []): py> self.__list = arg py> def __setitem__(self, key, value): py> length = len(self.__list) py> if length < key: py> for i in range(length, key +1): py> self.__list.append(None) py> self.__list[key] = value py> def __str__(self): py> return str(self.__list) py> py>x = llist() py>x[10] = 1 py>print x [None, None, None, None, None, None, None, None, None, None, 1] for other methods to add to the llist class see http://docs.python.org/ ref/sequence-types.html From karoly.kiripolszky at gmail.com Sun Jan 28 11:06:58 2007 From: karoly.kiripolszky at gmail.com (karoly.kiripolszky) Date: 28 Jan 2007 08:06:58 -0800 Subject: howto redirect and extend help content ? In-Reply-To: <1fc1a$45bcc7f4$d443bb3a$8806@news.speedlinq.nl> References: <1fc1a$45bcc7f4$d443bb3a$8806@news.speedlinq.nl> Message-ID: <1170000418.287748.107320@l53g2000cwa.googlegroups.com> maybe you should make use of the objects' __doc__ attribute which holds the appropriate docstring. try to append something to it in the constructor. :) more on this in the manual: http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 On Jan 28, 4:58 pm, Stef Mientki wrote: > I'm making special versions of existing functions, > and now I want the help-text of the newly created function to exists of > 1. an extra line from my new function > 2. all the help text from the old function > > # the old function > def triang(M,sym=1): > """The M-point triangular window. <== old help text > """ > .... > > # the new function > def chunked_triang(M): > """ Chunked version of "triang" <== the extra line > """ > > >>> help(chunked_triang) > # should give something like > > chunked_triang(M) <== the new definition > Chunked version of "triang" <== the extra line > The M-point triangular window. <== old help text > > Is that possible ? > > thanks, > Stef Mientki From dakman at gmail.com Mon Jan 22 10:06:14 2007 From: dakman at gmail.com (dakman at gmail.com) Date: 22 Jan 2007 07:06:14 -0800 Subject: module check In-Reply-To: <1169477715.178874.223290@51g2000cwl.googlegroups.com> References: <1169477715.178874.223290@51g2000cwl.googlegroups.com> Message-ID: <1169478374.666968.160590@11g2000cwr.googlegroups.com> I'm at work so I can't test this, but I do beleive the inspect module can help you out. If it can't you can always try import the module in a try-catch statement, catching ImportError, however ImportError may be raised if the module you imported has trouble loading another module, but it shouln't be to hard to track down where the ImportError came from, a traceback object can give a lot more information than you would believe. Victor Polukcht wrote: > Can anybody suggest a correct way of checking in python module exists > and correctly installed from python program. From adamgarstang at googlemail.com Sun Jan 28 08:21:50 2007 From: adamgarstang at googlemail.com (Adam) Date: 28 Jan 2007 05:21:50 -0800 Subject: Ip address In-Reply-To: References: Message-ID: <1169990510.352536.4760@a34g2000cwb.googlegroups.com> Hey, This will get your IP address: #######Code######## print socket.gethostbyaddr(socket.gethostname()) ('compname', [], ['192.168.1.2']) ########End Code######## If you are wanting to to communicate over the internet you will have to get the IP of you rounter. So you will have to either find a way to talk to your router or try and use an online service like these other guys suggest. On Jan 28, 9:54 am, Scripter47 wrote: > How do i get my ip address? > > in cmd.exe i just type "ipconfig" then it prints: > ... > IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10 > ... > how can i do that in python?? From bthom at cs.hmc.edu Tue Jan 9 03:39:37 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Tue, 09 Jan 2007 00:39:37 -0800 Subject: private variables In-Reply-To: <45a35032$0$319$426a34cc@news.free.fr> References: <45a35032$0$319$426a34cc@news.free.fr> Message-ID: On Jan 9, 2007, at 12:20 AM, Bruno Desthuilliers wrote: > belinda thom a ?crit : >> Hello, >> >> In what version of python were private variables added? > > Which private variables ? Haha. The ones that are provided for convenience (via name mangling) that aren't really private if you wish to violate convention. --b From aahz at pythoncraft.com Sat Jan 6 11:12:13 2007 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2007 08:12:13 -0800 Subject: Anyone persuaded by "merits of Lisp vs Python"? References: <1167324666.002153.27570@a3g2000cwd.googlegroups.com> <1167986689.741094.252270@v33g2000cwv.googlegroups.com> Message-ID: In article <1167986689.741094.252270 at v33g2000cwv.googlegroups.com>, Ant wrote: > >So far? After a bit of pain getting started and finding decent docs >(while waiting for the books to arrive) I've found the language quite >easy to use. I haven't got into closures or macros yet - I need to get >more familiar with the basics first, but first impressions are >favorable. It seems that there is nothing conceptually in Python that I >can't reasonably easily do in Lisp, but the Python syntax is much more >straightforward for most of the basics I think (such as dictionaries, >sets, list comprehensions etc), and the function/naming conventions for >the core language is much clearer and more obvious than in Lisp. Just remember: today is the car of the cdr of your life. Once upon a time, I was working at a company that was a commercialized MIT Lisp project rewritten in C. One day I was amused to discover that buried deep in the code were a pair of functions, car() and cdr()... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Plus ca change, plus c'est la meme chose." From rampeters at gmail.com Wed Jan 31 12:10:33 2007 From: rampeters at gmail.com (johnny) Date: 31 Jan 2007 09:10:33 -0800 Subject: Python **kwargs ? Message-ID: <1170263432.199403.175290@k78g2000cwa.googlegroups.com> What is **kwargs mean in python? When you put double **, does it mean passing by reference? For example: def redirect_to(request, url, **kwargs): From jgodoy at gmail.com Sun Jan 7 16:24:58 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 07 Jan 2007 19:24:58 -0200 Subject: strange for loop construct References: <1168029548.217679.251230@q40g2000cwq.googlegroups.com> <12ptf5bl21f2teb@corp.supernews.com> <1168193206.598957.257700@38g2000cwa.googlegroups.com> <1168200211.928423.319260@38g2000cwa.googlegroups.com> Message-ID: <87fyamzg0l.fsf@gmail.com> skip at pobox.com writes: > Gabriel> Where do you find the "What's new" for previous releases? I > Gabriel> have to read them online. > >> > >> Google for > >> > what's new site:python.org > > Sorry, I took "I have to read them online" to mean that you needed to read > them online because (perhaps) you don't have a source distribution on your > computer. My 2.5 source (Subversion sandbox) has 2.0 through 2.5 What's New > source in Doc/whatsnew. My SuSE installation has it as /usr/share/doc/packages/python/Misc/NEWS -- Jorge Godoy From emin.shopper at gmail.com Thu Jan 11 07:59:46 2007 From: emin.shopper at gmail.com (Emin) Date: 11 Jan 2007 04:59:46 -0800 Subject: what is the idiom for copy lots of params into self? In-Reply-To: <1168481112.291651.89300@i39g2000hsf.googlegroups.com> References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> <1168481112.291651.89300@i39g2000hsf.googlegroups.com> Message-ID: <1168520386.457345.23680@i39g2000hsf.googlegroups.com> Dear Luis and everyone else who responded, Thanks for your suggestions. One issue with using *args or **kw is that I might no want to copy all the arguments to __init__ into self. What made me ask the question in my original post was not so much that I had to loop over the names I wanted to save, but whether it's okay to mess with self.__dict__ or if there is another way I should be assigning to self. Thanks, -Emin On Jan 10, 9:05 pm, "Luis M. Gonz?lez" wrote: > Emin wrote: > > Dear Experts, > > > When writing large classes, I sometimes find myself needing to copy a > > lot of parameters from the argument of __init__ into self. Instead of > > having twenty lines that all basically say something like self.x = x, I > > often use __dict__ via something like: > > > class example: > > def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n): > > for name in > > ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']: > > self.__dict__[name] = locals()[name] > > > This saves a lot of code and makes it easier to see what is going on, > > but it seems like there should be a better idiom for this task. Any > > suggestions? > > > Thanks, > > -EminHow about using variable length argumens? > > class example: > def __init__(self, *args): > for i in args: > self.__dict__[i] = i > > x = example('uno','dos','tres') > > Luis From luismgz at gmail.com Wed Jan 10 21:05:12 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 10 Jan 2007 18:05:12 -0800 Subject: what is the idiom for copy lots of params into self? References: <1168469214.452389.221180@p59g2000hsd.googlegroups.com> Message-ID: <1168481112.291651.89300@i39g2000hsf.googlegroups.com> Emin wrote: > Dear Experts, > > When writing large classes, I sometimes find myself needing to copy a > lot of parameters from the argument of __init__ into self. Instead of > having twenty lines that all basically say something like self.x = x, I > often use __dict__ via something like: > > class example: > def __init__(self,a,b,c,d,e,f,g,h,i,j,k,l,m,n): > for name in > ['a','b','c','d','e','f','g','h','i','j','k','l','m','n']: > self.__dict__[name] = locals()[name] > > This saves a lot of code and makes it easier to see what is going on, > but it seems like there should be a better idiom for this task. Any > suggestions? > > Thanks, > -Emin How about using variable length argumens? class example: def __init__(self, *args): for i in args: self.__dict__[i] = i x = example('uno','dos','tres') Luis From melih.onvural at gmail.com Mon Jan 29 16:13:50 2007 From: melih.onvural at gmail.com (Melih Onvural) Date: 29 Jan 2007 13:13:50 -0800 Subject: Executing Javascript, then reading value In-Reply-To: References: <1170103447.839304.44900@v33g2000cwv.googlegroups.com> Message-ID: <1170105229.984079.219180@l53g2000cwa.googlegroups.com> Thanks, let me check out this route, and then I'll post the results. Melih Onvural On Jan 29, 4:04 pm, Jean-Paul Calderone wrote: > On 29 Jan 2007 12:44:07 -0800, Melih Onvural wrote: > > >I need to execute some javascript and then read the value as part of a > >program that I am writing. I am currently doing something like this:Python doesn't include a JavaScript runtime. You might look into the > stand-alone Spidermonkey runtime. However, it lacks the DOM APIs, so > it may not be able to run the JavaScript you are interested in running. > There are a couple other JavaScript runtimes available, at least. If > Spidermonkey is not suitable, you might look into one of them. > > Jean-Paul From tjreedy at udel.edu Tue Jan 9 13:37:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 Jan 2007 13:37:44 -0500 Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> <1168350028.3722.3.camel@dot.uniqsys.com> Message-ID: "Carsten Haese" wrote in message news:1168350028.3722.3.camel at dot.uniqsys.com... | On Tue, 2007-01-09 at 11:38 +0000, Nick Maclaren wrote: | > As Dan Bishop says, probably not. The introduction to the decimal | > module makes exaggerated claims of accuracy, amounting to propaganda. | > It is numerically no better than binary, and has some advantages | > and some disadvantages. | | Please elaborate. Which exaggerated claims are made, and how is decimal | no better than binary? As to the latter question: calculating with decimals instead of binaries eliminates conversion errors introduced when one has *exact* decimal inputs, such as in financial calculations (which were the motivating use case for the decimal module). But it does not eliminate errors inherent in approximating reals with (a limited set of) ratrionals. Nor does it eliminate errors inherent in approximation algorithms (such as using a finite number of terms of an infinite series. Terry Jan Reedy From afaNOSPAM at neuf.fr Mon Jan 8 18:29:34 2007 From: afaNOSPAM at neuf.fr (Amaury Forgeot d'Arc) Date: Tue, 09 Jan 2007 00:29:34 +0100 Subject: Getting started with Crystal Reports...little help in the far court. In-Reply-To: <1168293388.349793.256790@s80g2000cwa.googlegroups.com> References: <1168293388.349793.256790@s80g2000cwa.googlegroups.com> Message-ID: Good evening, Mudcat a ?crit : > I am not that familiar with Crystal Reports, but having read some other > posts I know that the way to integrate the API with Python is through > the COM interface provide by win32all. > > However, I have been unable to find any other information on how to get > started. I've used the COM interface before in integrating Excel and a > couple of other things. So I am familiar with how that works. But there > are at least 40 options dealing with Crystal and Business Objects. I > have no idea which makepy file to create or which one provides the > functionality I need. > > I'm not looking to do much. All I'm really trying to do is provide one > application where a list of crystal reports can be selected and ran in > series. Right now we have a lot of reports that all have to be run > manually (takes a while). So I think all I need api access to is server > selection, parameter selection, and output formats. > > Any pointers in the right direction would be helpful. In my previous job we had to to almost the same thing. If I remember correctly, for batch printing or file export it was enough to start with the "CrystalRuntime.Application" class. It was something along these lines (sorry I don't have any way to test it now.): app = win32com.client.dynamic.Dispatch("CrystalRuntime.Application") report = app.OpenReport("c:/path/to/file.rpt") for table in report.Database.Tables: table.ConnectionInfo.Password = "passwd" ... The rest is modeled after Visual Basic. There are tons of examples on the net. If you want to show the report on the screen then it is another story. I only remember the following: - the application must be a mfc application - I had to "makepy" a class. I think it was "CrystalReportsViewer". - create a class derived from both pywin.mfc.activex.Control and CrViewer (look at the script generated by makepy). - create a pywin.mfc.Frame, and put there an instance of the previous class. Voil?, it's not much. In the hope that you can do something with it. But don't give up. At the end, it works... -- Amaury From aboudouvas at panafonet.gr Wed Jan 31 11:55:32 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 31 Jan 2007 08:55:32 -0800 Subject: "Correct" db adapter In-Reply-To: References: <1170253666.826691.276800@s48g2000cws.googlegroups.com> <45c0b8cd$0$5072$ba4acef3@news.orange.fr> Message-ID: <1170262532.590048.247580@a75g2000cwd.googlegroups.com> Thanks for the replies. I think i do not need something like ORM, but just a db-module that i can "work" the database with it. I just want to know if pyodbc is the "correct" solution to do so or if it is another db-module that is more usefull for this job. From http Tue Jan 23 05:27:08 2007 From: http (Paul Rubin) Date: 23 Jan 2007 02:27:08 -0800 Subject: Noob Question: Force input to be int? References: <1169546377.017596.43840@k78g2000cwa.googlegroups.com> Message-ID: <7xac0arqbn.fsf@ruckus.brouhaha.com> wd.jonsson at gmail.com writes: > print "Select a build number from 0 to " + str(len(BuildList) - 1) > buildNum = int(raw_input('Select build #> ')) > > while buildNum > (len(BuildList) -1) or buildNum <= -1: > print > print "Error: Invalid build number!" > print "Select a build number from 0 to " + str(len(BuildList) - 1) > print > buildNum = int(raw_input('Select build: ')) > > The problem is with the while buildNum-loop. If the user enters a > non-numeric value in the buildNum input, the scripts throws an > exception. I need to constrict the user to ONLY use integers in the > input box. How can I solve this issue? You can either validate the input string before trying to convert it ("look before you leap") or attempt conversion and handle the exception if you get one ("it's easier to ask forgiveness than permission"). The second pattern is generally preferable since it means you don't duplicate input validation logic all over your program. The below is untested but is a partial rewrite of your code above, intended to illustrate a few normal Python practices (I hope I haven't introduced bugs) besides the input checking: # just loop til you get a valid number, reading the number at the # top of the loop. No need to read it in multiple places. while True: # you don't have to convert int to str for use in a print statement. # the print statement takes care of the conversion automatically. print "Select a build number from 0 to", len(BuildList) - 1 buildNumStr = raw_input('Select build #> ') # attempt conversion to int, which might fail; and catch the # exception if it fails try: buildNum = int(buildNumStr) except ValueError: buildNum = -1 # just treat this as an invalid value # you can say a < x < b instead of (a < x) and (x < b) if 0 <= buildNum < len(BuildList): break # you've got a valid number, so exit the loop # print error message and go back to top of loop print print "Error: Invalid build number!" From ivoras at fer.hr Fri Jan 5 05:58:27 2007 From: ivoras at fer.hr (Ivan Voras) Date: Fri, 05 Jan 2007 11:58:27 +0100 Subject: wxWindows off-screen? Message-ID: Is it possible to draw a widget or a window in an off-screen buffer? What I'm trying to do is capture rendered HTML to a bitmap (in other words, something like html2bitmap) by using wxWindows' HTML widget. If anyone has a different way of doing it, I'd be glad to hear it... From jason at tishler.net Wed Jan 24 10:23:04 2007 From: jason at tishler.net (Jason Tishler) Date: Wed, 24 Jan 2007 10:23:04 -0500 Subject: sys.path issue in cygwin In-Reply-To: <001801c73fc3$f8c410c0$1400a8c0@mytomato> References: <002401c73f8f$b9f7da90$14fd0179@WANGSHUHAO> <20070124124355.GA1308@tishler.net> <001801c73fc3$f8c410c0$1400a8c0@mytomato> Message-ID: <20070124152304.GA3668@tishler.net> Wang, Please keep your replies on-list. On Wed, Jan 24, 2007 at 10:28:51PM +0800, Wang Shuhao wrote: > > Why not use the Python that is part of the standard Cygwin > > distribution? > > > Cause the Cygwin version python has the same problem, that why I try > to build python from source. The above implies that you may have a Cygwin installation problem that may impact other Cygwin applications too. I recommend taking this problem to the Cygwin list: http://cygwin.com/problems.html FWIW, I get the following with the official Cygwin Python version: $ python -c 'import sys; print sys.path' ['', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-cygwin', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages'] > But finally I found the solution, the PYTHONHOME environment variable > controls the content of initial sys.path. Thanks anyway. > export PYTHONHOME=/usr/localWang Shuhao IMO, the above is just a workaround, not a solution. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From mail at microcorp.co.za Sat Jan 20 01:51:49 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 20 Jan 2007 08:51:49 +0200 Subject: OT Annoying Habits (Was: when format strings attack) References: Message-ID: <01bc01c73c5f$75e8cfe0$03000080@hendrik> "Steven D'Aprano" wrote: > Or perhaps I should say: > > .snoitnevnoc > hsilgnE tpada )ylbissop revenehw( dluohs ew os dna ,naitraM ton ,puorgswen > egaugnal hsilgnE na no er'ew ,segaugnal hcus era ereht fi neve tuB First I thought it was Welsh or Cornish or something. Then it was like being in my first year of school again- reading letter by letter. Never realised how difficult it is. I suppose it will improve with practice. - Hendrik From smusnmrNOSPAM at yahoo.com Sat Jan 13 04:01:01 2007 From: smusnmrNOSPAM at yahoo.com (Siggi) Date: Sat, 13 Jan 2007 10:01:01 +0100 Subject: how to clean sys.path References: Message-ID: "Tim Roberts" wrote: >wxDemos contains the demos. The "wx" module lives in >site-packages\wx-2.8-msw-ansi. Did you leave that in? Yes! Even on this computer I am writing now with - where the whole Python programs stuff is in a programs folder, such as C:\Programs\Python25\Lib\site-packages\wx-2.8-msw-ansi - it is the same problem! > "siggi" wrote: >> >>or in plain DOS: >> >>C:\Documents and Settings\User\My Documents\My Python files >>C:\Documents and Settings\User\My Documents\Python25\Lib\idlelib >>C:\Documents and Settings\User\My Documents\Python25\python25.zip >>C:\Documents and Settings\User\My Documents\Python25\DLLs >>C:\Documents and Settings\User\My Documents\Python25\lib >>C:\Documents and Settings\User\My Documents\Python25\lib\plat-win >>C:\Documents and Settings\User\My Documents\Python25\lib\lib-tk >>C:\Documents and Settings\User\My Documents\Python25 >>C:\Documents and Settings\User\My Documents\Python25\lib\site-packages >>C:\Documents and Settings\User\My Documents\Python25\lib\site-packages\PIL >>C:\Documents and Settings\User\My >>Documents\Python25\lib\site-packages\win32 >>C:\Documents and Settings\User\My >>Documents\Python25\lib\site-packages\win32\lib >>C:\Documents and Settings\User\My >>Documents\Python25\lib\site-packages\Pythonwin >>C:\Documents and Settings\User\My >>Documents\Python25\lib\site-packages\wx-2.8-msw-ansi >> >>...it just looked horrible to me at first sight! > > It looks horrible to me, too. That's why I install applications like that > in "\Apps" instead of a document off of Documents and setings. This looks > much better: > > C:\Documents and Settings\User\My Documents\My Python files > C:\Apps\Python25\Lib\idlelib > C:\Apps\Python25\python25.zip > C:\Apps\Python25\DLLs > C:\Apps\Python25\lib > C:\Apps\Python25\lib\plat-win > C:\Apps\Python25\lib\lib-tk > C:\Apps\Python25 > C:\Apps\Python25\lib\site-packages > C:\Apps\Python25\lib\site-packages\PIL > C:\Apps\Python25\lib\site-packages\win32 > C:\Apps\Python25\lib\site-packages\win32\lib > C:\Apps\Python25\lib\site-packages\Pythonwin > C:\Apps\Python25\lib\site-packages\wx-2.8-msw-ansi > > Searching these doesn't really take very long. Remember that it doesn't > have to read all the files -- it only has to read the directories. > >>'C:\Documents and Settings\User\My Documents\My Python files', >>'C:\Documents >>and Settings\User\My Documents\My Python files\wxDemos'. Now \wxDemos\ is >>being searched very early. >> >>... no way! After running AnalogClock.py again, this error message >>appears: >> >>------------------------------------------ >>Traceback (most recent call last): >> File "C:\Documents and Settings\My Documents\My Python >>files\wxAnalogClock.py", line 14, in >> import wx >>ImportError: No module named wx. >>------------------------------------------ >> >>Very strange! Because all this wx stuff IS IN the directory 'C:\Documents >>and Settings\User\My Documents\My Python files\wxDemos'. And >>AnalogClock.py >>does work when residing in that directory. > > wxDemos contains the demos. The "wx" module lives in > site-packages\wx-2.8-msw-ansi. Did you leave that in? > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. From horpner at yahoo.com Thu Jan 18 08:50:12 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 18 Jan 2007 13:50:12 GMT Subject: One more regular expressions question References: <1169113767.320500.71200@11g2000cwr.googlegroups.com> <1169117912.193536.321260@a75g2000cwd.googlegroups.com> Message-ID: On 2007-01-18, Victor Polukcht wrote: > My pattern now is: > > (?P[^(]+)(?P\d+)\)\s+(?P\d+) > > And i expect to get: > > var1 = "Unassigned Number " > var2 = "1" > var3 = "32" > > I'm sure my regexp is incorrect, but can't understand where > exactly. Break it up using verbose notation to help yourself. Also, use more helpful names. With names like var1 and var2 you might as well not used named groups. r = re.compile(r"""(?x) (?P [^(]+ ) (?P \d+ ) \) \s+ (?P \d+ )""") This way it's clearer that there's a \) with no matching \(. -- Neil Cerutti This team is one execution away from being a very good basketball team. --Doc Rivers -- Posted via a free Usenet account from http://www.teranews.com From reply at group.invalid Tue Jan 30 01:34:17 2007 From: reply at group.invalid (Pom) Date: Tue, 30 Jan 2007 06:34:17 GMT Subject: emulate a serial port in windows (create a virtual 'com' port) Message-ID: Hello how can I emulate a serial port in windows? I want to intercept data sent to a 'com'port by a proprietary program. It sends statistics to a serial display, and I want that data in my python program (that display isn't needed). Is this possible? I've seen this kind of serial ports being created when using USB and bleutooth adapters, so i guess it's possible ??? Thanks in advance Greets Pom From deets at nospam.web.de Wed Jan 17 10:48:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 Jan 2007 16:48:41 +0100 Subject: Python Web Frameworks References: <1169048071.353887.279160@q2g2000cwa.googlegroups.com> Message-ID: <516uqpF1epsqpU2@mid.uni-berlin.de> Shortash wrote: > Python Web Frameworks weak google skills you have, young friend. http://wiki.python.org/moin/WebFrameworks Diez From rzantow at gmail.com Wed Jan 31 21:35:30 2007 From: rzantow at gmail.com (rzed) Date: Wed, 31 Jan 2007 21:35:30 -0500 Subject: win32com.client References: <1170278964.738118.219600@k78g2000cwa.googlegroups.com> Message-ID: "vithi" wrote in news:1170278964.738118.219600 at k78g2000cwa.googlegroups.com: > Hi > Any one tell me where I can get (or download) python modules > win32com or win32com.client because I have to use "Dispatch" > thanks > What distribution are you using? If you are using Windows and have downloaded the Python.org one, then, as Gary has told you: "You want the "python for windows" extension, available from http://sourceforge.net/projects/pywin32/" I think the ActiveState distro includes it as part of its package. I don't know if any of this applies if you are using Linux, VMS, etc. -- rzed From CedricCicada at gmail.com Fri Jan 19 10:48:54 2007 From: CedricCicada at gmail.com (CedricCicada at gmail.com) Date: 19 Jan 2007 07:48:54 -0800 Subject: My first try using logger didn't work. Why? Message-ID: <1169221734.071338.107190@11g2000cwr.googlegroups.com> Greetings! I want to write messages into the Windows event log. I found sevicemanager, but the source is always "Python Service", and I'd like to be a bit more descriptive. Poking around on the Internet revealed the existence of the logging module. It seems to have easily understood methods with the power I need. So I tried it. Here's my attempt: logger = logging.getLogger("TahChung Part 1") logger.setLevel(logging.INFO) eventHandler = logging.NTEventLogHandler() eventHandler.setlevel(logging.INFO) formatter = logging.Formatter("%(message)s") eventHandler.setFormatter(formatter) logger.addHandler(eventHandler) logger.error("This comes from the logger object.") I get no error messages from this, but I also don't get anything in my event log. What am I doing wrong? By the way, my source of instructions for how to do this was: http://www.onlamp.com/pub/a/python/2005/06/02/logging.html Rob Richardson RAD-CON, Inc. From torriem at chem.byu.edu Mon Jan 29 19:19:41 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Mon, 29 Jan 2007 17:19:41 -0700 Subject: Excellent Interview with Dennis D'Souza, full of laughs In-Reply-To: <1170114420.772278.7130@a75g2000cwd.googlegroups.com> References: <1170083292.991070.79560@v33g2000cwv.googlegroups.com> <45be1d27$0$97248$892e7fe2@authen.yellow.readfreenews.net> <1170087497.071441.118560@s48g2000cws.googlegroups.com> <6Mqvh.5640$fC2.95@bignews4.bellsouth.net> <1170114420.772278.7130@a75g2000cwd.googlegroups.com> Message-ID: <1170116381.6907.20.camel@contra> On Mon, 2007-01-29 at 15:47 -0800, thermate at india.com wrote: > I know this is a useless gesture, but my normal tolerance for such behavior has reached an end. Please stop spamming this list with off-topic profanities. Your ramblings have nothing to do with programming in Python (this is a computer-related group by the way) and grow tiresome. I generally tolerate occasional off-topic posts because they can be intelligent, witty, diverting, and sometimes informative and educational. However your posts are none of these things. There are plenty of forums out there for you to vent your frustrations and express your beliefs and opinions. Kindly take your musings elsewhere, particularly when you have to resort to using profanity to make up for your lack of elegant expression and inability to argue a point, or even present a point. Should this become more of a problem, I would vote in favor of moving this newsgroup to being moderated. In fact, I'd be in favor of shutting down the newsgroup entirely and using the members-only mailing list exclusively, although I know a number of people here would oppose that. From metaperl at gmail.com Thu Jan 11 10:26:15 2007 From: metaperl at gmail.com (metaperl) Date: 11 Jan 2007 07:26:15 -0800 Subject: ValueError from dict - some detail would be helpful Message-ID: <1168529175.794131.109390@77g2000hsv.googlegroups.com> File "/sw/lib/python2.5/csv.py", line 120, in _dict_to_list raise ValueError, "dict contains fields not in fieldnames" --- it would be nice if it said what field it was I know that I can do a set difference on the two myself, but since it know what wasn't there.. why not report it and save me some time? From paul.sijben at xs4all.nl Wed Jan 10 09:43:23 2007 From: paul.sijben at xs4all.nl (Paul Sijben) Date: Wed, 10 Jan 2007 15:43:23 +0100 Subject: maximum number of threads In-Reply-To: References: Message-ID: <45A4FB8B.60508@xs4all.nl> All thanks for all the input! This was very informative. Looks like I indeed need stackless as my code benefits from being concurrently designed. Paul Jean-Paul Calderone wrote: > On Wed, 10 Jan 2007 12:11:59 -0200, Felipe Almeida Lessa > wrote: >> On 1/10/07, Laurent Pointal wrote: >>> This is a system configurable limit (up to a maximum). >>> >>> See ulimit man pages. >>> >>> test >>> >>> ulimit -a >>> >>> to see what are the current limits, and try with >>> >>> ulimit -u 2000 >>> >>> to modify the maximum number of user process (AFAIK each thread use a >>> process entry on Linux) >> >> I don't think it's only this. > > Indeed you are correct. The actual limit you are hitting is the size > of your address space. Each thread is allocated 8MB of stack. 382 > threads consumes about 3GB of address space. Even though most of this > memory isn't actually allocated, the address space is still used up. So, > when you try to create the 383rd thread, the kernel can't find anyplace > to put its stack. So you can't create it. > > Try reducing your stack size or reducing the number of threads you create. > There's really actually almost no good reason to have this many threads, > even though it's possible. > > exarkun at charm:~$ python Desktop/test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > Exception raised: can't start new thread > Biggest number of threads: 382 > exarkun at charm:~$ ulimit -Ss 4096 > exarkun at charm:~$ python Desktop/test.py > 50 > 100 > 150 > 200 > 250 > 300 > 350 > 400 > 450 > 500 > 550 > 600 > 650 > 700 > 750 > Exception raised: can't start new thread > Biggest number of threads: 764 > exarkun at charm:~$ > Jean-Paul From oliphant.travis at ieee.org Wed Jan 17 16:49:08 2007 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Wed, 17 Jan 2007 14:49:08 -0700 Subject: why scipy cause my program slow? In-Reply-To: References: <1168935124.912419.147250@a75g2000cwd.googlegroups.com> Message-ID: Robert Kern wrote: > HYRY wrote: > >>Why the exec time of test(readdata()) and test(randomdata()) of >>following program is different? >>my test file 150Hz10dB.wav has 2586024 samples, so I set randomdata >>function >>to return a list with 2586024 samples. >>the exec result is: >>2586024 >> >>10.8603842736 >>2586024 >> >>2.16525233979 >>test(randomdata()) is 5x faster than test(readdata()) >>if I remove "from scipy import *" then I get the following result: >>2586024 >> >>2.21851601473 >>2586024 >> >>2.13885042216 >> >>So, what the problem with scipy? > > > You're importing (through scipy) numpy's sum() function. The result type of that > function is a numpy scalar type. The set of scalar types was introduced for a > number of reasons, mostly having to do with being able to represent the full > range of numerical datatypes that Python does not have builtin types for. > Unfortunately, the code paths that get executed when arithmetic is performed > sith such scalars are still suboptimal; I believe they are still going through > the full ufunc machinery. This should not be true in the 1.0 release of NumPy. The numpy scalars do their own math which has less overhead than ufunc-based math. But, there is still more overhead than with simple floats because mixed-type arithmetic is handled more generically (the same algorithm covers all the cases). The speed could be improved but hasn't been because it is so easy to get a Python float if you are concerned about speed. -Travis From S.Mientki-nospam at mailbox.kun.nl Tue Jan 23 15:23:26 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 23 Jan 2007 21:23:26 +0100 Subject: best package for a physical simulation? In-Reply-To: References: Message-ID: sittner at lkb.ens.fr wrote: > Hello everyone, > i would like to use python to perform some simulation involving collisions > of colloidal particles. > which is the best package/engine to do that in python? > thanks, > T > Maybe this is what you're looking for ... http://simmodel.tigris.org/ ... but I don't know if there's already something touchable ;-) cheers, Stef Mientki From nmm1 at cus.cam.ac.uk Wed Jan 10 14:29:32 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 10 Jan 2007 19:29:32 GMT Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168449342.414838.181050@p59g2000hsd.googlegroups.com> <1168452879.866265.36880@i39g2000hsf.googlegroups.com> Message-ID: In article , Sergei Organov writes: |> |> Do you mean that POSIX threads are inherently designed and implemented |> to stay idle most of the time?! If so, I'm afraid those guys that |> designed POSIX threads won't agree with you. In particular, as far as I |> remember, David R. Butenhof said a few times in comp.programming.threads |> that POSIX threads were primarily designed to meet parallel programming |> needs on SMP, or at least that was how I understood him. I do mean that, and I know that they don't agree. However, the word "designed" doesn't really make a lot of sense for POSIX threads - the one I tend to use is "perpetrated". The people who put the specification together were either unaware of most of the experience of the previous 30 years, or chose to ignore it. In particular, in this context, the importance of being able to control the scheduling was well-known, as was the fact that it is NOT possible to mix processes with different scheduling models on the same set of CPUs. POSIX's facilities are completely hopeless for that purpose, and most of the systems I have used effectively ignore them. I could go on at great length, and the performance aspects are not even the worst aspect of POSIX threads. The fact that there is no usable memory model, and the synchronisation depends on C to handle the low-level consistency, but there are no CONCEPTS in common between POSIX and C's memory consistency 'specifications' is perhaps the worst. That is why many POSIX threads programs work until the genuinely shared memory accesses become frequent enough that you get some to the same location in a single machine cycle. Regards, Nick Maclaren. From fumanchu at amor.org Thu Jan 25 03:02:19 2007 From: fumanchu at amor.org (fumanchu) Date: 25 Jan 2007 00:02:19 -0800 Subject: ANN: Dejavu 1.5.0RC1 In-Reply-To: <1169703594.951755.180990@m58g2000cwm.googlegroups.com> References: <1169703594.951755.180990@m58g2000cwm.googlegroups.com> Message-ID: <1169712139.759270.165670@l53g2000cwa.googlegroups.com> On Jan 24, 9:39 pm, "Michele Simionato" wrote: > On Jan 24, 11:57 pm, "Robert Brewer" wrote: > > The Dejavu Object-Relational Mapper (version 1.5.0RC1) is now available > > and in the public domain. Get it at http://projects.amor.org/dejavu, > > or from PyPI: http://www.python.org/pypi/Dejavu/1.5.0RC1. > > I am curious ... how this compare to SQLAlchemy? The comparisons could be endless ;) but here are some of the larger differences: 1. Dejavu uses generic "storage" concepts and syntax, while SQLAlchemy prefers database concepts and syntax. 2. Dejavu uses Python expressions (lambdas) to query storage, whereas SQLAlchemy uses functions and magic attributes: * SQLAlchemy: users.select(and_(users.c.age < 40, users.c.name != 'Mary')) * Dejavu: recall(users, lambda u: u.age < 40 and u.name != 'Mary') 3. SQLAlchemy prefers that you write data classes, table classes and the mappers between them. Dejavu only expects you to write a data class. New in 1.5: you can auto-generate even the data classes if you already have a populated database. 4. SQLAlchemy allows you to write more complicated queries (like subqueries and aggregate columns). Dejavu doesn't provide those yet (slated for 1.6). Robert Brewer System Architect Amor Ministries fumanchu at amor.org From scott.daniels at acm.org Sat Jan 13 23:55:48 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 13 Jan 2007 20:55:48 -0800 Subject: Tkinter code (with pmw) executing to soon please help In-Reply-To: References: <1168746063.322340.10410@l53g2000cwa.googlegroups.com> Message-ID: <45a9ad0a$1@nntp0.pdx.net> Gabriel Genellina wrote: >... So `callback` should return a function, like this: > > def callback(text): > def handler(event): > print text > Even better than that: def callback(text): def handler(event): print text return handler Otherwise callback returns the spectacularly un-useful value None. --Scott David Daniels scott.daniels at acm.org From steve at REMOVE.THIS.cybersource.com.au Fri Jan 26 19:08:00 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 27 Jan 2007 11:08:00 +1100 Subject: instancemethod References: <45b51298$0$8289$426a74cc@news.free.fr> <45ba2b72$0$3007$426a34cc@news.free.fr> Message-ID: On Fri, 26 Jan 2007 17:25:37 +0100, Bruno Desthuilliers wrote: >> def __del__(self): >> try: >> self.close() >> finally: >> pass >> except: >> pass > > The finally clause is useless here. In principle, closing a file could raise an exception. I've never seen it happen, but it could. From the Linux man pages: "Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota." http://www.die.net/doc/linux/man/man2/close.2.html I assume that the same will apply in Python. It has to be said, however, that the error recovery shown ("pass") is fairly pointless :-) -- Steven From pretoriano_2001 at hotmail.com Mon Jan 8 08:25:49 2007 From: pretoriano_2001 at hotmail.com (vizcayno) Date: 8 Jan 2007 05:25:49 -0800 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <45A1F1D9.8070206@v.loewis.de> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <45A1F1D9.8070206@v.loewis.de> Message-ID: <1168262749.852897.13010@q40g2000cwq.googlegroups.com> Martin v. L?wis ha escrito: > vizcayno schrieb: > > Need your help in the "correct" definition of the next function. If > > necessary, I would like to know about a web site or documentation that > > tells me about best practices in defining functions, especially for > > those that consider the error exceptions management. > > I agree with George Sakkis' remarks. The best way to define this function is > > def ExecuteSQL(cmdSQL, cursor): > return cursor.execute(cmdSQL) > > If this raises an exception, it likely means there is something > wrong with the SQL statement. The program should abort, and the > developer should correct it. > > Regards, > Martin Martin: Thanks for your indications. However, what happens when the error is due to data error. Or when the program is reading many files to save data into a database and one or two files have problems with data format. I would like to keep the program running (using exception in a controlled way) for the remaining good files and prepare a log about the failed files. How to keep the same function for a program that runs in batch, or on-line or in the web? Giving the simple example I put, I would like to find more guidelines. Thanks. From etatoby at gmail.com Sun Jan 28 10:50:40 2007 From: etatoby at gmail.com (Toby) Date: 28 Jan 2007 15:50:40 GMT Subject: Commandline wrapper: help needed References: <45bb7527$0$20806$5fc30a8@news.tiscali.it> Message-ID: <45bcc64c$0$20817$5fc30a8@news.tiscali.it> Toby A Inkster wrote: > Hello Toby, excellent name you have there. Why, thank you! > What advantage (if any) does this method have over standard UNIX-style > pipes? The advantage is being able to write my own filters and input/output modules and have as small a granularity as needed (while standard UNIX filters such as cat, grep, sed and awk process entire lines at a time.) For example I can launch an interactive shell of some kind and use it both from the terminal I opened it in, and from the network, if my script is listening on a socket. By the way, I am using standard UNIX pipes, that's how popen() works! Toby From gagsl-py at yahoo.com.ar Sun Jan 21 03:30:47 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Jan 2007 05:30:47 -0300 Subject: A solution to the MSVCRT vs MSVCR71 problem? In-Reply-To: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> References: <1169348867.369917.104970@m58g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20070121042707.0432dda8@yahoo.com.ar> At Sunday 21/1/2007 00:07, sturlamolden wrote: >Solution to problem 1: > >Compile with your compiler or choice, never mind which CRT are used. >Use a 'dumpbin' program, find all references to msvcrt in the binary >DLL file. Create a dll with name "py_crt" that exports these functions >but redirects them to msvcrt71. That is, in the file py_crt.def we put >something like > >EXPORTS >malloc=msvcr71.malloc >free=msvcr71.free >etc. > >Compile the DLL py_crt.dll and then open your pyd file in binary mode. >Exchange all occurances of the string "msvcrt" (or any other CRT name) >with "py_crt". Now your binary should work just fine. What you need to >make sure is just that the name of the proxy has the same number of >letters as the CRT your compiler linked. So if it is msvcrt81.dll, e.g. >use something like py_crt81.dll instead of py_crt.dll. > >Solution to problem 2: >[modify external references inside python25.dll to use a different runtime] This would only work, if runtime dll's were compatibles between them, and they are not. You can't blindly redirect a call to msvcr71.__xyz to msvcr80.__xyz and expect that to work magically - it may have a different number of arguments, or different types, or even may not exist anymore. (And what about any symbol exported by ordinal?) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From borntonetwork at gmail.com Sat Jan 20 10:03:12 2007 From: borntonetwork at gmail.com (borntonetwork) Date: 20 Jan 2007 07:03:12 -0800 Subject: The proper use of QSignalMapper References: <1169045073.138626.60770@l53g2000cwa.googlegroups.com> <1169049100.393777.269350@v45g2000cwv.googlegroups.com> <1169085859.586698.149400@51g2000cwl.googlegroups.com> <1169135947.039984.108930@51g2000cwl.googlegroups.com> Message-ID: <1169305392.100624.295850@11g2000cwr.googlegroups.com> David, thanks for your help. Unfortunately, all attempts of making this solution work have failed. I would be interested to know if anyone has used QSignalMapper successfully in a similar situation. For any interested, I worked around the problem using a closure, which seems a bit cleaner from a coding point of view, although I don't have any idea if it is more efficient or not: def makeHandler(self, idx): def handler(state): print 'The state is:', str(state), 'for checkbox object', str(idx) return handler Each iteration then created a new function based on the closure: self.handlers = [] for idx in range(1, maxIngredients+1): wName = 'chkProductIngredientsDelete_'+str(idx) w = self.__dict__[wName] self.handlers.append(self.makeHandler(idx - 1)) self.window.connect(w, QtCore.SIGNAL("stateChanged(int)"), self.handlers[idx - 1]) So now the output when each checkbox is clicked is something like this: The state is: 2 for checkbox object 0 The state is: 2 for checkbox object 1 ... David Boddie wrote: > borntonetwork wrote: > > Thanks, David, for you help. > > > > When I change the slot function to what you show in your second > > example, I get the same results: nothing. > > This may be due to something I missed in your code. When you > connect the signal from the signal mapper to your class, you > need to specify the signal as a C++ signature as well: > > self.connect(self.signalMapper, QtCore.SIGNAL( > "mapped(int)"), > self.deleteProductIngredient) > > The second example should now work. > > Looking at the first example, which uses SLOT() rather than specifying > a Python method, the following might be due to the way you call > connect, though it is surprising: > > > When I change it to what you > > have in your first example, I get the following: > > > > Object::connect: No such slot QApplication::map() > > Object::connect: (sender name: 'chkProductIngredientsDelete_1') > > Object::connect: (receiver name: 'main.py') > > [...] > > It looks like you should try something like this: > > self.connect(w, QtCore.SIGNAL("stateChanged(int)"), > self.signalMapper, > QtCore.SLOT("map()")) > > I can't understand why calling self.app.connect() would cause the > connection to be attempted between self.signalMapper and self.app. > > Maybe someone on the PyQt/PyKDE mailing list would be able to > explain the behaviour you're seeing: > > http://mats.imk.fraunhofer.de/mailman/listinfo/pykde > > David From antonyliu2002 at yahoo.com Fri Jan 5 01:55:59 2007 From: antonyliu2002 at yahoo.com (antonyliu2002 at yahoo.com) Date: 4 Jan 2007 22:55:59 -0800 Subject: Undefined symbol __pure_virtual when importing MySQLdb References: <1167977378.425615.220350@51g2000cwl.googlegroups.com> Message-ID: <1167980159.711978.309970@i15g2000cwa.googlegroups.com> Fredrik Lundh wrote: > antonyliu2002 at yahoo.com wrote: > > > I have googled hard, and did see someone asking the same question, but > > haven't found a good solution to this problem. Could anyone give me a > > hint? Thanks a lot! > > googling for "undefined symbol: __pure_virtual" brings up hundreds of > posts on this topic, and the answer is *always* to make sure that you're > linking with a version of the C++ libraries that matches your compiler. > > Hi, thanks. I followed the strategy provided at the following url http://www.mail-archive.com/dbi-users at perl.org/msg27851.html by adding "-lmygcc" to the end of the librarys to link. I added it to the end of this line in the mysql_config script like so: libs=" $ldflags -L$pkglibdir -lmysqlclient -lz -lcrypt -lnsl -lm -lmygcc " And then I recompiled the MySQL-python-1.2.1 package, but the same problem remains. From gagsl-py at yahoo.com.ar Wed Jan 10 05:45:57 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Jan 2007 07:45:57 -0300 Subject: Is there a way to protect a piece of critical code? In-Reply-To: <000b01c734a0$2f635840$03000080@hendrik> References: <000b01c734a0$2f635840$03000080@hendrik> Message-ID: <7.0.1.0.0.20070110074006.03fea900@yahoo.com.ar> At Wednesday 10/1/2007 07:14, Hendrik van Rooyen wrote: >I would like to do the following as one atomic operation: > >1) Append an item to a list >2) Set a Boolean indicator Wouldn't a thread.Lock object serve your purposes? -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From wolf_tracks at invalid.com Sat Jan 6 23:33:13 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sat, 06 Jan 2007 20:33:13 -0800 Subject: Just Getting Started with Python on MS XP Pro In-Reply-To: References: Message-ID: Thomas Ploch wrote: > W. Watson schrieb: >> The wiki site lead to a link to download pythonwin, but the download is >> broken. Googling invariably leads back to that link. I found >> , which has >> two files listed: oadist.exe and win32dbg.exe. Do I need both or is just the >> latter one? > > > A google query 'pythonwin' directly brings me here: > > https://sourceforge.net/projects/pywin32/ > > I think this is the place to go > > Thomas > > That gets me the python program (pywin), which I got from a URL in a post above (python-win.msi). I guess these are the same or at least just the interpreter, and do not provide the IDE-debugger. I can't get pythonwin, the debugger and IDE. The link was broken last night when I tried it. Well, let me try now. Nope, it still reports "Error 404: File Not Found" Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet ""I do not fear death. I had been dead for billions and billions of years before I was born, and had not suffered the slightest inconvenience from it." -- Mark Twain (a nod to evolution) -- Web Page: From parallelpython at gmail.com Thu Jan 11 18:41:16 2007 From: parallelpython at gmail.com (parallelpython at gmail.com) Date: 11 Jan 2007 15:41:16 -0800 Subject: Parallel Python References: <1168127555.183795.183730@v33g2000cwv.googlegroups.com> <1168417065.105920.319970@o58g2000hsb.googlegroups.com> <1168449762.738411.128240@i56g2000hsf.googlegroups.com> Message-ID: <1168558876.033624.178010@k58g2000hse.googlegroups.com> sturlamolden wrote: > parallelpyt... at gmail.com wrote: > > > That's right. ppsmp starts multiple interpreters in separate > > processes and organize communication between them through IPC. > > Thus you are basically reinventing MPI. > > http://mpi4py.scipy.org/ > http://en.wikipedia.org/wiki/Message_Passing_Interface Thanks for bringing that into consideration. I am well aware of MPI and have written several programs in C/C++ and Fortran which use it. I would agree that MPI is the most common solution to run software on a cluster (computers connected by network). Although there is another parallelization approach: PVM (Parallel Virtual Machine) http://www.csm.ornl.gov/pvm/pvm_home.html. I would say ppsmp is more similar to the later. By the way there are links to different python parallelization techniques (including MPI) from PP site: http://www.parallelpython.com/component/option,com_weblinks/catid,14/Itemid,23/ The main difference between MPI python solutions and ppsmp is that with MPI you have to organize both computations {MPI_Comm_rank(MPI_COMM_WORLD, &id); if id==1 then ... else ....} and data distribution (MPI_Send / MPI_Recv) by yourself. While with ppsmp you just submit a function with arguments to the execution server and retrieve the results later. That makes transition from serial python software to parallel much simpler with ppsmp than with MPI. To make this point clearer here is a short example: --------------------serial code 2 lines------------------ for input in inputs: print "Sum of primes below", input, "is", sum_primes(input) --------------------parallel code 3 lines---------------- jobs = [(input, job_server.submit(sum_primes,(input,), (isprime,), ("math",))) for input in inputs] for input, job in jobs: print "Sum of primes below", input, "is", job() --------------------------------------------------------------- In this example parallel execution was added at the cost of 1 line of code! The other difference with MPI is that ppsmp dynamically decides where to run each given job. For example if there are other active processes running in the system ppsmp will use in the bigger extent the processors which are free. Since in MPI the whole tasks is usually divided between processors equally at the beginning, the overall runtime will be determined by the slowest running process (the one which shares processor with another running program). In this particular case ppsmp will outperform MPI. The third, probably less important, difference is that with MPI based parallel python code you must have MPI installed in the system. Overall ppsmp is still work in progress and there are other interesting features which I would like to implement. This is the main reason why I do not open the source of ppsmp - to have better control of its future development, as advised here: http://en.wikipedia.org/wiki/Freeware :-) Best regards, Vitalii From http Wed Jan 17 18:11:09 2007 From: http (Paul Rubin) Date: 17 Jan 2007 15:11:09 -0800 Subject: How can I create a linked list in Python? References: <45ad5104$0$393$426a74cc@news.free.fr> <1169009882.408482.43360@q2g2000cwa.googlegroups.com> <45ae8950$0$31033$426a74cc@news.free.fr> <1169074382.702857.313010@11g2000cwr.googlegroups.com> Message-ID: <7xps9dl04y.fsf@ruckus.brouhaha.com> "sturlamolden" writes: > Actually, nesting tuples or lists doesn't really duplicate Lisp cons, > as one can only create a stack-like object with the nesting. Python > really need a cons type like Lisp. I think it is time to write one, in > a plain C extension. But that's what Lisp does too. As the poet said: One thing the average language lacks Is programmed use of push-down stacks. But LISP provides this feature free: A stack - you guessed it - is a tree. An empty stack is simply NIL. In order, then, the stack to fill A CONS will push things on the top; To empty it, a CDR will Behave exactly like a pop. A simple CAR will get you back The last thing you pushed on the stack; An empty stack's detectable By testing with the function NULL. Thus even should a LISPer lose With PROGs and GOs, RETURNs and DOs, He need his mind not overtax To implement recursive hacks: He'll utilize this clever ruse Of using trees as moby stacks. (http://www.gotlisp.com/lambda/lambda.txt) All Python needs is a way of displaying the lists as (a b c) instead of [a, [b, [c, None]]], and that can be done in pure Python. From nmm1 at cus.cam.ac.uk Sat Jan 20 08:19:29 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 20 Jan 2007 13:19:29 GMT Subject: OT Annoying Habits (Was: when format strings attack) References: Message-ID: In article , "Carroll, Barry" writes: |> |> My thanks to Aahz and the others who responded. I also did some |> Googling on my own. I found out that top-posting is the norm in the |> e-mail world. Bottom- and inline-posting are the norm in the newsgroup |> world. =20 Sorry, even that is not so. I have been using Email since the 1960s, and top-posting has been used only by the inconsiderate. Note that, when you include a complete document in a message (whether Email or anything else), then you should put it at the bottom. Rather like an appendix. But top-posting when you are responding to Email is as discourteous as top-posting when you are responding to newsgroups. |> So I concede the point, and I'm bottom-posting like a good citizen. =20 Excellent! Regards, Nick Maclaren. From gagsl-py at yahoo.com.ar Wed Jan 10 04:57:32 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Jan 2007 06:57:32 -0300 Subject: maximum number of threads In-Reply-To: <45a497ec$0$331$e4fe514c@news.xs4all.nl> References: <45a497ec$0$331$e4fe514c@news.xs4all.nl> Message-ID: <7.0.1.0.0.20070110064655.0508d0a0@yahoo.com.ar> At Wednesday 10/1/2007 04:38, Paul Sijben wrote: >I have a server in Python 2.5 that generates a lot of threads. It is >running on a linux server (Fedora Core 6). >The server quickly runs out of threads. > > File "/usr/local/lib/python2.5/threading.py", line 434, in start > _start_new_thread(self.__bootstrap, ()) >error: can't start new thread > >Does anyone know what it going on here and how I can ensure that I have >all the threads I need? Simply you can't, as you can't have 10000 open files at once. Computer resources are not infinite. Do you really need so many threads? Above a certain threshold, the program total execution time may increase very quickly. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From arkanes at gmail.com Wed Jan 24 12:30:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 11:30:54 -0600 Subject: Python does not play well with others In-Reply-To: References: Message-ID: <4866bea60701240930w6d048973n590ffba0c4a1f13d@mail.gmail.com> On 1/24/07, John Nagle wrote: > Harry George wrote: > > John Nagle writes: > > > You experience isn't shared by everyone. Some of us find Python the > > most functional and portable of the candidates you mention. > > The language is fine. It's the bindings to other packages that > are the problem. There are three different packages for talking > to OpenSSL, and they're all broken in some important way. > > What's actually needed on the SSL side, I think, is to > add bindings to the built-in SSL to export the functionality > the M2Crypto C binding module has. Preferably with better > attention to reference count problems, and without using SWIG. > Then move over the Python portions of M2Crypto. > > Some problems, all of which are known and logged bugs: > > - The built in SSL package doesn't actually validate anything, > and will happily accept bogus SSL certificates. > - The built in SSL package doesn't allow access to most of the > fields of an SSL certificate, and the ones you can get > are returned in a debug format that's not parseable. > - M2Crypto has OpenSSL and SWIG version dependencies beyond > what is documented. The latest version of SWIG has > a problem which breaks builds with older versions of > OpenSSL. > - M2Crypto may still have a memory leak associated with contexts. > (Check out "close" in "Context".) > - M2Crypto doesn't understand SSL certificates which support > a list of sites. > - M2Crypto and the socket library don't play nice about timeouts. > > Most of these problems have been known for years. The last person to > try to fix this was treated so badly he stopped contributing. Read > the bug history for "[1114345] Add SSL certificate validation". > It's sad. > Just to be clear: The problem here is "my personal itch is not being scratched by other people for me", not "Python doesn't play well with others". You are not any more important than anyone else and assuming that anyone cares about your problems is a major fallacy. You have a specific library that doesn't meet your needs, and that you are not interested in maintaining yourself, so you are attempting to leverage some sort of community guilt trip to get other people to do it for you. That's dishonest and off-putting. Not everyone has the ability or desire to contribute. That is fine. They might even ask if anyone is interested in doing it for them, which is also fine - there are many people who enjoy working on something that is of use to others, even if it's not important to them personally. But stop acting like you're entitled to special consideration, or that the "Python community" is failing some sort of duty by not catering to you specifically. From morpheus at spamhater.too Thu Jan 25 11:03:02 2007 From: morpheus at spamhater.too (Morpheus) Date: Thu, 25 Jan 2007 17:03:02 +0100 Subject: wxPython: panel not fully painted References: <1169674550.837006.304370@q2g2000cwa.googlegroups.com> Message-ID: On Wed, 24 Jan 2007 13:35:51 -0800, citronelu wrote: > Hi, > > I'm new to wxpython, and the following code is my first serious > attempt: > > > #~ start code > import wx > > class MyPanel(wx.Panel): > def __init__(self, parent, id): > wx.Panel.__init__(self, parent, id) > self.parent = parent > button = wx.Button(self, -1, "Refresh") > button.SetPosition((100, 100)) > button.SetFocus() > > self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button) > > def OnCloseMe(self, event): > self.parent.f_redraw(self) > pass > > > class MyFrame(wx.Frame): > def __init__( > self, parent, ID, title, pos=wx.DefaultPosition, > size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE > ): > > wx.Frame.__init__(self, parent, ID, title, pos, size, style) > > def f_redraw(self, kill_window): > kill_window.Destroy() > MyPanel(self, -1) > #~ self.SendSizeEvent() > > > wxApp = wx.App() > f = MyFrame(None, -1, "App Title") > MyPanel(f, -1) > f.Show() > wxApp.MainLoop() > > > #~ end code > > > My problem is: when I press the "refresh" button, the new panel is > painted only as a 20x20 pixels square on the top right side of the > frame. If I resize the frame, the panel is repainted correctly (that's > why I inserted the self.SendSizeEvent() line - commented above). > > Is there something I'm missing, or this is normal ? > > I'm using python 2.4.3 and wxpython 2.8.1.1 unicode, on WinXP SP2. > Windows extensions are also installed. Consider using sizers, you'll need them anyway. They do such things for you, and many other things too. The help file has a good chapter on this: Working with sizers. Kind regards Morpheus From Eugene.Antimirov at portaone.com Tue Jan 23 07:21:09 2007 From: Eugene.Antimirov at portaone.com (Eugene Antimirov) Date: Tue, 23 Jan 2007 14:21:09 +0200 Subject: Working with shared folders In-Reply-To: <1169549029.039191.87240@s48g2000cws.googlegroups.com> References: <1169549029.039191.87240@s48g2000cws.googlegroups.com> Message-ID: <45B5FDB5.8050206@portaone.com> Marcpp wrote: > Any idea to work with windows shared folders? > Which library is needed to execute console comands? > Don't you want to look at fusesmb first and then work with windows files and dirs as well as with any others. -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer support at portaone.com * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ From richie at entrian.com Mon Jan 22 03:53:38 2007 From: richie at entrian.com (Richie Hindle) Date: 22 Jan 2007 00:53:38 -0800 Subject: PyMeld for html templates? References: <1169241497.610167.130580@a75g2000cwd.googlegroups.com> Message-ID: <1169456018.120120.324230@q2g2000cwa.googlegroups.com> [Sean] > The pymeld docs show examples only for the Python command line > interpreter and show using the print statement to output stuff. But > using mod_python.apache, I think you need to use req.write(something) > format. And of course, this fails when you feed it output from Meld. req.write(str(meld)) ? -- Richie Hindle richie at entrian.com From stj911 at rock.com Tue Jan 30 18:47:44 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 30 Jan 2007 15:47:44 -0800 Subject: BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job Message-ID: <1170200864.492655.11850@s48g2000cws.googlegroups.com> http://portland.indymedia.org/en/2006/06/341238.shtml BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job author: Jacob Hamblin Based on chemical analysis of WTC structural steel residue, a Brigham Young University physics professor has identified the material as Thermate. Thermate is the controlled demolition explosive thermite plus sulfur. Sulfur cases the thermite to burn hotter, cutting steel quickly and leaving trails of yellow colored residue. [ photo: wtc steel with diagonal cut, thermate residue ] Prof. Steven Jones, who conducted his PhD research at the Stanford Linear Accelerator Center and post-doctoral research at Cornell University and the Los Alamos Meson Physics Facility, has analyised materials from WTC and has detected the existence of thermate, used for "cutting" the steel support columns, as evident in the photo below. Dr. Jones is a co-founder of Scholars for 911 Truth. Dr. Jones in earlier work pointed to thermate as the likely explosive that brought down the WTC1, WTC2, and WTC7 skyscrapers. But only recently was physical material analysed in the lab and the presense of thermate announced. The samples were provided Dr. Jones team from redundant sourses. Both BYU and Prof. Jones have been offered additional grants if he would "change the direction" of his research. In addition, there have been threats made by an individual who "is taking action" to stop Steven Jones' research, specifically his experiment with thermites (aluminothermics), on the grounds his work may be helpful to "terrorists". Jones notes that much more detailed information on both thermite and thermate is readily available on the internet. add a comment on this article summary of 10 recent thermite/thermate posts 17.Jun.2006 15:59 foward me to someone link [COMMENTARY: in time order of article theme on thermite at WTCs, videos, discussion, pictures; [1] since thermite/thermate can be made of basic industrical chemicals, it can be made "tracerless"--i.e., avoid all signature tracer chemicals that the U.S. Govt requires be mixed in very small amounts in all highly powerful and highly monitored explosives to keep track of every batch's origin. [2] Moreover if he has found it in WTC7, as he says, then with Silverstein admitting that he conducted a controlled demolition on 9-11 of WTC7 around 5:30 p.m., then Silverstein is admitting that WTC1, WTC2, and WTC7 all are thermate controlled demolitions. [3] And who was in charge of WTC security? Why, Marvin Bush, brother of George W. Bush, on the board of Securatech. [4] And written up in their mom's (ghostwritten) autobiography, Barbara Bush drops the other bombshell that it's just a coincidence that Marvin's contract at the WTCs was up on September 11, 2001 anyway. She wrote about it in the book! [5] The Bush family through Marvin Bush have been in charge of security of the WTCs since immediately after the first failed terrorist attempt to knock down the WTCs one month into Clinton's Presidential tenure in 1993. [6] The FBI is on record giving the order to conduct terrorism on the WTC in 1993, via their hired gun Salam, who didn't want to carry out the attack 'for real' since he was told by the FBI that he was hired simply for a sting opreation to arrest some perpetrators in a terror cell he infiltrated for the FBI. [two minute video summary on this: http://video.google.com/videoplay?docid=6752092058844526234 [7] When the FBI instead told him to both suggest the WTC as a target for the 1993 attack, as well as teach them how to make bombs, as well as FBI allowing him to provide live explosives--their agent started taping everything covertly that he was ordered to do in reference to FBI ordering him to carry out the 1993 terrorist attack on the WTCs. [8] Immediately after the failed attack on the WTCs, the Bush family, through a corporate shell vehicle owned in part by the royal family of Kuwait, the Kuwaiti/American Corporation, was put in charge of security at the WTCs, with Marvin Bush on board. [9] Seven weeks before the controlled demolitions of 9-11, the towers change hands in their first (rushed) sale, being all bought up by Silverstein, who introduces a huge terrorism insurance appendage. [10] Despite admitting publicly that HE gave the order (in the PBS special "America Rebuilds") to blow up his own WTC7 on 9-11, the whole thing is so corrupt that he still collects 500 million dollars on the "terrorist destuction alibi" of WTC7, and has already collected several billion dollars on the 'terrorism clause' in the WTC1/2 insurance. [11] and We already know that the anthrax that was sent to congress and which killed several postal workers in the process (sent to Senator Daschle and to Senator Leahy), was weaponized under a covert CIA only contract, and it was a domestic Ames strain of anthrax coming from one of three or four of the U.S. bioweapons labs.[12] The "Patriot Act" was already written up before 9-11, just required a whiff of domestic anthrax to force passage with a bit more bio-terrorism on the Congress itself by domestic terrorists; [13] Bush and his whole Cabinet of course were out of danger: they were taking an anthrax exclusive drug to counter it, from September 11 onward, so when the anthrax hit in early October in DC, Bush's staff would be immune to the domestic-in- origin anthrax terrorism. The interesting point of course is Bush's whole team all psyched up and anticipating an anthrax attack one month in advance--which just so happens to be the incubation time for the anthax bacilli--I could go on ad nauseum. The whole U.S. government is a terrorist unit, operating under the guise of its counter terrorism squads.] summary: --------------------------------------------- Dr. Jones is a co-founder of Scholars for 911 Truth. "If Dr. Jones's work ever breaks into the mainstream media, and the rest of the country reacts the way the Utah County audience reacted, traditional political divisions will evaporate like steel beams exploded with thermite, and the whole lot of them, the Democrats and the Republicans, will be swept away, along with the military- industrial complex that has apparently managed to subvert the constitution of these United States and to con the American public, mesmerized by the shock of 9/11 and hypnotized by spell-binding incantations of freedom and patriotism, into going along with their mad plans for world domination." BYU Physics Prof Finds Thermate in WTC Physical Samples, Building Collapses an Inside Job.....Based on chemical analysis of WTC structural steel residue, a Brigham Young University physics professor has identified the material as Thermate. Thermate is the controlled demolition explosive thermite plus sulfur. Sulfur cases the thermite to burn hotter, cutting steel quickly and leaving trails of yellow colored residue. [see video comparisons of thermite/ate here and compare to WTC photos and live video below--both video links available from here: http://portland.indymedia.org/en/2006/04/338202.shtml ] Dr. Jones in earlier work pointed to thermate as the likely explosive that brought down the WTC1, WTC2, and WTC7 skyscrapers. But only recently was physical material analysed in the lab and the presense of thermate announced. The samples were provided Dr. Jones team from redundant sourses. INTERESTING HIGHER UP BRIBE AND THREAT COMING IN TO PLAY: ***"Both BYU and Prof. Jones have been offered additional grants if he would "change the direction" of his research. In addition, there have been threats made by an individual who "is taking action" to stop Steven Jones' research,*** specifically his experiment with thermites (aluminothermics), on the grounds his work may be helpful to "terrorists". Jones notes that much more detailed information on both thermite and thermate is readily available on the internet." From python.leojay at gmail.com Tue Jan 16 22:34:00 2007 From: python.leojay at gmail.com (Leo Jay) Date: Wed, 17 Jan 2007 11:34:00 +0800 Subject: How can I write code using FP In-Reply-To: <1169003899.592015.300290@s34g2000cwa.googlegroups.com> References: <1169003899.592015.300290@s34g2000cwa.googlegroups.com> Message-ID: <4e307e0f0701161934i5c143878g7f2825886cf323d4@mail.gmail.com> On 16 Jan 2007 19:18:19 -0800, kernel1983 wrote: > > In Function Program?Language can use like this: > > define a function: > f = lambda x,y:x,y > > then we use f to define another function: > f2 = f(1) > the f2 should equal to: > f2=lambda y:1,y > > we should be able call f2 with one parameter:f2(2) > just return 1,2 > > but how can I implement the characteristic in Python??I think it could > do like this but HOW-TO? > > thanks~~~ > I'm a English beginner! > I wish somebody understand my meaning > > try this: foo = lambda x, y: (x, y) foo1 = lambda x: foo(x,1) foo2 = lambda y: foo(1,y) print foo1(3) print foo2(3) -- Best Regards, Leo Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Fri Jan 5 13:21:46 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 05 Jan 2007 11:21:46 -0700 Subject: When argparse will be in the python standard installation In-Reply-To: <459e18db$0$17143$9b622d9e@news.freenet.de> References: <1167840708.209024.53810@k21g2000cwa.googlegroups.com> <459C008D.5040404@v.loewis.de> <459CBAC8.9060007@v.loewis.de> <64mdnTE_-5Ff3gDYnZ2dnUVZ_q6vnZ2d@comcast.com> <459e18db$0$17143$9b622d9e@news.freenet.de> Message-ID: <459E973A.3010102@gmail.com> [Thanks for looking through all these Martin!] Martin v. L?wis wrote: > Steven Bethard schrieb: >> * alias ArgumentParser to OptionParser >> * alias add_argument to add_option >> * alias Values to Namespace >> * alias OptionError and OptionValueError to ArgumentError >> * alias add_help= keyword argument of ArgumentParser to add_help_option= >> * alias namespace= keyword argument of parse_args to options= > > Not sure what you mean by "alias": I don't think the argparse names > should be retained (unless you feel they describe things better). They do describe things a bit better. Given a command line like:: prog --opt1 o --opt2 pos1 pos2 pos3 optparse can only parse out the optional command line arguments, ``--opt1 o --opt2``, hence it uses names like ``add_option``. On the other hand, argparse can parse the entire command line (including the positional arguments ``pos1 pos2 pos3``) so it uses ``add_argument`` instead of ``add_option``. >> * ArgumentParser.parse_args returns a single namespace object, not an >> (options, args) tuple, since argparse handles positional arguments. >> This could probably be addressed by adding an __iter__ method to the >> Namespace object which would return (self, []) > > I find that I'm not that familiar with command line arguments :-) > > To understand that difference, I would have to see examples of both, > and why it is better to return a single result. A brief example to illustrate the differences. Here is a program that reads the command-line args and writes the sum to a log file specified by --log. With optparse, this would look something like:: parser = optparse.OptionParser() parser.add_option('--log') options, args = parser.parse_args() if options.log is not None: logfile = open(options.log) else: logfile = sys.stdout try: integers = [int(arg) for arg in args] except ValueError: parser.error('positional arguments must be integers') logfile.write('%s\n' % sum(integers)) logfile.close() Since argparse handles positional arguments as well as optional arguments (and since it accepts type='outfile') the argparse version is much more concise:: parser = argparse.ArgumentParser() parser.add_argument('integers', type=int, nargs='+') parser.add_argument('--log', type='outfile', default=sys.stdout) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() So basically, since argparse parses the entire command line (instead of just the optional parts) there is no concept of "remaining command line arguments" -- *all* command line arguments have become attributes of the namespace returned by parse_args(). Thus, while optparse has to return both a namespace and the unparsed portion of the command line, argparse only has to return the namespace. >> * argparse makes the default value for a "store_true" action False, and >> the default value for a "store_false" action True. This is what users >> expect, but different from optparse where the default is always None. > > Could we deprecate "store_false" with no default? That's probably reasonable. In Python 3.0, the default could then become the appropriate one. > It may be that users expect to see True and False, but how can you find > out whether the option was given or not afterwards? For both optparse and argparse, with "store_false", you know the option was not given if the stored value is something other than ``False``, and with "store_true", you know the option was not given if the stored value is something other than ``True``. With optparse, that "something other" is always ``None`` which is unfortunate because it makes the following code fail:: parser = optparse.OptionParser() parser.add_option('--not-foo', action='store_false') options, args = parser.parse_args() if options.not_foo: # do something The ``do something`` block will execute every time because ``options.not_foo`` is either ``False`` or ``None``, both of which indicate that the if-statement should not be executed. In argparse, the code above works fine because the default is ``True`` instead of ``None``. > Alternatively, could the actions become keyword arguments (with the > action argument only preserved for backwards compatibility)? E.g. > > parser.add_option("-v", store_true_into="verbose") > parser.add_option("-q", store_false_into="verbose") > (same for store, append, count, callback) It looks like you're trying to merge the ``dest=`` and ``action=`` functionality, but I'm not sure I understand where this is going... >> * the choices argument is now checked *after* arguments have been >> type-converted. This is intentional, so that you can specify, say >> xrange(100) instead of ["0", "1", "2", "3", ... "99"]. There is also >> no "choices" type anymore since any action can also specify their >> choices. > > As an incompatible change, this could be warned-about if the type is not > string, yet the first choice is. > > Alternatively, we could require users that pass converted values to > specify converted_choices=True in 2.6, and warn all users that don't > pass a converted_choices flag, and then flip the default in 2.7 and 3.0. > Then current users had a quick fix to silence the warning, and new > users could drop the extra flag in the future. That seems reasonable. >> I could probably add callback actions by creating an appropriate >> Action subclass and registering it. However, any code relying on >> parser.{largs,rargs,values} would break because the parsing algorithm >> is completely different in argparse. > > If you can find a way to make callbacks work in the "common case", > this flag could be deprecated and removed. Sounds good. >> I guess I don't know how to proceed from here. I'm reluctant to start >> adding the code necessary to support even the easily solved issues when >> the issues that I don't know how to solve seem like they could be deal >> breakers. > > This asks for a PEP. The views above are mine only, others may feel > differently. Ok. I'll try to write a PEP up this week. Thanks again for all your useful feedback! STeVe From george.sakkis at gmail.com Tue Jan 2 17:30:53 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 2 Jan 2007 14:30:53 -0800 Subject: array of class References: <459ad4f7$0$293$426a34cc@news.free.fr> Message-ID: <1167777053.152492.3460@v33g2000cwv.googlegroups.com> Bruno Desthuilliers wrote: > FWIW, I guess that what you want here may looks like this: > > class Word(object): > def __init__(self, word=''): > self._word = word > def __repr__(self): > return "" % (self._word, id(self)) > > > words = [] > for w in ['this', 'is', 'probably', 'what', 'you', 'want']: > words.append(Word(w)) > print words Or more compactly: words = [Word(w) for w in 'this is probably what you want'.split()] print words George From rschroev_nospam_ml at fastmail.fm Sat Jan 20 11:25:03 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 20 Jan 2007 16:25:03 GMT Subject: **argv can't work In-Reply-To: References: Message-ID: Steven D'Aprano schreef: > Its because of an evil terrorist plot. I suggest you invade Belgium, that > should fix it. Please notify me in time so I can emigrate before it's too late. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From adonis at REMOVETHISearthlink.net Sun Jan 28 22:44:09 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Mon, 29 Jan 2007 03:44:09 GMT Subject: Convert from unicode chars to HTML entities In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > I have a string containing Latin-1 characters: > > s = u"? and many more..." > > I want to convert it to HTML entities: > > result => > "© and many more..." > > Decimal/hex escapes would be acceptable: > "© and many more..." > "© and many more..." > > I can look up tables of HTML entities on the web (they're a dime a > dozen), turn them into a dict mapping character to entity, then convert > the string by hand. Is there a "batteries included" solution that doesn't > involve reinventing the wheel? > > Its *very* ugly, but im pretty sure you can make it look prettier. import htmlentitydefs as entity s = u"? and many more..." t = "" for i in s: if ord(i) in entity.codepoint2name: name = entity.codepoint2name.get(ord(i)) entityCode = entity.name2codepoint.get(name) t +="&#" + str(entityCode) else: t += i print t Hope this helps. Adonis From jeremy+complangpython at jeremysanders.net Wed Jan 10 11:13:12 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 10 Jan 2007 16:13:12 +0000 Subject: maximum number of threads References: Message-ID: Jean-Paul Calderone wrote: > Indeed you are correct. The actual limit you are hitting is the size > of your address space. Each thread is allocated 8MB of stack. 382 > threads consumes about 3GB of address space. Even though most of this > memory isn't actually allocated, the address space is still used up. So, > when you try to create the 383rd thread, the kernel can't find anyplace > to put its stack. So you can't create it. Interesting. That's why I can get over 3000 on my x86-64 machine... Much more address space. -- Jeremy Sanders http://www.jeremysanders.net/ From walter at livinglogic.de Tue Jan 30 11:28:52 2007 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Tue, 30 Jan 2007 17:28:52 +0100 Subject: Unicode error handler In-Reply-To: References: Message-ID: <45BF7244.9080802@livinglogic.de> Rares Vernica wrote: > Hi, > > Does anyone know of any Unicode encode/decode error handler that does a > better replace job than the default replace error handler? > > For example I have an iso-8859-1 string that has an 'e' with an accent > (you know, the French 'e's). When I use s.encode('ascii', 'replace') the > 'e' will be replaced with '?'. I would prefer to be replaced with an 'e' > even if I know it is not 100% correct. > > If only this letter would be the problem I would do it manually, but > there is an entire set of letters that need to be replaced with their > closest ascii letter. > > Is there an encode/decode error handler that can replace all the > not-ascii letters from iso-8859-1 with their closest ascii letter? You might try the following: # -*- coding: iso-8859-1 -*- import unicodedata, codecs def transliterate(exc): if not isinstance(exc, UnicodeEncodeError): raise TypeError("don'ty know how to handle %r" % r) return (unicodedata.normalize("NFD", exc.object[exc.start])[:1], exc.start+1) codecs.register_error("transliterate", transliterate) print u"Fr?d?ric Chopin".encode("ascii", "transliterate") Running this script gives you: $ python transliterate.py Frederic Chopin Hope that helps. Servus, Walter From robin at NOSPAMreportlab.com Mon Jan 15 18:30:37 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Mon, 15 Jan 2007 23:30:37 +0000 Subject: ReportLab - Frames - Images In-Reply-To: <1168898486.300488.264920@a75g2000cwd.googlegroups.com> References: <1168898486.300488.264920@a75g2000cwd.googlegroups.com> Message-ID: <45AC0E9D.80104@jessikat.plus.net> Chuck wrote: > I have been trying all day to get this to work. My complete code is > below. I can get my text into the PDF, I can get my image in the PDF. > What I can't get to work is frames so that the image (logo) appears to > the right of the text. The image always appears first and then the text > below on the next line. > > Please help. you'll get more help at the reportlab users list (see http://two.pairlist.net/pipermail/reportlab-users/ ) Anyhow I got some output from your script, by making two changes > *************** CUT *********************** > from reportlab.pdfgen import * .......... > > pdf = SimpleDocTemplate('bill2.pdf', pagesize = letter) > > #need a style > normal = ParagraphStyle('normal') > > doc.append(Image("pic.jpg", 100, 71)) #Logo > > para = Paragraph("Some text1", normal) > doc.append(para) > para = Paragraph("Some text2", normal) > doc.append(para) > para = Paragraph("Some text3", normal) > doc.append(para) > para = Paragraph("Some text4", normal) > doc.append(para) > para = Paragraph(" ", normal) > doc.append(para) > doc.append(HRFlowable(color="black", thickness=3, width="100%")) change(1) doc.append(flowables.HRFlowable(color="black", thickness=3, width="100%")) > > > pdf.build(doc,bill) change(2) pdf.build(doc) > > run() > *************************** CUT *********************************** > I also had to change the name of the image to one on my system. Hope this helps -- Robin Becker From martin at v.loewis.de Sun Jan 28 17:05:59 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 28 Jan 2007 23:05:59 +0100 Subject: Trouble with max() and __cmp__() In-Reply-To: <1170019291.084041.150780@h3g2000cwc.googlegroups.com> References: <1170017167.165222.325800@a34g2000cwb.googlegroups.com> <1170019291.084041.150780@h3g2000cwc.googlegroups.com> Message-ID: <45BD1E47.2080704@v.loewis.de> Thomas Nelson schrieb: > On Jan 28, 3:13 pm, Wojciech Mu?a > wrote: >> Define method __gt__. > > This works, thanks. I was a little surprised though. is __cmp__ used > by any builtin functions? It is used by max() if the object doesn't implement __gt__. Regards, Martin From ptmcg at austin.rr._bogus_.com Fri Jan 12 09:40:21 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 12 Jan 2007 08:40:21 -0600 Subject: How much slower is dict indexing vs. list indexing? References: <1168555253.601611.258600@k58g2000hse.googlegroups.com> <1168611039.720278.13430@s34g2000cwa.googlegroups.com> Message-ID: <45a79dd5$0$7646$4c368faf@roadrunner.com> "Emin" wrote in message news:1168611039.720278.13430 at s34g2000cwa.googlegroups.com... > On Jan 11, 5:53 pm, Steve Holden wrote: >> >> What technique were you thinking of to look up the cached index values >> in Python, just as a matter of curiosity? Storing them in a dict? It >> would be hard to think of a faster way ... ;-) > > I didn't have anything fancy in mind. I was just wondering whether it > makes sense to replace a block of code like > > data = {'a' : 1, 'b' :2, 'c' : 3} > for i in someLargeList: > for name in ['a','b','c']: > result.append(data[name]) > > with somthing like > > data = {'a' : 1, 'b' :2, 'c' : 3} > dataValues = [data[k] for k in ['a','b','c'] > for i in someLargeList: > for index in [0,1,2]: > result.append(dataValues[index]) > [Your as-posted code doesn't run, you are missing a trailing ']' in your list comprehension. ] So what you want is this? 1. Get the values from the data dict in order of their key, ['a','b','c'] (which is not the same as getting the data.values() list, which is in unpredictable order) 2. For every element in some larger list, append each of the elements in order from step 1 to some other result list. First of all, realize that: > for index in [0,1,2]: > result.append(dataValues[index]) is the same as result.extend(dataValues) assuming that dataValues has exactly 3 elements in it. Second, why are you iterating over someLargeList? You are doing nothing with i, and neither the data dict nor the dataValues list changes as you iterate. This will do the job more quickly, I should think: data = {'a' : 1, 'b' :2, 'c' : 3} dataValues = [data[k] for k in ['a','b','c']] result.extend( dataValues * len(someLargeList) ) -- Paul From martin at v.loewis.de Wed Jan 3 10:43:03 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 Jan 2007 16:43:03 +0100 Subject: Why does Python never add itself to the Windows path? In-Reply-To: <1167543262.361311.123700@v33g2000cwv.googlegroups.com> References: <1167009405.771413.122790@i12g2000cwa.googlegroups.com> <1167543262.361311.123700@v33g2000cwv.googlegroups.com> Message-ID: <459BCF07.6080302@v.loewis.de> vbgunz schrieb: > I don't understand what all the fuss is about. Add a single page to the > installer and on it, have 3 radio buttons. The choices could be "add to > path (recommended)", "add to path with version", "do not add to path > (not recommended)". Please submit a patch to sf.net/projects/python that does so. Regards, Martin From istvan.albert at gmail.com Thu Jan 11 09:18:05 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: 11 Jan 2007 06:18:05 -0800 Subject: Need startup suggestions for writing a MSA viewer GUI in python References: Message-ID: <1168525085.580490.76860@i39g2000hsf.googlegroups.com> Joel Hedlund wrote: > ideas from you people to get me going in the right direction. Despite my > GUI n00b-ness I need to get it good and usable with an intuitive look > and feel. UI design requires a different skillset than programming. It can be a very frustrating and thankless task as well. It is incomparably easier to see the flaws in existing interfaces than correcting them (or even creating the said interface). Make sure to start with something simple, and learn that way. I would also recommend that you implement something novel, there are many existing MSA viewers and it won't be easy to improve on them. Do something that adds new value and people will be willing to expend effort to use it. i. From hg at nospam.org Thu Jan 18 01:25:24 2007 From: hg at nospam.org (hg) Date: Thu, 18 Jan 2007 07:25:24 +0100 Subject: what can be used in a signal handler Message-ID: <3zKrh.30692$sE7.26486@newsfe21.lga> Hi, I posted an equivalent question earlier ... but am still not sure: I currently (under Linux) have a program that uses Queue.put (raw_input('')) in a signal handler and Queue.get() in the main/only thread. It works but I want to know if it is legal / what type of synchro API I have the right to use in a signal handler. Regards, hg From ptmcg at austin.rr._bogus_.com Tue Jan 9 01:45:56 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 9 Jan 2007 00:45:56 -0600 Subject: Colons, indentation and reformatting. (2) References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> Message-ID: <45a33a24$0$7658$4c368faf@roadrunner.com> "Paddy" wrote in message news:1168323368.592642.314130 at i15g2000cwa.googlegroups.com... >I was just perusing a Wikipedia entry on the "off side rule" at > http://en.wikipedia.org/wiki/Off-side_rule . > It says that the colon in Python is purely for readability, and cites > our FAQ entry > http://www.python.org/doc/faq/general.html#why-are-colons-required-fo... > . > However, near the top of the Alternatives section, it states that for C > type, curly braces using languages: > "An advantage of this is that program code can be automatically > reformatted and neatly indented without fear of the block structure > changing". > > Thinking about it a little, it seems that a colon followed by > non-indented code that has just been pasted in could also be used by a > Python-aware editor as a flag to re-indent the pasted code. > > Tell me it is not so, or I will be editing the Wikipedia page I think. > > - Paddy. > No, the ambiguity comes in when you have a nested construct within another nested construct. Here is some (fake) code where all the indentation was lost after pasting through a badly-behaved newsreader (this is NOT real code, I know that it wont really run, I'm just trying to demonstrate the indentation issue): while x: a = 100 if b > 3: a += 1 b += 1 Here are some valid indented versions: while x: a = 100 if b > 3: a += 1 b += 1 while x: a = 100 if b > 3: a += 1 b += 1 while x: a = 100 if b > 3: a += 1 b += 1 while x: a = 100 if b > 3: a += 1 b += 1 The colons alone are not sufficient to tell us which is correct. -- Paul From arkanes at gmail.com Wed Jan 24 10:32:40 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Jan 2007 09:32:40 -0600 Subject: My python programs need a GUI, wxPython or PyQt4? In-Reply-To: References: <45b69f63$0$24463$88260bb3@free.teranews.com> Message-ID: <4866bea60701240732j469de8b1u12a5a6ff7961a68b@mail.gmail.com> On 1/24/07, Giovanni Bajo wrote: > On 24/01/2007 1.45, Joshua J. Kugler wrote: > > >> I've downloaded both the wxPython and the PyQt4 package, and by the > >> first impression I must say that the PyQt4 system had a very > >> compelling presentation. From what I can understand from the feedback > >> I've gotten so far is that the wxPython is a better choice when it > >> comes to compability (with linux), and it's free even if I want to > >> create applications and sell them. > >> So, from what I understand I will have to go with PyQt4 since (from > >> my understanding): > >> 1. I will not sell the applications I'm working with since they will > >> only be used by the internal QA at a computer game company. > > > > Even that is getting on shaky ground, at least according to Troll Tech. > > See: http://www.trolltech.com/developer/knowledgebase/190/ So, write it > > for internal use, and put up for distribution on your personal web site > > (pending company approval, of course). > > That page is legal babble, trying to trick you into buying (or making your > boss buy) a commercial license. The Qt Open Source edition *IS* GPL and thus > it falls under all the normal GPL clauses and uses, irrespective of what > Trolltech may or may not think. > > For instance, see this FAQ: > http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic > > which makes pretty clear that a "company"/"organization" is basically the same > of an "individual". "Releasing a software within a company for internal usage" > is by no means the same of "releasing it to the public". Basically, for what > the GPL is concerned, it is *not* a "release" or a "distribution" at all. > I should point out that the FSFs position in this regard is not supported by copyright law and that the fact that Trolltech takes a different position is something that you should consider strongly. If the FSFs position were true, there would be no need for per-seat licensing of commercial software (because internal distribution wouldn't be). US copyright law does not draw a distinction between "internal distribution" and any other kind, and I'm not aware of any case law that does so either. This distinction is also not codified in the GPL itself anywhere, so it's not a necessary condition of the license - it is an interpretation by the FSF and that is all. > Thus, it is well possible to write internal GPL software, using the Qt Open > Source library, and to release/distribute/use it *ONLY* internally. Also, it > should be made clear that a company can of course relicense its own > proprietary libraries as GPL for internal usage only, so that they can be > linked to other GPL libraries "legally". For instance, in the case of Daniel > and his game company, they can link their proprietary game code to PyQt4 (Open > source edition) to produce an internal tool, like a level editor, which would > then fall under the GPL. If and only if they were to release that tool to the > public (either for free or for sale), they would have to either go GPL and > release full source code (include the parts of their game code linked to it), > or buy a Qt commercial license. > > [[ Another page of similar babble is the one where they try to convince you > that you cannot use the Qt Open Source edition to develop a software, and then > buy the commercial edition only the day before you want to release it as non > open-source. I can't even understand how they can even try to support such a > nonsense position. You're free to develop your software for years as GPL > without distributing it, and then relicense your own code whenever you want. > They're obviously just trying to scare people. ]] > -- Trolltech can do this because they won't sell you a commercial license if they think you've been using the GPL version to develop. It's a practical limitation, not a legal one. From gagsl-py at yahoo.com.ar Fri Jan 26 22:33:54 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 27 Jan 2007 00:33:54 -0300 Subject: Problem embedding the Python interpreter and importing win32extensions References: Message-ID: escribi? en el mensaje news:OF3B0F680E.702A5F55-ON8525726F.0065766F-8525726F.0066AF6D at is002023.gdls.com... > I am using python 2.2.3, because I am using some dSpace software > (controldesk/automationdesk) that is based upon that version of python. I > have some pre-compiled python modules that come with the dspace > applications. I am pretty sure that those modules use win32com or > pythoncom. I want to use those modules from a C/C++ application or DLL via > an embedded interpreter. I can make it work, but it only works once. I get > an error trying to import those modules again, even after uninitializing > the interpreter (Py_Initialize) and re-initializing it (Py_Uninitialize). > I thought may be using a new sub-interpreter would help but it doesn't so > now I have no idea what I could try. Any ideas? Unfortunately there is no way to uninitialize an extension module (no "unload(module)" exists). So Py_Uninitialize doesn't fully reset the environment. Try to avoid that, initialize the interpreter just once, and uninitialize it only at the end of the application. -- Gabriel Genellina From vinay_sajip at yahoo.co.uk Fri Jan 19 16:32:50 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 19 Jan 2007 13:32:50 -0800 Subject: My first try using logger didn't work. Why? References: <1169221734.071338.107190@11g2000cwr.googlegroups.com> <1169224835.820468.316040@v45g2000cwv.googlegroups.com> <1169233154.076956.231540@q2g2000cwa.googlegroups.com> <1169233925.571841.75480@a75g2000cwd.googlegroups.com> Message-ID: <1169242370.384356.156340@11g2000cwr.googlegroups.com> CedricCicada at gmail.com wrote: > Vinay (or anybody else), > > Well, now that logging is working, how do I stop it from working? > > I'm developing in PythonWin. When I run my test script, I get one > message. When I run it a second time, I get two, a third time gets me > three, and so on. > > I feel like the Sorceror's Apprentice! > > Rob The way to avoid this is to only call addHandler() once in your script. PythonWin imports logging and keeps it in memory (something that wouldn't happen if you ran the script repeatedly from the command-line), so adding a handler every time results in multiple handlers logging to the same event sink (e.g. NT Event Log). So you need to use a flag to indicate whether initialisation has already happened once, and avoid doing it again. I'm not sure of the best way of doing this, since I don't know exactly how your app is set up: if there's no more natural way, you could get a Logger instance and see if it has any handlers added, before creating a new one and adding it. This could be done by checking len(logger.handlers) == 0 for that logger. Best regards, Vinay Sajip From igouy at yahoo.com Sat Jan 20 13:55:11 2007 From: igouy at yahoo.com (Isaac Gouy) Date: 20 Jan 2007 10:55:11 -0800 Subject: Py 2.5 on Language Shootout In-Reply-To: <1169275613.093797.67320@v45g2000cwv.googlegroups.com> References: <1169242255.023147.310570@38g2000cwa.googlegroups.com> <1169258423.824108.228810@s34g2000cwa.googlegroups.com> <1169265192.891496.194550@q2g2000cwa.googlegroups.com> <1169275613.093797.67320@v45g2000cwv.googlegroups.com> Message-ID: <1169319310.996003.147970@38g2000cwa.googlegroups.com> pgarrone at acay.com.au wrote: > Isaac Gouy wrote: > > pgarrone at acay.com.au wrote: > > > Alioth is a great site for selecting the language in which to implement > > > primitives. Usually it's C. > > > > And for selecting a language for which you might need to implement > > primitives in C :-) > > Well if you like C so much, just do it in C. ":-)" iirc I've never written a program in C or C++ (although I may have fixed one or two that someone else wrote). > > > > > > > > > Two of the alioth benchmarks, Partial-sums and Spectral-norm, could be > > > done using Numarray, or would be done with Numarray if most of the > > > program was in Python and there was a need to implement a similar > > > numerical procedure. The speed would be up near the compiled language > > > benchmarks. However the specific wording of these benchmarks prohibits > > > this approach. Spectral-norm must pretend the dataset is infinite, and > > > Partial-sums has to be implemented in a simple dumb loop. > > > > And we wouldn't use a na?ve recursive algorithm to find fibonnaci > > numbers ... unless we were interested in recursion for its own sake. > > > > Maybe the author of spectral-norm was interested in function calls. > > Maybe the author of partial-sums was interested in simple dumb loops > > and simple dumb Math. > > I am not disputing this. I think you take my point though. I'm confident in my ability to misunderstood the point someone intended to make - I think your point is some variation on 'we wouldn't write the program like that' '"real-world" programs aren't like that'. > > > > > > > > Looking over the benchmarks, one gains the impression that Python is a > > > slow language. > > > > What does that even mean - a slow language? > > > > The alioth benchmarks provide a set of numbers by which > languages may be compared. Unless we notice that sometimes there's more than one language implementation for some languages; unless we notice that sometimes there's more than one program for the same language implementation. (Unless we read the bold text on the homepage.) > > > > > > My first serious Python programming exercise involved converting a 900 > > > line Bash Shell program to a 500 line Python program, with a speedup > > > factor of 17. Using Python allowed an OO structure and advanced > > > containers, meaning the program was more maintainable and portable, > > > which were the main aims of the exercise. The speedup was a surprising > > > and welcome side benefit. I think it was mosly because the Python > > > byte-code interpreter is probably an order of magnitude faster than > > > Bash's direct interpretation, and because in Python system calls to > > > recurse directories and create symbolic links were not forked to > > > separate processes. In fact I would guess that the overall speed of the > > > Python program would be little less than a C program, given that most > > > of the time would be spent in system calls. > > > > /I would guess/ > > I don't have the time, or interest, to recode it in C to find out. > In reality the choice would be C++ because of OO and STL. > Perhaps traversing and linking a tree containing about 1000 files would > not > take a full second. I might be wrong. All i know is, its a lot faster > than Bash. > > > > > > Its almost possible to make a large Python program arbitrarily fast by > > > profiling it and implementing slow bits as primitives. Size is probably > > > of greater concern. > > > > We could read that simply as - /it's not possible/ to make a large > > Python program arbitrarily fast. Is that what you meant? > > No. I meant that if my Python program is too big in terms of its > execution memory > requirements, then that would be a difficult issue to deal with. Rather > than > optimizing execution hotspots, I might have to use another language. > > Cheers, > P.S. Alioth is a great site. From tundra at tundraware.com Tue Jan 9 19:25:10 2007 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 09 Jan 2007 18:25:10 -0600 Subject: tkinter Ignoring Certain Key Presses? Message-ID: <8cod74-a361.ln1@eskimo.tundraware.com> I am having trouble getting tkinter to recognize the following key presses- it seems to be ignoring them alltogether: Alt F1-F10: FreeBSD 4.x console running XFree86 and cygwin/X (current) connected to same machine. Works on cygwin/X local to Windows machine and native Windows. Ctl 1-5: FreeBSD, Cygwin/X (local or connected to FreeBSD), Windows - i.e. Does not seem to work anywhere. Ideas anyone? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From fdelente at mail.cpod.fr Fri Jan 26 12:08:03 2007 From: fdelente at mail.cpod.fr (Fabrice DELENTE) Date: 26 Jan 2007 17:08:03 GMT Subject: python+ncurses: I can't display accents Message-ID: <45ba3573$0$16171$426a34cc@news.free.fr> Hello. I'm trying to display french characters (? -- that's e grave -- or ? -- agrave) in python 2.5, with the ncurses wrapper that comes it, and I can't. My locale is set correctly (fr_FR.iso885915), and my terminal (rxvt-unicode) is able to display those chars. What am I missing? Thanks. -- Fabrice DELENTE From akhavr at kds.com.ua Tue Jan 16 08:28:41 2007 From: akhavr at kds.com.ua (Andrey Khavryuchenko) Date: Tue, 16 Jan 2007 15:28:41 +0200 Subject: html + javascript automations = [mechanize + ?? ] or something else? References: <1168920755.599905.97250@a75g2000cwd.googlegroups.com> <513oovF1ib4g4U1@mid.uni-berlin.de> Message-ID: Diez, "DBR" == Diez B Roggisch wrote: >> Up to my knowledge, there no way to test javascript but to fire up a >> browser. >> >> So, you might check Selenium (http://www.openqa.org/selenium/) and its >> python module. DBR> No use in that, as to be remote-controlled by python, selenium must be run DBR> on the server-site itself, due to JS security model restrictions. Sorry, missed 'spider' word in the original post. -- Andrey V Khavryuchenko Software Development Company http://www.kds.com.ua/ From codecraig at gmail.com Tue Jan 16 11:19:19 2007 From: codecraig at gmail.com (abcd) Date: 16 Jan 2007 08:19:19 -0800 Subject: Search Queue In-Reply-To: <1168962673.664083.146220@38g2000cwa.googlegroups.com> References: <1168960945.787822.286690@s34g2000cwa.googlegroups.com> <1168962673.664083.146220@38g2000cwa.googlegroups.com> Message-ID: <1168964356.125262.45110@v45g2000cwv.googlegroups.com> Yea basically I need Queue like functionality with the ability to search for a particular instance in it. I guess I could just use a list and search it as needed. Thanks. From liam_jones at yahoo.com Wed Jan 10 10:22:46 2007 From: liam_jones at yahoo.com (liam_jones at yahoo.com) Date: 10 Jan 2007 07:22:46 -0800 Subject: Using Excel With Python Message-ID: <1168442566.323237.152740@i39g2000hsf.googlegroups.com> I'm very new to Python, well IronPython to precise, and have been having problems when using Excel. The problem I'm having is the closing of my Excel object. I'm able to successfully quit the Excel Application that I create, but when I open a Workbook in the Application I can't successfully Quit Excel (by this I mean I can quit it, but the Excel process isn't getting killed and I have to manually go this through Task Manager). I've given a sample of code below to hopefully make things clearer. I've then given all of the information I think might be useful (sorry if I've gone over the top!). import System import clr from System.Data import * from System.Web import * from System.Web.UI import * from clr import * clr.AddReference("Microsoft.Office.Interop.Word") clr.AddReference("Microsoft.Office.Interop.Excel") clr.AddReference("Microsoft.Office.Interop.PowerPoint") clr.AddReference("Office") from Microsoft.Office.Interop.Word import ApplicationClass as WordApplication from Microsoft.Office.Interop.Excel import ApplicationClass as ExcelApplication from Microsoft.Office.Interop.PowerPoint import ApplicationClass as PowerPointApplication from Microsoft.Office.Interop.Word import WdReplace from Microsoft.Office.Interop.Excel import XlCellType from Microsoft.Office.Interop.Excel import XlSearchDirection from System.Type import Missing from System import GC missing = Missing FileLocation = "C:\\test.xls" ExcelApp = ExcelApplication() workbook= None workbook = ExcelApp.Workbooks.Open(FileLocation, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing) workbook.Save() workbook.Close(SaveChanges=0) ExcelApp.Quit() workbook = None ExcelApp = None GC.Collect() GC.WaitForPendingFinalizers() I've simpilised the code by taking all of my Workbook processing from it and the problem is still occurring. As I said above if I don't create the workbook, then ExcelApp closes as expected (there are no stray processes). I've read many articles and postings over the last few days regarding this, but have had no luck with anything I've seen, examples of this are now given. I've tried adding the below code, but with no luck. ExcelApp.ActiveWorkbook.Save() ExcelApp.ActiveWorkbook.Close(SaveChanges=0) ExcelApp.Workbooks.Close() I've also tried the below (again with no luck). System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook) System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp) And, I've also tried the following (again with no luck!). del(workbook) del(excelApp) It may seem strange using the Garbage Collector (well I wouldn't have thought about using it here), but it was something that I read about using for code written in C#. I've tried the code in C# (what I normally write in) and all works fine, the only real difference is that I'm setting the objects to NULL in C# and None here in IronPython - Does this make a difference, is there something else I should be setting it to? The Workbook object HAS to be set to NULL in C#, it's then picked up by the Garbage Collector and the task disappears from the Task Manager. I did think of killing the actual EXCEL.EXE process at the end of my code, but there might be several versions of the containing application running on the same box, so I can't kill all of the Excel processes. As I said above, I'm sorry if I've gone over the top in my description. Any ideas or pointers would be greatly appreciated as I'm now going round in circles. Thanks in advance. Rgds Liam From mensanator at aol.com Tue Jan 9 01:42:04 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Jan 2007 22:42:04 -0800 Subject: Colons, indentation and reformatting. (2) In-Reply-To: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> Message-ID: <1168324924.666258.80030@42g2000cwt.googlegroups.com> Paddy wrote: > I was just perusing a Wikipedia entry on the "off side rule" at > http://en.wikipedia.org/wiki/Off-side_rule . > It says that the colon in Python is purely for readability, and cites > our FAQ entry > http://www.python.org/doc/faq/general.html#why-are-colons-required-fo... > . > However, near the top of the Alternatives section, it states that for C > type, curly braces using languages: > "An advantage of this is that program code can be automatically > reformatted and neatly indented without fear of the block structure > changing". > > Thinking about it a little, it seems that a colon followed by > non-indented code that has just been pasted in could also be used by a > Python-aware editor as a flag to re-indent the pasted code. How would you re-indent this? if x>0: print x > > Tell me it is not so, or I will be editing the Wikipedia page I think. > > - Paddy. From petercable at gmail.com Sun Jan 14 09:48:17 2007 From: petercable at gmail.com (petercable at gmail.com) Date: 14 Jan 2007 06:48:17 -0800 Subject: template engine In-Reply-To: References: Message-ID: <1168786097.581896.281030@q2g2000cwa.googlegroups.com> > > > $title > > > #if user > hello $user/name > #else > hello guest > #endif > > This example code would work in cheetah with only 2 changes... www.cheetahtemplate.org Pete From roland.hedberg at adm.umu.se Wed Jan 3 06:22:07 2007 From: roland.hedberg at adm.umu.se (Roland Hedberg) Date: Wed, 03 Jan 2007 12:22:07 +0100 Subject: import order or cross import In-Reply-To: References: Message-ID: <459B91DF.6040807@adm.umu.se> Jussi Salmela wrote: > Roland Hedberg kirjoitti: >> I'm having a bit of a problem with import. >> >> I'm writing a marshalling system that based on a specification will >> create one or more files containing mostly class definitions. > Maybe I'm missing something, but why is the class BaseColor in file > ONE.py and not in TWO.py? This has to do with the how the specifications that the marshallings system works with are structured. And it is therefor not something I can control. -- Roland From steven.bethard at gmail.com Wed Jan 17 14:07:38 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 17 Jan 2007 12:07:38 -0700 Subject: A note on heapq module In-Reply-To: References: <1168968284.777451.170710@m58g2000cwm.googlegroups.com> Message-ID: <4Yidnf9NFKFm7jPYnZ2dnUVZ_u3inZ2d@comcast.com> Antoon Pardon wrote: > For me, your class has the same drawback as the heappush, heappop > procedurers: no way to specify a comparision function. Agreed. I'd love to see something like ``Heap(key=my_key_func)``. STeVe From deets at nospam.web.de Fri Jan 19 06:07:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 Jan 2007 12:07:46 +0100 Subject: Why this script can work? References: <51bjskF1jbnhrU1@mid.uni-berlin.de> Message-ID: <51bn42F1jn1paU2@mid.uni-berlin.de> Jm lists wrote: > Thanks for all the helps. > I'm not habitual for this usage of 'else',other languages seem don't > support this syntax. > i.g,writting the codes below by Perl would get an error: I personally consider this part of python also somewhat obscure. But I just don't use it and don't bother. Diez From frank at chagford.com Tue Jan 9 02:14:54 2007 From: frank at chagford.com (Frank Millman) Date: 8 Jan 2007 23:14:54 -0800 Subject: Recommendations (or best practices) to define functions (or methods) In-Reply-To: <50gqeoF1dnbdqU1@mid.uni-berlin.de> References: <1168219279.578866.217580@s80g2000cwa.googlegroups.com> <50ehtmF1fh46iU1@mid.uni-berlin.de> <1168262998.765702.38760@i15g2000cwa.googlegroups.com> <50gqeoF1dnbdqU1@mid.uni-berlin.de> Message-ID: <1168326894.875890.174350@i15g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > > If you don't handle the exceptions, exactly what you seem to want will > happen - you will see the interpreter stop, and why. > > All you did was to take the unpythonic (and un-javaic and un-C#ic) road > to transform an exception to a returncode. But that has nothing to do > with actually _dealing_ with the error. Instead, it just makes it more > likely that you _don't_ deal with it, as a return-code evaluation might > be more easily forgotten, and turn out with a program that will be > error-prone, as it continues to run even when the preconditions for > pieces of code aren't met anymore. > I absolutely agree with this. I will describe my particular experience, in the hope that it will make it clear to vizcayno just how important this is. My app does a lot of database/user interaction. I read a row from the database, display it to the user, allow the user to change the value of various columns, and write it back again. I had a routine which validated whether the user input was acceptable based on various business rules. If the input was good, it would update the internal value of the column and return True, else it would not update the value and return False. I would check the return code and, if False, display an error message and reprompt the user for input. What could go wrong with that? Well, during the execution of the program, I also update the values of various columns programatically. I call the same routine, but I did not check the return code, as it would add a lot of extra checks, and as it was program generated it would always pass a valid value. This was true 99.9% of the time, but occasionally, due to a program error, I would pass an invalid value. The validation routine correctly did not update the internal value, and returned False, but as I did not check this I continued merrily on my way. Later on when I found that the value had not changed, it took me a long time to trace the error. I suffered like this for quite a long time before the light bulb went off, based on a thread on c.l.py. Now I do it like this. The validation routine performs the same function, but instead of returning True/False, it raises ValueError if the check fails. Where I previously tested the return code, I now have a try/except clause, which does the same as before. The big difference is, what happens if I programmatically pass an invalid value? Where before, the error would pass silently, now my program aborts, with the traceback, which is exactly what I want. Frank Millman From seandavi at gmail.com Thu Jan 11 07:27:06 2007 From: seandavi at gmail.com (Sean Davis) Date: 11 Jan 2007 04:27:06 -0800 Subject: Read from database, write to another database, simultaneously In-Reply-To: <9ihph.72$fo1.64@newsfe03.lga> References: <1168468649.437848.311800@o58g2000hsb.googlegroups.com> <50l9dlF1fuc1sU1@mid.individual.net> <9ihph.72$fo1.64@newsfe03.lga> Message-ID: <1168518426.111465.290430@o58g2000hsb.googlegroups.com> On Jan 10, 9:27 pm, johnf wrote: > Bjoern Schliessmann wrote: > > Sean Davis wrote: > > >> The author of one of the python database clients mentioned that > >> using one thread to retrieve the data from the oracle database and > >> another to insert the data into postgresql with something like a > >> pipe between the two threads might make sense, keeping both IO > >> streams busy. > > > IMHO he's wrong. Network interaction is quite slow compared with CPU > > performance, so there's no gain (maybe even overhead due to thread > > management and locking stuff). That's true even on multiprocessor > > machines, not only because there's almost nothing to compute but > > only IO traffic. CMIIW. > > > Using multiplexing, you'll get good results with simple code without > > the danger of deadlocks. Have a look at asyncore (standard library) > > or the Twisted framework -- personally, I prefer the latter. > > > Regards, > > Sean you can't win - everyone has a different idea! You need to explain > that oracle has millions of records and it's possible to a pipe open to > feed the Postgres side. > > One thing I didn't get - is this a one time transfer or something that is > going to happen often. Yes, some detail about the problem is definitely in order! We have a collaborator that is going to maintain a large genome database that is a component of a postgresql database that we currently maintain. There are going to be consumers of the oracle data using both mysql and postgresql. The oracle database is LARGE with around 100,000,000 rows spread over some 50-70 tables in multiple schemas. The idea is that as publicly available data (from various datasources on the web) become available, the oracle team will update the oracle database, doing all the parsing and necessary data cleanup of the raw data. We then want to be able to update postgres with these oracle data. So the process may be done only once per month on some tables, but as often as once a day on others. As for the specifics, Oracle data is going to be coming in as a DB-API 2 cursor in manageable chunks (and at a relatively slow pace). On the postgres loading side, I wanted to use the pscycopg2 copy_from function, which expects an open file-like object (that has read and readline functionality) and is quite fast for loading data. Note the disconnect here--Oracle is coming in in discrete chunks, while postgresql is looking for a file object. I solved this problem by creating a temporary file as an intermediary, but why wait for Oracle to finish dumping data when I can potentially be loading into postgres at the same time that the data is coming in? So, I am actually looking for a solution to this problem that doesn't require an intermediate file and allows simultaneous reading and writing, with the caveat that the data cannot all be read into memory simultaneously, so will need to be buffered. I hope that clarifies things. Thanks, Sean From steve at REMOVE.THIS.cybersource.com.au Fri Jan 19 07:00:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 19 Jan 2007 23:00:45 +1100 Subject: Determining when a file is an Open Office Document References: Message-ID: On Fri, 19 Jan 2007 12:22:04 +1100, Ben Finney wrote: > tubby writes: > >> Silly question, but here goes... what's a good way to determine when >> a file is an Open Office document? I could look at the file >> extension, but it seems there would be a better way. > > Yes, the name of a file may be useful for communicating with humans > about that file's intended use, but is a lousy, unreliable way to make > a definite statement about the actual contents of the file. > > The Unix 'file' command determines the type of a file by its contents, > not its name. This functionality is essentially a database of "magic" > byte patterns mapping to file types, Ah, another lousy, unreliable way to make a definite statement about the actual contents of a file. Looking at magic bytes inside a file is hardly bullet-proof (although file seems to be moderately reliable in practice, at least under Linux). Simple example: is the file consisting of two bytes "x09x0A" meant to be a text file with a tab and a newline, or a binary file consisting of a single two-byte int? There's no way to tell just from the contents. It's a circular problem: to be sure what the file is ("it's a two-byte int") one has to understand the contents ("the integer 2305") -- but you can only understand the contents if you know what the file is. There are only two ways out of this vicious circle: (1) Have the creator of the file unambiguously label it. Some file systems associate file-type metadata to files (e.g. Classic Apple Macintosh did that), but sadly the main file systems in use today do not. (2) Make an educated guess from various heuristics and conventions. The old DOS 8.3 naming system is one such convention, and modern operating systems tend to follow it. The Unix "file" utilities database of magic bytes is such a heuristic. -- Steven. From sjmachin at lexicon.net Tue Jan 9 19:08:25 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Jan 2007 11:08:25 +1100 Subject: pyExcelerator big integer values In-Reply-To: <1168349446.381187.65810@11g2000cwr.googlegroups.com> References: <1168349446.381187.65810@11g2000cwr.googlegroups.com> Message-ID: <45a42e7c@news.eftel.com> On Jan 10, 12:30 am, "Gacha" wrote: > I use pyExcelerator to import some data from xml file. One column > contains integer values like: > 4750456000708 > 4750456000715 > 4750456000333 I think you must mean "xls", not "xml". Those are integers only in the mathematical sense. The value of each number cell in an XLS file is treated as a 64-bit floating point number. How do you know that they are whole numbers? What you see on-screen with Excel etc is not necessarily what you've got. If you format your column with 0 decimal places, 4750456000708.123 will show as 4750456000708 However, whether they are whole numbers or not, you still have a problem on the Python side: > ... > But when I do import the pyExcelerator converts them to something like > this: > 4.7504560002e+12 > 4.7504560007e+12 > 4.7504560007e+12 > 4.7504560003e+12 No it doesn't. It converts the XLS file data to Python float type -- 64-bit floating point numbers. There is no loss of precision. What you are seeing are different visual presentations of the *same* object. Perhaps this will explain: | >>> for x in (4750456000708.0, 4750456000708.123): | ... print x, str(x), repr(x) | ... | 4.75045600071e+012 4.75045600071e+012 4750456000708.0 | 4.75045600071e+012 4.75045600071e+012 4750456000708.123 | >>> > > How I understand it's because the integer value is too big. A 12-digit integer is too big for what? > If the type > of the items was string, then all would be fine, but I can't control > the file content. > > The question is, how can I import the integers in normal format. The answer is, there is no such thing as "normal format". Normality, like beauty, is in the eye of the beholder. You have a value, how you format it for display depends on your purpose. If what you want is to see the most precise representation of what you've got, then use repr(). HTH, John From tjreedy at udel.edu Thu Jan 11 02:30:02 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Jan 2007 02:30:02 -0500 Subject: Urgent Openings with the World's Leading Software Company !!! References: <1168499359.596195.286240@77g2000hsv.googlegroups.com> Message-ID: (cc'ed) "Software Hiring" wrote Hi Vamsi. Recruiting for Microsoft gives you no extra right to spam comp.lang.python with off-topic messages. There are thousands of other software groups that might like to do the same but with a couple of exceptions a year, they all desist for the greater common good. Please do likewise. tjr ps. A Microsoft recruiter using gmail is a puzzle, but that is a different off-topic issue. From could.net at gmail.com Sun Jan 7 04:05:55 2007 From: could.net at gmail.com (Frank Potter) Date: 7 Jan 2007 01:05:55 -0800 Subject: where is python on linux? Message-ID: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> I installed fedora core 6 and it has python installed. But the question is, where is the executable python file? I can't find it so I come here for help. I want to config pydev for eclipse and I need to know where the ececutable python file is. Thank you! From s.mientki at id.umcn.nl Wed Jan 31 10:44:11 2007 From: s.mientki at id.umcn.nl (stef) Date: Wed, 31 Jan 2007 16:44:11 +0100 Subject: another newbie question: why should you use "*args" ? In-Reply-To: References: Message-ID: <4b4a3$45c0b94c$83aef404$20934@news1.tudelft.nl> Eugene Antimirov wrote: > stef wrote: > >> # method 2 >> def chunk_plot(self, list): >> for i in range ( len(list) ): >> .... do something > > > And one note more. Just to be more pythonic you shouldn't use form > range(len(blabla)). Instead use: > > for i in list: > ....blabla... > > I would love that, but please tell me how (I need an integer counter for something else too): def chunk_plot(*args): if len(args) == 1: list = args[0] else: list = args color = ['g','r','b','y','m'] plot ( list[0], color[0]) hold (True) for i in range ( 1, len(list) ): plot ( list[i], color[i] ) cheers, Stef From raedfarid at gmail.com Fri Jan 19 20:37:46 2007 From: raedfarid at gmail.com (Raed) Date: 19 Jan 2007 17:37:46 -0800 Subject: nice one Message-ID: <1169257066.102313.287240@11g2000cwr.googlegroups.com> Take a break and try this cool game, this test is apporved by Peugeot for car parking http://www.pixelswall.com/Download/peugeot/peugeot.html Anton www.pixelswall.com From ggg at zzz.it Wed Jan 31 12:05:14 2007 From: ggg at zzz.it (deelan) Date: Wed, 31 Jan 2007 18:05:14 +0100 Subject: subway In-Reply-To: References: Message-ID: <3%3wh.17848$K8.7787@news.edisontel.com> Daniel Nogradi wrote: > Does anyone know what has happened to the codebase of the subway > project? It seems the whole project has been shut down leaving no > trace of the code on net but I would be very happy to see it, > apparently it had some cool features that would be fun to look at. > Does anyone have access to the code and/or is willing to make it > publically available? Try: -- d. From bignose+hates-spam at benfinney.id.au Fri Jan 19 20:39:40 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 Jan 2007 12:39:40 +1100 Subject: OT Annoying Habits References: <2BBAEE949D384D40A2B851287ADB6A4304595A9C@eugsrv400.psc.pscnet.com> <2BBAEE949D384D40A2B851287ADB6A4304595A9C@eugsrv400.psc.psc net.com> <7.0.1.0.0.20070119205257.033b9310@yahoo.com.ar> Message-ID: <87k5zi4gtf.fsf@benfinney.id.au> Gabriel Genellina writes: > At Friday 19/1/2007 18:43, Carroll, Barry wrote: > > >Secondly, can someone point me to the Standard Usenet Convention > >that mandates against top-posting. This is not sarcasm; I would > >really like to see it. > > There are some guidelines, like RFC 1855 (not a real standard, or > enforced in any way): They *are* enforced: by social convention. In other words, they're codified recordings of behaviour the society prefers. To the extent that's true, they are enforced by that society. -- \ "I met my girlfriend in Macy's; she was buying clothes, and I | `\ was putting Slinkies on the escalators." -- Steven Wright | _o__) | Ben Finney From mattheww at chiark.greenend.org.uk Wed Jan 24 13:24:05 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 24 Jan 2007 18:24:05 +0000 (GMT) Subject: Thoughts on using isinstance References: <1169642310.421573.129420@j27g2000cwj.googlegroups.com> <1169647934.219682.144390@j27g2000cwj.googlegroups.com> <1169656371.689791.216360@v33g2000cwv.googlegroups.com> Message-ID: abcd wrote: > Well my example function was simply taking a string and printing, but > most of my cases would be expecting a list, dictionary or some other > custom object. Still propose not to validate the type of data being > passed in? There are many people here who will indeed suggest that you're still best off not validating. There are various points to consider: - Not adding the validation code saves a certain amount of effort. - Not adding the validation code avoids one source of possible bugs. - Not adding the validation code can make your code more readable, in that there's that much less uninteresting code for your readers to skip before they get to the meat. - Adding the validation code can make your code more readable, in that it can be clearer to the readers what kind of values are being handled. - If you validate, you can raise an exception from the start of your function with a fairly explicit message. If you don't validate, you're likely to end up with an exception whose message is something like 'iteration over non-sequence', and it might be raised from some function nested several levels deeper in. The latter can be harder for the user of your function to debug (in particular, it may not be easy to see that the problem was an invalid parameter to your function rather than a bug in your function itself, or corrupt data elsewhere in the system). - If you don't validate, your function will accept anything that behaves sufficiently like a list/dictionary/custom-object for its purposes. You may consider this an advantage or a disadvantage. To some extent it depends on the circumstances in which the function is used: if someone passes a not-quite-a-file (say) to a function expecting a file, is it more likely that this is because of a subtle bug that they'll be pleased to learn about early, or that they wanted the function to 'do the obvious thing' with it? - In particular, suppose your function expects a list and someone passes a string when they should have passed a list containing only that string. If you don't validate, the function is likely to process the string the same way as it would process a list containing a number of single-character strings. This might well lead to your program apparently completing successfully but giving the wrong result (which is usually the kind of error you most want to avoid). - If the function is going to be maintained together with its callers (rather than being part of the public interface to a library, say), then validation code is less likely to get in the way, because it should be easy to relax the checks if that turns out to be convenient. -M- From gagsl-py at yahoo.com.ar Thu Jan 4 21:02:16 2007 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 04 Jan 2007 23:02:16 -0300 Subject: pow() works but sqrt() not!? In-Reply-To: References: <1167899693.759071.51450@31g2000cwt.googlegroups.com> Message-ID: <7.0.1.0.0.20070104225605.038f7d40@yahoo.com.ar> At Thursday 4/1/2007 10:12, siggi wrote: >Thanks for the explanation. I am astonished what an interpreted language is >able to do! Python is as interpreted as Java. Its numerical capabilities are more or less independent of this fact, I'd say. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From Barry.Carroll at psc.com Wed Jan 17 14:34:39 2007 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 17 Jan 2007 11:34:39 -0800 Subject: *POLL* How many sheeple believe in the 911 fairy tale and willingto accept an Orwellian doublespeak and enslavement world ? Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595A82@eugsrv400.psc.pscnet.com> > -----Original Message----- > From: st911 at rock.com [mailto:st911 at rock.com] > Sent: Wednesday, January 17, 2007 11:12 AM > To: python-list at python.org > Subject: Re: *POLL* How many sheeple believe in the 911 fairy tale and > willingto accept an Orwellian doublespeak and enslavement world ? > > > David Bostwick wrote: > > In article <1169058752.659674.6680 at s34g2000cwa.googlegroups.com>, > "Robert Hicks" wrote: > > >Please, none of the real facts points to anything else except what > > >actually happened. Two planes hit two towers and they came down. > > > > > > > You're talking to the wind. This is a conspiracy precisely because > people > > deny the crackpots. Denial of their "evidence" proves that there is a > > coverup. > > Quite the contrary. A million dollar reward was posted to come with a > consistent > explanation of the SERIOUS anomalies involved on that day. Professor > Steven > Jones research on Thermate is an EYE OPENER. He is a BRILLIANT > physicists. > > > Logic is not involved, only belief that doesn't respond to dissenting > evidence. > > Indeed, the 19 hijacker theory is a fairy tale based on illogical > forensic investigation. > As for dissent, Bush is on video record to utter, "Lets not tolerate > any conspiracy theories." > The video is floating on the internet for you to see if you had the IQ > to search for it. > Ladies and Gentlemen: PLEASE take this discussion to a more appropriate forum. There are many forums where people will be happy to debate this: physics, firefighting, metallurgy, geopolitics, etc. This forum is about the Python programming language. Let's keep it that way. Regards, Barry barry.carroll at psc.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From nmm1 at cus.cam.ac.uk Thu Jan 11 05:24:53 2007 From: nmm1 at cus.cam.ac.uk (Nick Maclaren) Date: 11 Jan 2007 10:24:53 GMT Subject: Maths error References: <50fudtF1g1nplU1@mid.individual.net> Message-ID: In article , Tim Peters writes: |> |> Sure. Possibly even most. Short of writing a long & gentle tutorial, |> can that be improved? Alas, most people wouldn't read that either <0.5 |> wink>. Yes. Improved wording would be only slightly longer, and it is never appropriate to omit all negative aspects. The truth, the whole truth and nothing but the truth :-) |> Worse, I expect most people have no real idea of that there's a possible |> difference between internal and external representations. This is often |> given as a selling point for decimal arithmetic: it's WYSIWYG in ways |> binary fp can't be (short of inventing power-of-2 fp representations for |> I/O, which few people would use). Right. Another case when none of the problems show up on dinky little examples but do in real code :-( |> > A lot of very well-respected numerical analysts said that larger bases |> > led to a faster build-up of error (independent of the precision). My |> > limited investigations indicated that there was SOME truth in that, |> > but it wasn't a major matter; I never say the matter settled |> > definitively. |> |> My point was that 28 decimal digits of precision is far greater than |> supplied even by 64-bit binary floats today (let alone the smaller sizes |> in most-common use back in the 60s and 70s). "Pollution" of low-order |> bits is far less of a real concern when there are some number of low- |> order bits you don't care about at all. Yes, but that wasn't their point. It was that in (say) iterative algorithms, the error builds up by a factor of the base at every step. If it wasn't for the fact that errors build up, almost all programs could ignore numerical analysis and still get reliable answers! Actually, my (limited) investigations indicated that such an error build-up was extremely rare - I could achieve it only in VERY artificial programs. But I did find that the errors built up faster for higher bases, so that a reasonable rule of thumb is that 28 digits with a decimal base was comparable to (say) 80 bits with a binary base. And, IN GENERAL, programs won't be using 128-bit IEEE representations. Given Python's overheads, there is no reason not to, unless the hardware is catastrophically slower (which is plausible). |> If you know a < b, doing |> |> c = a + (b-a)/2 |> |> instead of |> |> c = (a+b)/2 |> |> at least guarantees (ignoring possible overflow) a <= c <= b. As shown |> last time, it's not even always the case that (x+x)/2 == x in decimal fp |> (or in any fp base > 2, for that matter). Yes. Back in the days before binary floating-point started to dominate, we taught that as a matter of routine, but it has not been taught to all users of floating-point for a couple of decades. Indeed, a lot of modern programmers regard having to distort simple expressions in that way as anathema. It isn't a major issue, because our experience from then is that it is both teachable and practical, but it IS a way in which any base above 2 is significantly worse than base 2. Regards, Nick Maclaren. From ptmcg at austin.rr._bogus_.com Tue Jan 9 06:24:29 2007 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 9 Jan 2007 05:24:29 -0600 Subject: Colons, indentation and reformatting. (2) References: <1168323368.592642.314130@i15g2000cwa.googlegroups.com> <45a33a24$0$7658$4c368faf@roadrunner.com> <1168327796.187713.107530@38g2000cwa.googlegroups.com> Message-ID: <45a37b6d$0$5767$4c368faf@roadrunner.com> "Paddy" wrote in message news:1168327796.187713.107530 at 38g2000cwa.googlegroups.com... > > If this is not > the case then the user should be asked wether to re-indent the copy > block to be equal to, or de-dented w.r.t. the paste line indent prior > to pasting. > How would the user know this? Every dedent is ambiguous, since there is no punctuation to indicate it. -- Paul From inq1ltd at verizon.net Sun Jan 7 12:06:47 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Sun, 07 Jan 2007 12:06:47 -0500 Subject: where is python on linux? In-Reply-To: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> References: <1168160755.253030.132260@i15g2000cwa.googlegroups.com> Message-ID: <200701071206.48133.inq1ltd@verizon.net> on linux type: whereis python You should get a list of directories where all of python lives. jim-on-linux http:\\www.inqvista.com On Sunday 07 January 2007 04:05, Frank Potter wrote: > I installed fedora core 6 and it has python > installed. But the question is, where is the > executable python file? I can't find it so I > come here for help. I want to config pydev for > eclipse and I need to know where the ececutable > python file is. > Thank you! From george.sakkis at gmail.com Wed Jan 17 03:34:54 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 17 Jan 2007 00:34:54 -0800 Subject: How to determine what exceptions a method might raise? References: <12qq98ijkn5mld8@corp.supernews.com> Message-ID: <1169022894.357383.45950@a75g2000cwd.googlegroups.com> Ben Finney wrote: > Ed Jensen writes: > > > it would be handy if there was something I could do in the > > interactive interpreter to make it tell me what exceptions the file > > method might raise (such as IOError). > > For what purpose would this be handy? Surely the benefit of the > interactive interpreter is that you can simply try it out and *see* > what happens. > > But, in case it helps: Any code may raise any exception at any > time. This is a feature, since it encourages program that are tested > properly. That's a silly argument, really, unless perhaps you'd consider a box of pills that look like M&Ms a 'feature' since it encourages parents to hide them from their kids. A better answer would be along the lines of "yes, that would be nice to have but in general it's not possible in a dynamic language; that's the price you have to pay for leaving the static typing world". As for the OP's question, since file is a fixed builtin, I think it should be possible to know all the possible exceptions that can be raised; I'm not sure if it's clearly documented though. George